Kaydet (Commit) 943e06d4 authored tarafından Lei De Bin's avatar Lei De Bin

#119998# copy the VCLAuto from Symphony code base to AOO trunk.

More info, check here
http://wiki.services.openoffice.org/wiki/QA/vclauto
http://wiki.services.openoffice.org/wiki/Test_Refactor
Copy the testcommon
üst 4964a13d
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="source"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="output/class"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>testcommon</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
<?xml version="1.0"?>
<!--************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************ -->
<project basedir="." default="dist">
<property name="src" value="./source" />
<property name="out" value="output" />
<property name="classes" value="${out}/class" />
<property name="dist" value="${out}/class" />
<property name="jar.name" value="testcommon.jar" />
<target name="init">
<mkdir dir="${classes}" />
<mkdir dir="${dist}" />
<copy includeemptydirs="false" todir="${classes}">
<fileset dir="${src}">
<exclude name="**/*.java" />
</fileset>
</copy>
</target>
<target name="clean" description="Clean all output">
<delete dir="${classes}" />
<delete dir="${dist}" />
</target>
<target name="compile" depends="init">
<javac srcdir="${src}" destdir="${classes}" debug="on" source="1.6">
</javac>
</target>
<target name="dist" depends="compile">
<jar destfile="${dist}/${jar.name}" basedir="${classes}" excludes="*.jar"/>
</target>
</project>
#*************************************************************************
#
# Licensed Materials - Property of IBM.
# (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
# U.S. Government Users Restricted Rights:
# Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
#
#*************************************************************************
#**************************************************************
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#**************************************************************
PRJ=.
PRJNAME=testcommon
TARGET=testcommon
.INCLUDE : ant.mk
ALLTAR : ANTBUILD
\ No newline at end of file
tcomm testcommon : NULL
tcomm testcommon nmake - all tcomm_mkout NULL
..\%__SRC%\class\testcommon.jar %_DEST%\bin%_EXT%\testcommon.jar
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.openoffice.test.common;
public abstract class Condition {
/**
*
* @return true, if the condition is true. false, if it's not true.
*/
public abstract boolean value();
public boolean test(double iTimeout, double interval) {
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime < iTimeout * 1000) {
if (value())
return true;
try {
Thread.sleep((long) (interval * 1000));
} catch (InterruptedException e) {
}
}
return value();
}
public void waitForTrue(String message, double iTimeout, double interval) {
if (!test(iTimeout, interval)) {
throw new RuntimeException(message);
}
}
}
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.openoffice.test.common;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
/**
* Utilities related to the file system
*
*/
public class FileUtil {
private final static DateFormat FILENAME_FORMAT = new SimpleDateFormat("yyMMddHHmm");
private FileUtil(){
}
public static Document parseXML(String path) {
try {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setNamespaceAware(true);
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
return docBuilder.parse(path);
} catch (Exception e) {
return null;
}
}
public static String getStringByXPath(String xml, String xpathStr) {
Document doc = parseXML(xml);
if (doc == null)
return null;
try {
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile(xpathStr);
return (String) expr.evaluate(doc);
} catch (XPathExpressionException e) {
e.printStackTrace();
return null;
}
}
/**
* Update the given property in a properties file
* @param file the properties file path
* @param key the key
* @param value the value
*/
public static void updateProperty(String file, String key, String value) {
Properties map = new Properties();
map.put(key, value);
updateProperty(file, map);
}
/**
* Update the given properties in a properties file
* @param file the properties file path
* @param props properties updated
*/
public static void updateProperty(String file, Properties props) {
Properties properties = loadProperties(file);
properties.putAll(props);
storeProperties(file, properties);
}
/**
* Load a properties file to Properties class
* @param file the properties file path
* @return
*/
public static Properties loadProperties(String file) {
Properties properties = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
properties.load(fis);
} catch (IOException e) {
//System.out.println("Can't read properties file.");
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// ignore
}
}
}
return properties;
}
/**
* Store properties into a file
* @param file the properties file path
* @param properties the properties to be stored
*/
public static void storeProperties(String file, Properties properties) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
properties.store(fos, "Generated By PropertyFileUtils");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// ignore
}
}
}
}
/**
* Delete a property in a properties file
* @param file the properties file path
* @param key the key to be deleted
*/
public static void deleteProperty(String file, String key) {
Properties properties = loadProperties(file);
properties.remove(key);
storeProperties(file, properties);
}
/**
* Load a file as string
* @param file the file path
* @return
*/
public static String readFileAsString(String file) {
return readFileAsString(new File(file));
}
/**
* Load a file as string
* @param file the file path
* @return
*/
public static String readFileAsString(File file) {
StringBuffer strBuffer = new StringBuffer(10240);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
char[] buf = new char[1024];
int count = 0;
while ((count = reader.read(buf)) != -1) {
strBuffer.append(buf, 0, count);
}
} catch (IOException e) {
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
// ignore
}
}
return strBuffer.toString();
}
/**
* Find the first file matching the given name.
* @param dir The directory to search in
* @param name Regular Expression to match the file name
* @return
*/
public static File findFile(File dir, String name) {
if (!dir.isDirectory())
return null;
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
File ret = findFile(files[i], name);
if (ret != null)
return ret;
} else if (files[i].getName().matches(name)) {
return files[i];
}
}
return null;
}
/**
* Find the last file matching the given name.
* @param dir The directory to search in
* @param name Regular Expression to match the file name
* @return
*/
public static File findLastFile(File dir, String name) {
if (!dir.isDirectory())
return null;
File[] files = dir.listFiles();
File file = null;
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
File ret = findFile(files[i], name);
if (ret != null)
file = ret;
} else if (files[i].getName().matches(name)) {
file = files[i];
}
}
return file;
}
/**
* find the first file matching the given name.
* @param dirs The directories to search in. Use ';' separate each directory.
* @param name Regular Expression to match the file name
* @return
*/
public static File findFile(String dirs, String name) {
String[] directories = dirs.split(";");
for (String s : directories) {
File dir = new File(s);
if (!dir.exists())
continue;
File file = findFile(dir, name);
if (file != null)
return file;
}
return null;
}
/**
* find the last file matching the given name.
* @param dirs The directories to search in. Use ';' separate each directory.
* @param name Regular Expression to match the file name
* @return
*/
public static File findLastFile(String dirs, String name) {
String[] directories = dirs.split(";");
for (String s : directories) {
File dir = new File(s);
if (!dir.exists())
continue;
File file = findLastFile(dir, name);
if (file != null)
return file;
}
return null;
}
/**
* find the directory matching the given name.
* @param dir The directory to search in
* @param name Regular Expression to match the file name
* @return
*/
public static File findDir(String dir, String dirName) {
File[] files = new File(dir).listFiles();
for (int i = 0; i < files.length; i++) {
if (!files[i].isDirectory()) {
File ret = findFile(files[i], dirName);
if (ret != null)
return ret;
} else if (files[i].getName().matches(dirName)) {
return files[i];
}
}
return null;
}
public static void writeStringToFile(String filePath, String contents) {
FileWriter writer = null;
try {
File file = new File(filePath);
file.getParentFile().mkdirs();
writer = new FileWriter(file);
if (contents != null)
writer.write(contents);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException e) {
}
}
}
/**
* Appeand a string to the tail of a file
* @param file
* @param contents
*/
public static void appendStringToFile(String file, String contents) {
FileWriter writer = null;
try {
writer = new FileWriter(file, true);
writer.write(contents);
} catch (IOException e) {
System.out.println("Warning:" + e.getMessage());
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException e) {
}
}
}
/**
* Replace string in the file use regular expression
* @param file
* @param expr
* @param substitute
*/
public static void replace(String file, String expr, String substitute) {
String str = readFileAsString(file);
str = str.replaceAll(expr, substitute);
writeStringToFile(file, str);
}
/**
* Recursively copy all files in the source dir into the destination dir
* @param fromDirName the source dir
* @param toDirName the destination dir
* @return
*/
public static boolean copyDir(String fromDirName, String toDirName) {
return copyDir(new File(fromDirName), new File(toDirName), true);
}
/**
* Copy all files in the source dir into the destination dir
* @param fromDir
* @param toDir
* @param recursive
* @return
*/
public static boolean copyDir(File fromDir, File toDir, boolean recursive) {
if (!fromDir.exists() || !fromDir.isDirectory()) {
System.err.println("The source dir doesn't exist, or isn't dir.");
return false;
}
if (toDir.exists() && !toDir.isDirectory())
return false;
boolean result = true;
toDir.mkdirs();
File[] files = fromDir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory() && recursive)
result &= copyDir(files[i], new File(toDir, files[i].getName()), true);
else
result &= copyFile(files[i], toDir);
}
return result;
}
/**
* Copy a file
* @param fromFile
* @param toFile
* @return
*/
public static boolean copyFile(File fromFile, File toFile) {
if (!fromFile.exists() || !fromFile.isFile() || !fromFile.canRead()) {
System.err.println(fromFile.getAbsolutePath() + "doesn't exist, or isn't file, or can't be read");
return false;
}
if (toFile.isDirectory())
toFile = new File(toFile, fromFile.getName());
FileInputStream from = null;
FileOutputStream to = null;
try {
from = new FileInputStream(fromFile);
File p = toFile.getParentFile();
if (p != null && !p.exists())
p.mkdirs();
to = new FileOutputStream(toFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1)
to.write(buffer, 0, bytesRead);
return true;
} catch (IOException e) {
//Can't copy
e.printStackTrace();
return false;
} finally {
if (from != null)
try {
from.close();
} catch (IOException e) {
}
if (to != null)
try {
to.close();
} catch (IOException e) {
}
}
}
/**
* Copy a file
* @param fromFileName
* @param toFileName
* @return
*/
public static boolean copyFile(String fromFileName, String toFileName) {
return copyFile(new File(fromFileName), new File(toFileName));
}
/**
* Copy all the files under fromDirName to toDirName
* @param fromDirName
* @param toDirName
* @return
*/
public static boolean copyFiles(String fromDirName, String toDirName) {
boolean res = true;
File fromDir = new File(fromDirName);
if (!fromDir.exists() || !fromDir.isDirectory() || !fromDir.canRead()) {
System.err.println(fromDir.getAbsolutePath() + "doesn't exist, or isn't file, or can't be read");
return false;
}
File [] files = fromDir.listFiles();
for(int i=0; i<files.length; i++){
if(files[i].isDirectory()){
res = res && copyDir(fromDirName + "/" + files[i].getName(), toDirName + "/" + files[i].getName());
}
else
res = res && copyFile(fromDirName + "/" + files[i].getName(), toDirName + "/" + files[i].getName());
}
return res;
}
/**
* Delete a file
* @param file
* @return
*/
public static boolean deleteFile(File path) {
if (!path.exists())
return true;
if (path.isDirectory()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteFile(files[i]);
} else {
files[i].delete();
}
}
}
return path.delete();
}
public static boolean deleteFile(String path) {
return deleteFile(new File(path));
}
public static boolean fileExists(String file) {
return new File(file).exists();
}
/**
* Get the extension name of a file
* @param file
* @return
*/
public static String getFileExtName(String file) {
if (file == null)
return null;
int i = file.lastIndexOf('.');
if (i < 0 && i >= file.length() - 1)
return null;
return file.substring(i+1);
}
/**
* Get the file's size
* @param file
* @return KB
*/
public static long getFileSize(String filePath){
long totalSize = 0;
FileInputStream f = null;
File file = new File(filePath);
try {
f = new FileInputStream(file);
totalSize = f.available();
f.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return totalSize/1000;
}
/**
* Get the folder's size
* @param folder's path
* @return Kb
*/
public static long getFolderSize(String dir){
long totalSize = 0;
File[] files = new File(dir).listFiles();
for(int i=0; i<files.length; i++){
if(files[i].isDirectory())
totalSize = totalSize + getFolderSize(files[i].getAbsolutePath())*1000;
else
totalSize = totalSize + files[i].length();
}
return totalSize/1000;
}
/**
* unzip file to the unzipToLoc
* @param folder's path
* @return Kb
*/
public static void unzipFile(String unzipfile, String unzipDest){
try {
File dest = new File(unzipDest);
ZipInputStream zin = new ZipInputStream(new FileInputStream(unzipfile));
ZipEntry entry;
//Create folder
while ( (entry = zin.getNextEntry()) != null){
if (entry.isDirectory()) {
File directory = new File(dest, entry.getName());
if (!directory.exists())
if (!directory.mkdirs())
System.exit(0);
zin.closeEntry();
}
if (!entry.isDirectory()) {
File myFile = new File(entry.getName());
FileOutputStream fout = new FileOutputStream(unzipDest + "/" + myFile.getPath());
DataOutputStream dout = new DataOutputStream(fout);
byte[] b = new byte[1024];
int len = 0;
while ( (len = zin.read(b)) != -1) {
dout.write(b, 0, len);
}
dout.close();
fout.close();
zin.closeEntry();
}
}
}
catch (IOException e) {
e.printStackTrace();
System.out.println(e);
}
}
public static File getUniqueFile(File dir, String prefix, String suffix) {
String name = prefix + "." + FILENAME_FORMAT.format(new Date()) + ".";
for (int i = 0; i < Integer.MAX_VALUE; i++) {
File file = new File(dir, name + i + suffix);
if (!file.exists()) {
return file;
}
}
return null;
}
public static File getUniqueFile(String dir, String prefix, String suffix) {
return getUniqueFile(new File(dir), prefix, suffix);
}
public static File download(String urlString, File output) {
InputStream in = null;
OutputStream out = null;
System.out.println("[Vclauto] Download '" + urlString + "'");
try {
URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
int totalSize = urlConnection.getContentLength();
in = urlConnection.getInputStream();
if (output.isDirectory()) {
output = new File(output, url.getPath());
output.getParentFile().mkdirs();
}
out = new FileOutputStream(output);
byte[] buffer = new byte[1024 * 100]; // 100k
int count = 0;
int totalCount = 0;
int progress = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
totalCount += count;
if (totalSize > 0) {
int nowProgress = totalCount * 10 / totalSize;
if (nowProgress > progress) {
progress = nowProgress;
System.out.print(".");
}
}
}
System.out.println("Done!");
return output;
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error!");
return null;
} finally {
if (in != null)
try {
in.close();
} catch (IOException e) {
}
if (out != null)
try {
out.close();
} catch (IOException e) {
}
}
}
}
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.openoffice.test.common;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* Utilities related to graphics
*
*/
public class GraphicsUtil {
/**
* Error tolerance for rectangle
*/
static final double ERR_RANGLE_RECTANGLE = 0.0;
/**
* Error tolerance for ellipse
*/
static final double ERR_RANGLE_ELLIPSE = 1;
/**
* Load a image file as buffered image
* @param file
* @return
*/
public static BufferedImage loadImage(String file) {
BufferedImage image = null;
FileInputStream in = null;
try {
in = new FileInputStream(file);
image = ImageIO.read(in);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
// ignore
}
}
return image;
}
/**
* Store a buffered image in the given file
*
* @param image
* @param imgFile
*/
public static void storeImage(BufferedImage image, String imgFile) {
File file = new File(imgFile);
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
ImageIO.write(image, FileUtil.getFileExtName(imgFile), fos);
} catch (Exception e) {
//
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException e) {
//ignore
}
}
}
/**
* Get a BufferedImage including the full current screen shot
* @return
*/
public static BufferedImage screenshot() {
return screenshot(null, null);
}
/**
* Get a BufferedImage including the area of current screen shot
* @param area
* @return
*/
public static BufferedImage screenshot(Rectangle area) {
return screenshot(null, area);
}
/**
* Store the screen shot as a image file
* @param filename
*/
public static BufferedImage screenShot(String filename) {
return screenshot(filename, null);
}
/**
* Store the specified area of the screen as a image file
* @param filename
* @param area
*/
public static BufferedImage screenshot(String filename, Rectangle area) {
// screen capture
try {
Robot robot = new Robot();
if (area == null)
area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = robot.createScreenCapture(area);
if (filename != null)
storeImage(capture, filename);
return capture;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Find a rectangle in the screen.
* Note: The rectangle must be filled with solid color and the color must be different from the background color
*
* @param rect the area in the screen to search
* @param color the rectangle color.
* @return The found rectangle's location and size. If no rectangle is
* found, return null
*/
public static Rectangle findRectangle(Rectangle rect, int color) {
return findRectangle(screenshot(rect), color);
}
/**
* find a rectangle in an image
* Note: The rectangle must be filled with solid color and the color must be different from the background color
* @param src
* @param color
* the rectangle color.
* @return The found rectangle's location and size. If no rectangle is
* found, return null
*/
public static Rectangle findRectangle(BufferedImage src, int color) {
Rectangle re = new Rectangle();
BufferedImage dst = new BufferedImage(src.getWidth(), src.getHeight(),
BufferedImage.TYPE_INT_ARGB);
for (int x = 0; x < dst.getWidth(); x++) {
for (int y = 0; y < dst.getHeight(); y++) {
dst.setRGB(x, y, 0xFFFFFFFF);
}
}
Graphics g = dst.getGraphics();
g.setColor(Color.black);
int sx = -1, sy = 0, ex = 0, ey = 0;
for (int x = 0; x < src.getWidth(); x++) {
for (int y = 0; y < src.getHeight(); y++) {
int rgbSrc = src.getRGB(x, y);
if (rgbSrc == color) {
if (sx == -1) {
sx = x;
sy = y;
}
ex = x;
ey = y;
}
}
}
g.fillRect(sx, sy, ex - sx + 1, ey - sy + 1);
// g.fillRect(0, 0, dst.getWidth(), dst.getHeight());
int perimeter = 2 * (ex - sx + ey - sy);
int errMax = (int)(perimeter * ERR_RANGLE_RECTANGLE);
if (!(detect(src, color, dst, 0xff000000, errMax) && detect(dst, 0xff000000,
src, color, errMax)))
return null;
re.setBounds(sx, sy, ex - sx, ey - sy);
if (re.width < 2 || re.height < 2) {
return null;
}
return re;
}
protected static boolean detect(BufferedImage src, int colorSrc,
BufferedImage dst, int colorDst, double errMax) {
int errCount = 0;
for (int x = 0; x < src.getWidth(); x++) {
for (int y = 0; y < src.getHeight(); y++) {
int rgbSrc = src.getRGB(x, y);
if (rgbSrc == colorSrc) {
int rgbDst = dst.getRGB(x, y);
if (!(rgbDst == colorDst)) {
errCount++;
}
}
} // end for y
}// end for x
// System.out.println(errCount);
if (errCount <= errMax)
return true;
return false;
}
}
/************************************************************************
*
* Licensed Materials - Property of IBM.
* (C) Copyright IBM Corporation 2003, 2012. All Rights Reserved.
* U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*
************************************************************************/
package org.openoffice.test.common;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;
/**
* Utilities related to system
*
*/
public class SystemUtil {
private static Logger LOG = Logger.getLogger(SystemUtil.class.getName());
private static Clipboard sysClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
private static final String OSNAME = System.getProperty("os.name");
public static final File SCRIPT_TEMP_DIR = new File(System.getProperty("user.home"), ".ootest");
/**
* Play beep sound! The method doesn't work, if the code is executed on
* Eclipse IDE.
*
*/
public static void beep() {
System.out.print("\007\007\007");
System.out.flush();
}
public static boolean isWindows() {
return OSNAME.startsWith("Windows");
}
public static boolean isLinux() {
return OSNAME.startsWith("Linux");
}
public static boolean isMac() {
return OSNAME.startsWith("Mac");
}
public static String getEnv(String name, String defaultValue) {
String value = System.getenv(name);
return value == null ? defaultValue : value;
}
/**
* Set the contents of the clipboard to the provided text
*/
public static void setClipboardText(String s) {
StringSelection ss = new StringSelection(s);
// if (OS.get() == OS.MACOSX) {
// // workaround MAC OS X has a bug. After setting a text into
// clipboard, the java program will not
// // receive the data written by other apllications.
// File file = null;
// try {
// file = File.createTempFile("SystemUtil", "SystemUtil");
// FileUtil.writeStringToFile(file.getAbsolutePath(), s);
// if (exec("pbcopy < \""+ file.getAbsolutePath() + "\"", false) == 0)
// return;
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } finally {
// if (file != null)
// file.delete();
// }
//
// }
//
sysClipboard.setContents(ss, ss);
}
/**
* Get plain text from clipboard
*
* @return
*/
public static String getClipboardText() {
Transferable contents = getTransferable();
if (contents == null
|| !contents.isDataFlavorSupported(DataFlavor.stringFlavor))
return "";
try {
return (String) contents.getTransferData(DataFlavor.stringFlavor);
} catch (Exception ex) {
return "";
}
}
private static Transferable getTransferable() {
// To avoid IllegalStateException, we try 25 times to access clipboard.
for (int i = 0; i < 25; i++) {
try {
return sysClipboard.getContents(null);
} catch (IllegalStateException e) {
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
}
}
}
throw new RuntimeException("System Clipboard is not ready");
}
public static int execScript(String content, boolean spawn) {
File file = null;
try {
file = FileUtil
.getUniqueFile(SCRIPT_TEMP_DIR, "tempscript", ".bat");
FileUtil.writeStringToFile(file.getAbsolutePath(), content);
String[] cmd;
if (isWindows())
cmd = new String[] { file.getAbsolutePath() };
else
cmd = new String[] { "sh", file.getAbsolutePath() };
StringBuffer output = new StringBuffer();
int code = exec(cmd, null, spawn, output, output);
LOG.info(content + "\n" + "Exit Code: " + code + "\n" + output);
return code;
} catch (Exception e) {
return -1;
} finally {
if (file != null) {
try {
file.deleteOnExit();
} catch (Exception e) {
// ignore
}
}
}
}
public static int exec(String[] command, String workingDir, boolean spawn,
StringBuffer output, StringBuffer error) {
Process process = null;
File dir = workingDir == null ? null : new File(workingDir);
int code = 0;
try {
process = Runtime.getRuntime().exec(command, null, dir);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
StreamPump inputPump = new StreamPump(output, process.getInputStream());
StreamPump errorPump = new StreamPump(error, process.getErrorStream());
inputPump.start();
errorPump.start();
try {
if (!spawn) {
code = process.waitFor();
inputPump.join();
errorPump.join();
}
return code;
} catch (InterruptedException e) {
e.printStackTrace();
return -1;
}
}
public static class StreamPump extends Thread {
StringBuffer stringBuffer = null;
InputStream inputStream = null;
public StreamPump(StringBuffer stringBuffer, InputStream inputStream) {
this.stringBuffer = stringBuffer;
this.inputStream = inputStream;
}
public void run() {
InputStreamReader reader = null;
try {
reader = new InputStreamReader(inputStream);
char[] buf = new char[1024];
int count = 0;
while ((count = reader.read(buf)) != -1) {
// If we need collect the output
if (stringBuffer != null)
stringBuffer.append(buf, 0, count);
}
} catch (IOException e) {
// ignore.
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
// ignore
}
}
}
}
public static void sleep(double second) {
try {
Thread.sleep((long) (second * 1000));
} catch (InterruptedException e) {
}
}
/**
* Get the commands of all running processes
*
* @return
*/
public static List<String> getProcesses() {
List<String> ret = new ArrayList<String>();
try {
StringBuffer output = new StringBuffer();
if (isWindows()) {
File file = File.createTempFile("ssssss", ".js");
String contents = "var e=new Enumerator(GetObject(\"winmgmts:\").InstancesOf(\"Win32_process\"));\n\r";
contents += "for (;!e.atEnd();e.moveNext()) {\n\r";
contents += "WScript.Echo(e.item ().CommandLine);}";
FileUtil.writeStringToFile(file.getAbsolutePath(), contents);
// exec("cscript //Nologo \"" + file.getAbsolutePath() + "\"",
// output, output);
} else {
// exec("ps -x -eo command", output, output);
}
BufferedReader reader = new BufferedReader(new StringReader(
output.toString()));
String line = null;
while ((line = reader.readLine()) != null) {
ret.add(line);
}
} catch (IOException e) {
}
return ret;
}
/**
* parse a string to arguments array.
*
* @param line
* @return
*/
public static String[] parseCommandLine(String line) {
ArrayList<String> arguments = new ArrayList<String>();
StringTokenizer tokenizer = new StringTokenizer(line, "\"\' ", true);
int state = 0;
StringBuffer current = new StringBuffer();
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
switch (state) {
case 1:
if ("\'".equals(token)) {
state = 3;
} else {
current.append(token);
}
break;
case 2:
if ("\"".equals(token)) {
state = 3;
} else {
current.append(token);
}
break;
default:
if ("\'".equals(token)) {
state = 1;
} else if ("\"".equals(token)) {
state = 2;
} else if (" ".equals(token)) {
if (current.length() > 0) {
arguments.add(current.toString());
current = new StringBuffer();
}
} else {
current.append(token);
}
break;
}
}
if (current.length() > 0)
arguments.add(current.toString());
return arguments.toArray(new String[arguments.size()]);
}
/**
* Get local machine ip address
* */
public static String getIPAddress() {
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return addr.getHostAddress().toString();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment