public void read(JarPackageData jarPackage) throws CoreException { try { readXML(jarPackage); } catch (IOException ex) { String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); // $NON-NLS-1$ throw new CoreException( new Status( IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, ex)); } catch (SAXException ex) { String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); // $NON-NLS-1$ throw new CoreException( new Status( IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, ex)); } }
/** @param file */ public void export(File file) { LOG.debug("Writing index file for directory..."); ObjectOutputStream out = null; try { out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file))); out.writeObject(qtree); out.writeObject(createEnvelope(envelope)); out.writeObject(rasterDataInfo); out.writeObject(rasterGeoReference.getOriginLocation()); out.writeDouble(rasterGeoReference.getResolutionX()); out.writeDouble(rasterGeoReference.getResolutionY()); out.writeDouble(rasterGeoReference.getRotationX()); out.writeDouble(rasterGeoReference.getRotationY()); out.writeDouble(rasterGeoReference.getOriginEasting()); out.writeDouble(rasterGeoReference.getOriginNorthing()); out.writeObject(rasterGeoReference.getCrs()); out.writeObject(resolutionInfo); out.writeObject(options); LOG.debug("Done."); } catch (IOException e) { LOG.debug( "Raster pyramid file '{}' could not be written: '{}'.", file, e.getLocalizedMessage()); LOG.trace("Stack trace:", e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.debug( "Raster pyramid file '{}' could not be closed: '{}'.", file, e.getLocalizedMessage()); LOG.trace("Stack trace:", e); } } } }
private String DownloadText(String URL) { int BUFFER_SIZE = 2000; InputStream in; try { in = OpenHttpConnection(URL); } catch (IOException e) { Log.d("Networking", e.getLocalizedMessage()); return ""; } InputStreamReader isr = new InputStreamReader(in); int charRead; String str = ""; char[] inputBuffer = new char[BUFFER_SIZE]; try { while ((charRead = isr.read(inputBuffer)) > 0) { // convert the chars to a String String readString = String.copyValueOf(inputBuffer, 0, charRead); str += readString; inputBuffer = new char[BUFFER_SIZE]; } in.close(); } catch (IOException e) { Log.d("Networking", e.getLocalizedMessage()); return ""; } return str; }
public static void copyResources(final File sourceDirectories[], final File targetDirectory) { // copy js, css and html resources final File htmlResourceDirectory = new File(Launcher.getMindRoot(), HTML_RESOURCES_DIR); if (!htmlResourceDirectory.canRead()) { logger.severe("Cannot read resource directory: " + htmlResourceDirectory.getPath()); System.exit(1); } final FileFilter ff = new FileFilter() { public boolean accept(final File file) { return file.getName().endsWith(".css") || file.getName().endsWith(".html") || file.getName().endsWith(".js") || file.isDirectory(); } }; try { FileUtils.copyDirectory(htmlResourceDirectory, targetDirectory, ff); } catch (final IOException e) { logger.severe("Error while copying resources: " + e.getLocalizedMessage()); System.exit(1); } // copy **/doc-files/* try { for (final File sourceDirectory : sourceDirectories) { DocFilesCopier.copy(sourceDirectory, targetDirectory); } } catch (final IOException e) { logger.severe("Error while copying resources: " + e.getLocalizedMessage()); System.exit(1); } }
public static synchronized void writeReport(String key, EParserResultType resultType) { BufferedWriter writer = null; try { FileWriter file = new FileWriter( REPORT_FILE_PATH + File.separator + "CodeParser-" + Thread.currentThread().getName() + ".txt", true); writer = new BufferedWriter(file); writer.append(key + ": " + resultType.toString()); writer.newLine(); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); } finally { try { writer.close(); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); } } }
public String getText(String URL) { int BUFFER_SIZE = 2000; InputStream in = null; try { in = openHttpConnection(URL); } catch (IOException e1) { Log.e(TAG, e1.getLocalizedMessage()); e1.printStackTrace(); return ""; } InputStreamReader isr = new InputStreamReader(in); int charRead; String str = ""; char[] inputBuffer = new char[BUFFER_SIZE]; try { while ((charRead = isr.read(inputBuffer)) > 0) { // ---convert the chars to a String--- String readString = String.copyValueOf(inputBuffer, 0, charRead); str += readString; inputBuffer = new char[BUFFER_SIZE]; } in.close(); } catch (IOException e) { Log.e(TAG, e.getLocalizedMessage()); e.printStackTrace(); return ""; } return str; }
/** * Versorgt die Verbindung uns schließt sie wieder. In dieser Methode wird die Verbindung zum * Client versorgt. Es werden empfange Pakete weitergeleitet und Pakete, die versendet werden * sollen, dem Client übermittelt. Wird eine Verbindung vom Client abgebaut oder der Thread * darüber informiert, dass er sich beenden soll, wird die Verbindung geschlossen und die Methode * verlassen. */ public void run() { int available = 0; Element element = null; log.trace("run(): ClientConnection gestartet."); while ((!Thread.interrupted()) && (!this.isClosed())) { // Empfangen try { available = this.in.available(); } catch (IOException ioe) { log.error(ioe.getLocalizedMessage(), ioe); available = 0; } if (available > 0) { log.trace("run(): Nachricht kommt an..."); element = null; try { element = this.receiveElement(); } catch (IOException ioe) { log.error(ioe.getLocalizedMessage(), ioe); } catch (JDOMException jde) { log.error(jde.getLocalizedMessage(), jde); } if (element != null) { Message message = new Message(element, this); this.processConnectionEvent(message); } } else { Thread.yield(); } // Senden synchronized (this.elementQueue) { if (this.elementQueue.size() > 0) { log.trace("run(): Nachricht in der Schlange gefunden."); element = (Element) this.elementQueue.elementAt(0); this.elementQueue.removeElementAt(0); try { this.sendElement(element); } catch (IOException ioe) { log.error("run() Problem beim Versenden eines Elementes.", ioe); // ROADMAP Probleme sollten dem System mitgeteilt werden. } } } } // Verbindung schliessen. try { this.close(); } catch (Throwable t) { log.error("run(): " + t.getLocalizedMessage(), t); } log.trace("run(): ClientConnection gestoppt."); }
/** * method to find all classes in a given jar * * @param resource The url to the jar file * @param pkgname The package name for classes found inside the base directory * @return The classes */ private static List findClassesInJar(URL resource, String pkgname) { String relPath = pkgname.replace('.', '/'); String path = resource .getPath() .replaceFirst("[.]jar[!].*", ".jar") // $NON-NLS-1$ //$NON-NLS-2$ .replaceFirst("file:", ""); // $NON-NLS-1$ //$NON-NLS-2$ try { path = URLDecoder.decode(path, "utf-8"); // $NON-NLS-1$ } catch (UnsupportedEncodingException uee) { log.error(uee.getLocalizedMessage(), uee); } List classes = new ArrayList(); JarFile jarFile = null; try { jarFile = new JarFile(path); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); String entryName = entry.getName(); String className = null; if (entryName.endsWith(".class") // $NON-NLS-1$ && entryName.startsWith(relPath)) { className = entryName .replace('/', '.') .replace('\\', '.') .replaceAll(".class", ""); // $NON-NLS-1$ //$NON-NLS-2$ if (className != null) { try { classes.add(Class.forName(className)); } catch (ClassNotFoundException cnfe) { log.error(cnfe.getLocalizedMessage(), cnfe); } } } } } catch (IOException ioe) { log.warn(ioe.getLocalizedMessage(), ioe); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { log.error(e.getLocalizedMessage(), e); } } } return classes; }
@Override public void performOperation() throws OperationFailedException { BEDFile intervals = (BEDFile) this.getInputBufferForClass(BEDFile.class); BAMFile bam = (BAMFile) this.getInputBufferForClass(BAMFile.class); DOCMetrics metrics = (DOCMetrics) getOutputBufferForClass(DOCMetrics.class); try { intervals.buildIntervalsMap(); CoverageCalculator covCalc = new CoverageCalculator(bam.getFile(), intervals, false); covCalc.setThreadCount(getPipelineOwner().getThreadCount()); int[] depthHistogram = covCalc.computeOverallCoverage(); // The depth histogram is an un-normalized raw counts of the number of bases with a certain // read depth // for instance, the 10th position in the list of the number of bases found with read depths = // 10 double mean = CoverageCalculator.getMean(depthHistogram); double[] covs = CoverageCalculator.convertCountsToProportions(depthHistogram); int[] cutoffs = new int[] {1, 10, 15, 20, 25, 50, 100}; double[] covAboveCutoffs = new double[cutoffs.length]; for (int i = 0; i < covAboveCutoffs.length; i++) { covAboveCutoffs[i] = covs[cutoffs[i]]; } metrics.setMeanCoverage(mean); metrics.setCoverageProportions(covs); metrics.setCutoffs(cutoffs); metrics.setFractionAboveCutoff(covAboveCutoffs); Logger.getLogger(Pipeline.primaryLoggerName) .info(getObjectLabel() + " Found mean depth : " + mean); } catch (IOException e) { e.printStackTrace(); Logger.getLogger(Pipeline.primaryLoggerName) .warning(getObjectLabel() + " encountered IO Error : " + e.getLocalizedMessage()); throw new OperationFailedException( "IO Error calculating coverages : " + e.getLocalizedMessage(), this); } catch (InterruptedException e) { e.printStackTrace(); Logger.getLogger(Pipeline.primaryLoggerName) .warning(getObjectLabel() + " was interrupted: " + e.getLocalizedMessage()); throw new OperationFailedException( "Interrupted calculating coverages : " + e.getLocalizedMessage(), this); } }
/** * Program entry point. * * @param args program arguments */ public static void main(String[] args) { try { // configure Orekit Autoconfiguration.configureOrekit(); // input/out File input = new File(VisibilityCircle.class.getResource("/visibility-circle.in").toURI().getPath()); File output = new File(input.getParentFile(), "visibility-circle.csv"); new VisibilityCircle().run(input, output, ","); System.out.println("visibility circle saved as file " + output); } catch (URISyntaxException use) { System.err.println(use.getLocalizedMessage()); System.exit(1); } catch (IOException ioe) { System.err.println(ioe.getLocalizedMessage()); System.exit(1); } catch (IllegalArgumentException iae) { System.err.println(iae.getLocalizedMessage()); System.exit(1); } catch (OrekitException oe) { System.err.println(oe.getLocalizedMessage()); System.exit(1); } }
/** * Returns an ImageIcon, or null if the path was invalid. When running an applet using Java * Plug-in, getResourceAsStream is more efficient than getResource. * * @param path the path to the image icon * @param description a text description of the image * @return a new ImageIcon or null if the image could not be loaded from the specified path */ protected static ImageIcon createAppletImageIcon(String path, String description) { int MAX_IMAGE_SIZE = 575000; // Change this to the size of // your biggest image, in bytes. int count = 0; BufferedInputStream imgStream = new BufferedInputStream(Folder.class.getResourceAsStream(path)); if (imgStream != null) { byte buf[] = new byte[MAX_IMAGE_SIZE]; try { count = imgStream.read(buf); } catch (IOException ieo) { LOG.error(Messages.getString(BUNDLE_NAME, "Folder.29") + path); // $NON-NLS-1$ LOG.error(ieo.getLocalizedMessage()); } try { imgStream.close(); } catch (IOException ieo) { LOG.error(Messages.getString(BUNDLE_NAME, "Folder.30") + path); // $NON-NLS-1$ } if (count <= 0) { LOG.error(Messages.getString(BUNDLE_NAME, "Folder.31") + path); // $NON-NLS-1$ return null; } return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf), description); } else { LOG.error(Messages.getString(BUNDLE_NAME, "Folder.32") + path); // $NON-NLS-1$ return null; } }
/* Load Record Key Map from configuration file. */ static { try { // Initialize log and output file buffered writers. theLog = new BufferedWriter(new FileWriter(new File(FILE_PATH + File.separator + LOG_FILE_NAME))); theOutputFile = new BufferedWriter( new FileWriter(new File(FILE_PATH + File.separator + OUTPUT_FILE_NAME))); // Generate key map keyMap = new Maps().generateKeyMap(); writeToLog("\n------------ KEY MAP ------------\n"); for (Entry<Integer, ArrayList<Key>> entry : keyMap.entrySet()) { writeToLog("Record type: " + entry.getKey()); for (Key key : entry.getValue()) { writeToLog( "\tKey Name: " + key.getKeyDescription() + " -> Init Pos: " + key.getKeyPosition() + " (len " + key.getKeyLength() + ")"); } } writeToLog("\n------------ END OF KEY MAP ------------\n"); } catch (IOException ex) { System.out.println("Exception: " + ex.getLocalizedMessage()); } }
@Override public Object convertToKey( FacesContext context, String keyString, UIComponent component, Converter converter) { Object convertedKey = treeDataModel.convertToKey(context, keyString, component, converter); if (convertedKey != null) { final TreeRowKey treeRowKey = (TreeRowKey) convertedKey; try { walk( context, NULL_VISITOR, new TreeRange() { public boolean processChildren(TreeRowKey rowKey) { return rowKey == null || rowKey.isSubKey(treeRowKey); } public boolean processNode(TreeRowKey rowKey) { return this.processChildren(rowKey) || rowKey.equals(treeRowKey); } }, null); } catch (IOException e) { context.getExternalContext().log(e.getLocalizedMessage(), e); return null; } } return convertedKey; }
/** * 入力データからパケットを構築して送信する。今回はSocketを複数開いたり、 ということは起こらないので本メソッドに集約してしまってる。空文字列が送られてきたら * 特殊パターンとしてrefresh用のパケットを構築する(つまり\0単独は特殊パターン) * * @return 正常終了時は0。サーバへの接続が失われていれば-4。その他I/Oエラー時は-1。 */ private int sendPacket(String src) { OutputStream writer; Log.d("moku99", "sending a packet"); try { if (clientSock.isConnected() == false) { return -4; } writer = clientSock.getOutputStream(); if (src.equals("")) { // 空の特殊パターン ByteBuffer buf = ByteBuffer.allocate(8); buf.putInt(myId.intValue()); buf.putInt(0); writer.write(buf.array()); } else { // 通常メッセージ送信パターン byte[] strBuf = src.getBytes(); ByteBuffer buf = ByteBuffer.allocate(8 + strBuf.length); buf.putInt(myId.intValue()); buf.putInt(strBuf.length); buf.put(strBuf); writer.write(buf.array()); } } catch (IOException e) { Log.d("moku99", e.getLocalizedMessage()); return -1; } return 0; }
private void initServiceDiscovery() { ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(extXMPPConnection); try { if (capsCacheDir == null) { capsCacheDir = new File(service.getCacheDir(), "entity-caps-cache"); capsCacheDir.mkdirs(); EntityCapsManager.setPersistentCache(new SimpleDirectoryPersistentCache(capsCacheDir)); } } catch (java.io.IOException e) { Log.e(TAG, "Could not init : " + e.getLocalizedMessage()); } PingManager.getInstanceFor(extXMPPConnection).setPingMinimumInterval(10 * 1000); String app_name = service.getString(R.string.app_name); String build_revision = service.getString(R.string.build_revision); Version.Manager.getInstanceFor(extXMPPConnection) .setVersion(new Version(app_name, build_revision, Constant.ANDROID)); DeliveryReceiptManager dm = DeliveryReceiptManager.getInstanceFor(extXMPPConnection); dm.enableAutoReceipts(); dm.addReceiptReceivedListener( new ReceiptReceivedListener() { // DOES NOT WORK IN CARBONS public void onReceiptReceived(String fromJid, String toJid, String receiptId) { changeMessageDeliveryStatus(receiptId, ChatConstants.DS_ACKED); } }); }
/** * Configuration method invoked by framework while initializing Class. Following are the * parameters used : * * <p> * * <blockquote> * * <pre> * resource-file - oneinc-resource.properties * validation-file - validation-rules.xml * </pre> * * </blockquote> * * <p>This method initialize the ValidatorResources by reading the validation-file passed and then * initialize different forms defined in this file. It also initialize the validation resource * bundle i.e. oneinc-resource.properties from where user friendly message would be picked in case * of validation failure. * * <p>Member-variable needs to be initialized/assigned once while initializing the class, and is * being passed from the XML is initialized in this method. * * <p>In XML, use the following tag to define the property: * * <p><property name="resource-file" value="oneinc-resource" /> * * <p>corresponding code to get the property is as follow: * * <p>String resourceName = cfg.get("resource-file"); * * @param cfg - Configuration object holds the property defined in the XML. * @throws ConfigurationException */ public void setConfiguration(Configuration cfg) throws ConfigurationException { try { String resourceName = cfg.get("resource-file"); apps = ResourceBundle.getBundle(resourceName); validationFileName = cfg.get("validation-file"); InputStream in = null; in = BaseValidation.class.getClassLoader().getResourceAsStream(validationFileName); try { resources = new ValidatorResources(in); form = resources.getForm(Locale.getDefault(), "ValidateBean"); provForm = resources.getForm(Locale.getDefault(), "ValidateProvBean"); } finally { if (in != null) { in.close(); } } prepareTxnMap(); } catch (FileNotFoundException e) { throw new ConfigurationException(e.getLocalizedMessage(), e); } catch (IOException e) { throw new ConfigurationException(e.getLocalizedMessage(), e); } catch (Exception e) { throw new ConfigurationException(e.getLocalizedMessage(), e); } }
/** * Method to initialize file writers for uniSTS data source * * @param alias boolean to show whether file is uniSTS.alias * @throws FatalException Throws exception if unable to initialise file writers */ private void createFileWriters(boolean noAlias) throws FatalException { try { /** * If UniSTS.sts file is input then unists base table and unists_accession tables are * populated so their file writers are being initialised */ if (true == noAlias) { m_fileWriterHashTable.put( Variables.uniStsBaseTableName, new FileWriter(Variables.uniStsBaseTableName + "." + m_fileToParse)); m_fileWriterHashTable.put( Variables.uniStsAccessionTableName, new FileWriter(Variables.uniStsAccessionTableName + "." + m_fileToParse)); } else { /** In case of UniSTS.alias file initialise corresponsing table */ m_fileWriterHashTable.put( Variables.uniStsAliasTableName, new FileWriter(Variables.uniStsAliasTableName + "." + m_fileToParse)); } } catch (IOException ioEx) { Logger.log( "Uniable to initialize file writers (UniSTS parser): " + ioEx.getLocalizedMessage(), Logger.INFO); } }
@Override public Engine createEngine() throws Exception { testFile = "jpa-test." + JpaH2DataStore.FILE_EXT; try { // File temp = Files.createTempFile("jpa-test", "." + JpaH2DataStore.FILE_EXT).toFile(); // temp.deleteOnExit(); testFile = Files.createTempFile("jpa-test", "." + JpaH2DataStore.FILE_EXT).toString(); } catch (final IOException ex) { Logger.getLogger(JpaH2EngineTest.class.getName()) .log(Level.SEVERE, ex.getLocalizedMessage(), ex); fail(); } EngineFactory.deleteDatabase(testFile); try { return EngineFactory.bootLocalEngine( testFile, EngineFactory.DEFAULT, PASSWORD, DataStoreType.H2_DATABASE); } catch (final Exception e) { fail(e.getMessage()); return null; } }
/** * Write the ZIP entry to the given Zip output stream. * * @param pOutput the stream where to write the entry data. */ public void writeContentToZip(ZipOutputStream pOutput) { BufferedInputStream origin = null; try { FileInputStream fi = new FileInputStream(mResource); origin = new BufferedInputStream(fi, BUFFER_SIZE); ZipEntry entry = new ZipEntry(mEntryName); pOutput.putNextEntry(entry); int count; byte data[] = new byte[BUFFER_SIZE]; while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) { pOutput.write(data, 0, count); } pOutput.closeEntry(); } catch (IOException e) { System.err.println( "Problem when writing file to zip: " + mEntryName + " (" + e.getLocalizedMessage() + ")"); } finally { // Close the file entry stream try { if (origin != null) { origin.close(); } } catch (IOException e) { } } }
/** * Cancel a Delegation Token. * * @param nnAddr the NameNode's address * @param tok the token to cancel * @throws IOException */ public static void cancelDelegationToken(String nnAddr, Token<DelegationTokenIdentifier> tok) throws IOException { StringBuilder buf = new StringBuilder(); buf.append(nnAddr); buf.append(CancelDelegationTokenServlet.PATH_SPEC); buf.append("?"); buf.append(CancelDelegationTokenServlet.TOKEN); buf.append("="); buf.append(tok.encodeToUrlString()); BufferedReader in = null; HttpURLConnection connection = null; try { URL url = new URL(buf.toString()); SecurityUtil.fetchServiceTicket(url); connection = (HttpURLConnection) url.openConnection(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Error cancelling token: " + connection.getResponseMessage()); } } catch (IOException ie) { LOG.info("error in cancel over HTTP", ie); IOException e = getExceptionFromResponse(connection); IOUtils.cleanup(LOG, in); if (e != null) { LOG.info("rethrowing exception from HTTP request: " + e.getLocalizedMessage()); throw e; } throw ie; } }
private CloudServersException parseCloudServersException(HttpResponse response) { CloudServersException cse = new CloudServersException(); try { BasicResponseHandler responseHandler = new BasicResponseHandler(); String body = responseHandler.handleResponse(response); CloudServersFaultXMLParser parser = new CloudServersFaultXMLParser(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(parser); xmlReader.parse(new InputSource(new StringReader(body))); cse = parser.getException(); } catch (ClientProtocolException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (IOException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (ParserConfigurationException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (SAXException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (FactoryConfigurationError e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } return cse; }
/** * Static function for exporting a JXTable to a CSV text file * * @param table - table to export * @param file - file to export to */ public static void exportToCSV(JXTable table, File file) { int i = 0; int j = 0; try { TableModel model = table.getModel(); FileWriter csv = new FileWriter(file); for (i = 0; i < model.getColumnCount(); i++) { csv.write(model.getColumnName(i) + ","); } csv.write(System.getProperty("line.separator")); for (i = 0; i < model.getRowCount(); i++) { for (j = 0; j < (model.getColumnCount()); j++) { if (model.getValueAt(i, j) == null) { csv.write("" + ","); } else { csv.write(model.getValueAt(i, j).toString() + ","); } } csv.write(System.getProperty("line.separator")); } csv.close(); } catch (IOException e) { JOptionPane.showMessageDialog( App.mainFrame, "Error saving file '" + file.getName() + "'\n" + e.getLocalizedMessage()); e.printStackTrace(); } }
/** * Closes this stream. It is the clients responsibility to close the stream. * * @exception CoreException if closing the stream fails */ public void close() throws CoreException { if (fInputStream != null) try { fInputStream.close(); } catch (IOException ex) { String message = (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); // $NON-NLS-1$ throw new CoreException( new Status( IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, ex)); } }
/** * If the download successfully spins up a new thread to start downloading, then we return true, * otherwise false. This is useful, e.g. when we use a cached version, and so don't want to bother * with progress dialogs et al. */ public boolean download() { // Can we use the cached version? if (verifyOrDeleteCachedVersion()) { sendCompleteMessage(); return false; } String remoteAddress = getRemoteAddress(); Log.d(TAG, "Downloading apk from " + remoteAddress); try { Downloader downloader = DownloaderFactory.create(remoteAddress, localFile); dlWrapper = new AsyncDownloadWrapper(downloader, this); dlWrapper.download(); return true; } catch (MalformedURLException e) { onErrorDownloading(e.getLocalizedMessage()); } catch (IOException e) { onErrorDownloading(e.getLocalizedMessage()); } return false; }
public void addChange( String path, FSID id, FSPathChangeKind changeKind, boolean textModified, boolean propsModified, long copyFromRevision, String copyFromPath, SVNNodeKind kind) throws SVNException { path = SVNPathUtil.canonicalizeAbsolutePath(path); OutputStream changesFile = null; try { FSTransactionRoot txnRoot = getTxnRoot(); changesFile = SVNFileUtil.openFileForWriting(txnRoot.getTransactionChangesFile(), true); FSPathChange pathChange = new FSPathChange( path, id, changeKind, textModified, propsModified, copyFromPath, copyFromRevision, kind); txnRoot.writeChangeEntry(changesFile, pathChange, true); } catch (IOException ioe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, ioe.getLocalizedMessage()); SVNErrorManager.error(err, ioe, SVNLogType.FSFS); } finally { SVNFileUtil.closeFile(changesFile); } }
public static boolean downloadOCSSWInstaller() { if (isOcsswInstalScriptDownloadSuccessful()) { return ocsswInstalScriptDownloadSuccessful; } try { URL website = new URL(OCSSW_INSTALLER_URL); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(TMP_OCSSW_INSTALLER); fos.getChannel().transferFrom(rbc, 0, 1 << 24); fos.close(); (new File(TMP_OCSSW_INSTALLER)).setExecutable(true); ocsswInstalScriptDownloadSuccessful = true; } catch (MalformedURLException malformedURLException) { handleException("URL for downloading install_ocssw.py is not correct!"); } catch (FileNotFoundException fileNotFoundException) { handleException( "ocssw installation script failed to download. \n" + "Please check network connection or 'seadas.ocssw.root' variable in the 'seadas.config' file. \n" + "possible cause of error: " + fileNotFoundException.getMessage()); } catch (IOException ioe) { handleException( "ocssw installation script failed to download. \n" + "Please check network connection or 'seadas.ocssw.root' variable in the \"seadas.config\" file. \n" + "possible cause of error: " + ioe.getLocalizedMessage()); } finally { return ocsswInstalScriptDownloadSuccessful; } }
/** * Writes data out in XML format. * * @return A flag indicating the success of the operation. */ private boolean writeXMLFile() { File selectedFile = model.getFile(); try { FileOutputStream ow = new FileOutputStream(selectedFile); DriveTrainEncoder.encode(ow, model); ow.close(); model.reset(); return true; } catch (IOException iox) { JOptionPane.showMessageDialog( this, Messages.format("Main.15", iox.getLocalizedMessage()), // $NON-NLS-1$ Messages.getString("Main.16"), JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$ return false; } catch (ParserConfigurationException iox) { JOptionPane.showMessageDialog( this, Messages.format("ParserConfigurationException", iox.getLocalizedMessage()), // $NON-NLS-1$ Messages.getString("Main.16"), JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$ return false; } catch (TransformerException iox) { JOptionPane.showMessageDialog( this, Messages.format("TransformerException", iox.getLocalizedMessage()), // $NON-NLS-1$ Messages.getString("Main.16"), JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$ return false; } }
private int _doReceive() { try { int len = readBuffer.remaining(); if (len == 0) { readBuffer.position(0); log.warn("缓冲区满,不能接收数据。dump=" + HexDump.hexDumpCompact(readBuffer)); readBuffer.clear(); len = readBuffer.remaining(); } byte[] in = readBuffer.array(); int off = readBuffer.position(); int n = socket.getInputStream().read(in, off, len); if (n <= 0) return -1; lastReadTime = System.currentTimeMillis(); readBuffer.position(off + n); readBuffer.flip(); } catch (SocketTimeoutException te) { return 0; } catch (IOException ioe) { log.warn("client IO exception," + ioe.getLocalizedMessage() + ",peer=" + getPeerAddr()); return -2; } catch (Exception e) { log.warn("client socket[" + getPeerAddr() + "] _doReceive:" + e.getLocalizedMessage(), e); return -3; } try { _handleBuffer(); } catch (Exception e) { log.error(e.getLocalizedMessage(), e); return 0; // 处理异常,非通信异常。 } return 0; // 成功 }
@RequestMapping( value = "/getKfkConfig", method = {RequestMethod.GET}) @ResponseBody public List<KafkaConfig> getKafkaConfigs( @RequestParam(value = "kafkaConfigName", required = false) String kafkaConfigName, @RequestParam(value = "limit", required = false) Integer limit, @RequestParam(value = "offset", required = false) Integer offset) { try { return kafkaConfigService.getKafkaConfigs(kafkaConfigName, limit, offset); } catch (IOException e) { logger.error("Failed to deal with the request:" + e.getLocalizedMessage(), e); throw new InternalErrorException( "Failed to deal with the request: " + e.getLocalizedMessage()); } }
/** * Reads news from a text file. * * @param position a constant indicating which file (top or side) should be read in. */ public static String readNewsFile(String newsFile) { String fileName = getNewsFilePath(); fileName += newsFile; String text = ""; try { // retrieve existing news from file FileInputStream fir = new FileInputStream(fileName); InputStreamReader ir = new InputStreamReader(fir, "UTF-8"); BufferedReader br = new BufferedReader(ir); String lineIn; while ((lineIn = br.readLine()) != null) { text += lineIn; } br.close(); } catch (IOException e) { warn("news_read: " + e.getLocalizedMessage()); } return text; }