use of java.io.BufferedWriter in project cogtool by cogtool.
the class SNIFACTPredictionAlgo method createSimilarityScoresFile.
protected String createSimilarityScoresFile(ISimilarityDictionary dict) {
// if (dict.size() == 0) {
// return null; // TODO ask about
// }
OutputStreamWriter fw = null;
BufferedWriter buffer = null;
String scoresPath = null;
try {
File dest = File.createTempFile("scores", ".lisp");
dest.deleteOnExit();
fw = new OutputStreamWriter(new FileOutputStream(dest), "US-ASCII");
buffer = new BufferedWriter(fw);
Iterator<DictEntry> entries = dict.getEntries().iterator();
while (entries.hasNext()) {
DictEntry entry = entries.next();
if ((parameters.algorithm == ITermSimilarity.ALL) || entry.algorithm.getClass().isInstance(parameters.algorithm)) {
DictValue value = dict.getValue(entry);
double simil = (value.similarity == ITermSimilarity.UNKNOWN) ? 0.0 : value.similarity;
// escape any \'s and "'s in the input strings
String quotedGoal = entry.goalWord.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"");
String quotedSearch = entry.searchWord.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"");
buffer.write("(store-score \"" + quotedGoal + "\" \"");
buffer.write(quotedSearch + "\" " + simil + ")\n");
}
}
scoresPath = dest.getAbsolutePath();
} catch (IOException e) {
throw new ComputationException("Writing file failed", e);
} finally {
try {
if (buffer != null) {
buffer.close();
}
if (fw != null) {
fw.close();
}
} catch (IOException e) {
throw new ComputationException("Closing writer failed", e);
}
}
return scoresPath;
}
use of java.io.BufferedWriter in project cogtool by cogtool.
the class DesignExportToHTML method exportToHTML.
public void exportToHTML(Design d, String dir, Cancelable cancelState, ProgressCallback progressState) {
// No need to duplicate here; we're already in the child thread
// and the design had to have been duplicated in the main thread!
design = d;
destDirectory = dir;
// Performed by the child thread
// Create a file object for DestDir and test if it is actually
// a directory
parentDir = new File(destDirectory);
if (!parentDir.isDirectory()) {
// If there is no directory specified, we should fail here.
throw new IllegalArgumentException("Create Web pages called " + "without a directory");
}
Set<Frame> frameSet = design.getFrames();
int frameCount = frameSet.size();
// Start at 0 leaving one extra "count" for overlib copy
// Use "double" to force proper division when setting progress below
double progressCount = 0.0;
// call buildFrameList to build the lookup maps.
buildFrameList();
Iterator<Frame> iter = frameSet.iterator();
ImageLoader imageLoader = new ImageLoader();
String html = null;
Image img = null;
//Note: Very long while loop in terms of code
while ((!cancelState.isCanceled()) && iter.hasNext()) {
Frame frame = iter.next();
try {
//below function, "buildFrameImage", takes in a frame and returns its image
img = buildFrameImage(frame);
imageLoader.data = new ImageData[] { img.getImageData() };
String imageName = getFrameFileName(frame, ".jpg");
// create new FILE handler for the new imageSaver's use
File imageFile = new File(parentDir, imageName);
try {
imageLoader.save(imageFile.getCanonicalPath(), SWT.IMAGE_JPEG);
} catch (IOException ex) {
// We can continue even with exceptions on individual images
throw new ImageException("Failed saving image for HTML export", ex);
}
} finally {
// dispose the image, it's not needed any more.
img.dispose();
}
try {
// write HTML to destDir
FileWriter fileOut = null;
BufferedWriter writer = null;
try {
// Use the local file name, and not the complete path.
html = buildFrameHTML(frame);
File htmlFile = new File(parentDir, getFrameFileName(frame, ".html"));
fileOut = new FileWriter(htmlFile);
writer = new BufferedWriter(fileOut);
writer.write(html);
} finally {
if (writer != null) {
writer.close();
} else if (fileOut != null) {
fileOut.close();
}
}
} catch (IOException ex) {
throw new ExportIOException("Could not save HTML for export ", ex);
}
// Update the progress count
progressCount += 1.0;
progressState.updateProgress(progressCount / frameCount, SWTStringUtil.insertEllipsis(frame.getName(), 250, StringUtil.NO_FRONT, SWTStringUtil.DEFAULT_FONT));
//end of getting frames
}
//make sure user did not cancel, and then create folder "build"
if (!cancelState.isCanceled()) {
File buildDir = new File(parentDir, "build");
if (!buildDir.exists()) {
if (!buildDir.mkdir()) {
throw new ExportIOException("Could not create build directory");
}
}
try {
// Write out the index page.
FileWriter fileOut = null;
BufferedWriter writer = null;
try {
// Use the local file name, and not the complete path.
//This creates the main page, needs a little styling
html = buildIndexPage();
File htmlFile = new File(parentDir, "index.html");
fileOut = new FileWriter(htmlFile);
writer = new BufferedWriter(fileOut);
writer.write(html);
} finally {
if (writer != null) {
writer.close();
} else if (fileOut != null) {
fileOut.close();
}
}
} catch (IOException ex) {
throw new ExportIOException("Could not save index.html for export ", ex);
}
//Here we import all the resources from the standard directory
InputStream overlibStream = ClassLoader.getSystemResourceAsStream("edu/cmu/cs/hcii/cogtool/resources/ExportToHTML/overlib.js");
if (overlibStream == null) {
throw new ExportIOException("Could not locate overlib.js resource");
}
File overlibFile = new File(buildDir, "overlib.js");
InputStream containerCoreStream = ClassLoader.getSystemResourceAsStream("edu/cmu/cs/hcii/cogtool/resources/ExportToHTML/container_core.js");
if (containerCoreStream == null) {
throw new ExportIOException("Could not locate container_core.js resource");
}
File containerCoreFile = new File(buildDir, "container_core.js");
InputStream fontsStream = ClassLoader.getSystemResourceAsStream("edu/cmu/cs/hcii/cogtool/resources/ExportToHTML/fonts-min.css");
if (fontsStream == null) {
throw new ExportIOException("Could not locate fonts-min.css resource");
}
File fontsFile = new File(buildDir, "fonts-min.css");
InputStream menuStyleStream = ClassLoader.getSystemResourceAsStream("edu/cmu/cs/hcii/cogtool/resources/ExportToHTML/menu.css");
if (menuStyleStream == null) {
throw new ExportIOException("Could not locate menu.css resource");
}
File menuStyleFile = new File(buildDir, "menu.css");
InputStream menuStream = ClassLoader.getSystemResourceAsStream("edu/cmu/cs/hcii/cogtool/resources/ExportToHTML/menu.js");
if (menuStream == null) {
throw new ExportIOException("Could not locate menu.js resource");
}
File menuFile = new File(buildDir, "menu.js");
//As you can see, lots of yahoo fancy shmancy
InputStream eventStream = ClassLoader.getSystemResourceAsStream("edu/cmu/cs/hcii/cogtool/resources/ExportToHTML/yahoo-dom-event.js");
if (eventStream == null) {
throw new ExportIOException("Could not locate yahoo-dom-event.js resource");
}
File eventFile = new File(buildDir, "yahoo-dom-event.js");
InputStream spriteStream = ClassLoader.getSystemResourceAsStream("edu/cmu/cs/hcii/cogtool/resources/ExportToHTML/sprite.png");
if (spriteStream == null) {
throw new ExportIOException("Could not locate sprite.png resource");
}
File spriteFile = new File(buildDir, "sprite.png");
try {
FileUtil.copyStreamToFile(overlibStream, overlibFile);
FileUtil.copyStreamToFile(containerCoreStream, containerCoreFile);
FileUtil.copyStreamToFile(fontsStream, fontsFile);
FileUtil.copyStreamToFile(menuStyleStream, menuStyleFile);
FileUtil.copyStreamToFile(menuStream, menuFile);
FileUtil.copyStreamToFile(eventStream, eventFile);
FileUtil.copyStreamToFile(spriteStream, spriteFile);
} catch (IOException ex) {
throw new ExportIOException("Failed to create file", ex);
}
}
// clear the look up object
frameLookUp.clear();
frameLookUp = null;
}
use of java.io.BufferedWriter in project openhab1-addons by openhab.
the class PanasonicTVBinding method sendCommand.
/**
* This methods sends the command to the TV
*
* @return HTTP response code from the TV (should be 200)
*/
private int sendCommand(PanasonicTVBindingConfig config) {
String command = config.getCommand().toUpperCase();
final String soaprequest_skeleton = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<s:Body><u:X_SendKey xmlns:u=\"urn:panasonic-com:service:p00NetworkControl:1\">" + "<X_KeyEvent>NRC_%s</X_KeyEvent></u:X_SendKey></s:Body></s:Envelope>\r";
String soaprequest = "";
if (config.getCommand().toUpperCase().startsWith("HDMI")) {
soaprequest = String.format(soaprequest_skeleton, command);
} else {
soaprequest = String.format(soaprequest_skeleton, command + "-ONOFF");
}
String tvIp = registeredTVs.get(config.getTv());
if ((tvIp == null) || tvIp.isEmpty()) {
return 0;
}
try {
Socket client = new Socket(tvIp, tvPort);
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(client.getOutputStream(), "UTF8"));
String header = "POST /nrc/control_0/ HTTP/1.1\r\n";
header = header + "Host: " + tvIp + ":" + tvPort + "\r\n";
header = header + "SOAPACTION: \"urn:panasonic-com:service:p00NetworkControl:1#X_SendKey\"\r\n";
header = header + "Content-Type: text/xml; charset=\"utf-8\"\r\n";
header = header + "Content-Length: " + soaprequest.length() + "\r\n";
header = header + "\r\n";
String request = header + soaprequest;
logger.debug("Request send to TV with IP " + tvIp + ": " + request);
wr.write(header);
wr.write(soaprequest);
wr.flush();
InputStream inFromServer = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inFromServer));
String response = reader.readLine();
client.close();
logger.debug("TV Response from " + tvIp + ": " + response);
return Integer.parseInt(response.split(" ")[1]);
} catch (IOException e) {
logger.error("Exception during communication to the TV: " + e.getStackTrace());
} catch (Exception e) {
logger.error("Exception in binding during execution of command: " + e.getStackTrace());
}
return 0;
}
use of java.io.BufferedWriter in project openhab1-addons by openhab.
the class CULSerialHandlerImpl method openHardware.
@Override
protected void openHardware() throws CULDeviceException {
String deviceName = config.getDeviceAddress();
logger.debug("Opening serial CUL connection for {}", deviceName);
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(deviceName);
if (portIdentifier.isCurrentlyOwned()) {
throw new CULDeviceException("The port " + deviceName + " is currenty used by " + portIdentifier.getCurrentOwner());
}
CommPort port = portIdentifier.open(this.getClass().getName(), 2000);
if (!(port instanceof SerialPort)) {
throw new CULDeviceException("The device " + deviceName + " is not a serial port");
}
serialPort = (SerialPort) port;
serialPort.setSerialPortParams(config.getBaudRate(), SerialPort.DATABITS_8, SerialPort.STOPBITS_1, config.getParityMode());
InputStream is = serialPort.getInputStream();
OutputStream os = serialPort.getOutputStream();
synchronized (serialPort) {
br = new BufferedReader(new InputStreamReader(is));
bw = new BufferedWriter(new OutputStreamWriter(os));
}
serialPort.notifyOnDataAvailable(true);
logger.debug("Adding serial port event listener");
serialPort.addEventListener(this);
} catch (NoSuchPortException e) {
throw new CULDeviceException(e);
} catch (PortInUseException e) {
throw new CULDeviceException(e);
} catch (UnsupportedCommOperationException e) {
throw new CULDeviceException(e);
} catch (IOException e) {
throw new CULDeviceException(e);
} catch (TooManyListenersException e) {
throw new CULDeviceException(e);
}
}
use of java.io.BufferedWriter in project openhab1-addons by openhab.
the class SqueezeServer method sendCommand.
/**
* Send a command to the Squeeze Server.
*/
private synchronized boolean sendCommand(String command) {
if (!isConnected()) {
logger.debug("No connection to SqueezeServer, will attempt to reconnect now...");
connect();
if (!isConnected()) {
logger.error("Failed to reconnect to SqueezeServer, unable to send command {}", command);
return false;
}
}
logger.debug("Sending command: {}", command);
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
writer.write(command + NEW_LINE);
writer.flush();
return true;
} catch (IOException e) {
logger.error("Error while sending command to Squeeze Server (" + command + ")", e);
return false;
}
}
Aggregations