List of usage examples for org.apache.commons.io FileUtils openInputStream
public static FileInputStream openInputStream(File file) throws IOException
new FileInputStream(file)
. From source file:com.haulmont.cuba.core.app.filestorage.FileStorage.java
@Override public InputStream openStream(FileDescriptor fileDescr) throws FileStorageException { checkFileDescriptor(fileDescr);//from ww w . java 2s .c o m File[] roots = getStorageRoots(); if (roots.length == 0) { log.error("No storage directories available"); throw new FileStorageException(FileStorageException.Type.FILE_NOT_FOUND, fileDescr.getId().toString()); } InputStream inputStream = null; for (File root : roots) { File dir = getStorageDir(root, fileDescr); File file = new File(dir, getFileName(fileDescr)); if (!file.exists()) { log.error("File " + file + " not found"); continue; } try { inputStream = FileUtils.openInputStream(file); break; } catch (IOException e) { log.error("Error opening input stream for " + file, e); } } if (inputStream != null) return inputStream; else throw new FileStorageException(FileStorageException.Type.FILE_NOT_FOUND, fileDescr.getId().toString()); }
From source file:com.hangum.tadpole.importdb.core.dialog.importdb.sql.SQLToDBImportDialog.java
private void insert() throws IOException { int ret;// w ww .java 2 s . c om BOMInputStream bomInputStream = null; File[] arryFiles = receiver.getTargetFiles(); if (arryFiles.length == 0) { MessageDialog.openError(null, Messages.CsvToRDBImportDialog_4, Messages.CsvToRDBImportDialog_21); return; } if (!MessageDialog.openConfirm(null, Messages.CsvToRDBImportDialog_4, Messages.SQLToDBImportDialog_UploadQuestion)) return; bufferBatchResult = new StringBuffer(); try { batchSize = Integer.valueOf(textBatchSize.getText()); } catch (Exception e) { batchSize = 1000; } File userUploadFile = arryFiles[arryFiles.length - 1]; try { // bom? charset? ? ?. bomInputStream = new BOMInputStream(FileUtils.openInputStream(FileUtils.getFile(userUploadFile)));//`, false, ByteOrderMark.UTF_8, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE); String charsetName = "utf-8"; String strSQLData = ""; if (bomInputStream.getBOM() == null) { strSQLData = FileUtils.readFileToString(userUploadFile, charsetName); } else { charsetName = bomInputStream.getBOMCharsetName(); strSQLData = FileUtils.readFileToString(userUploadFile, charsetName).substring(1); } String[] strArrySQL = StringUtils.split(strSQLData, textSeprator.getText()); ret = runSQLExecuteBatch(Arrays.asList(strArrySQL)); if (ret == 0) MessageDialog.openInformation(null, "Confirm", Messages.SQLToDBImportDialog_StoreData); //$NON-NLS-1$ } catch (IOException e) { logger.error(Messages.SQLToDBImportDialog_ReadError, e); MessageDialog.openError(null, Messages.CsvToRDBImportDialog_4, Messages.SQLToDBImportDialog_LoadException + e.getMessage()); } catch (Exception e) { logger.error(Messages.SQLToDBImportDialog_ImportException, e); MessageDialog.openError(null, Messages.CsvToRDBImportDialog_4, Messages.SQLToDBImportDialog_LoadException + e.getMessage()); } finally { if (bomInputStream != null) bomInputStream.close(); } }
From source file:com.hangum.tadpole.importexport.core.dialogs.SQLToDBImportDialog.java
private void insert() throws IOException { int ret;/*from www .j a v a 2 s. co m*/ BOMInputStream bomInputStream = null; File[] arryFiles = receiver.getTargetFiles(); if (arryFiles.length == 0) { MessageDialog.openWarning(null, Messages.get().Warning, Messages.get().CsvToRDBImportDialog_21); return; } if (!MessageDialog.openConfirm(null, Messages.get().Confirm, Messages.get().SQLToDBImportDialog_UploadQuestion)) return; bufferBatchResult = new StringBuffer(); try { batchSize = Integer.valueOf(textBatchSize.getText()); } catch (Exception e) { batchSize = 1000; } File userUploadFile = arryFiles[arryFiles.length - 1]; try { // bom? charset? ? ?. bomInputStream = new BOMInputStream(FileUtils.openInputStream(FileUtils.getFile(userUploadFile)));//`, false, ByteOrderMark.UTF_8, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE); String charsetName = "utf-8"; //$NON-NLS-1$ String strSQLData = ""; //$NON-NLS-1$ if (bomInputStream.getBOM() == null) { strSQLData = FileUtils.readFileToString(userUploadFile, charsetName); } else { charsetName = bomInputStream.getBOMCharsetName(); strSQLData = FileUtils.readFileToString(userUploadFile, charsetName).substring(1); } String[] strArrySQL = StringUtils.split(strSQLData, textSeprator.getText()); ret = runSQLExecuteBatch(Arrays.asList(strArrySQL)); if (ret == 0) MessageDialog.openInformation(null, Messages.get().Confirm, Messages.get().SQLToDBImportDialog_StoreData); //$NON-NLS-1$ } catch (IOException e) { logger.error(Messages.get().SQLToDBImportDialog_ReadError, e); MessageDialog.openError(null, Messages.get().Confirm, Messages.get().SQLToDBImportDialog_LoadException + e.getMessage()); } catch (Exception e) { logger.error(Messages.get().SQLToDBImportDialog_ImportException, e); MessageDialog.openError(null, Messages.get().Confirm, Messages.get().SQLToDBImportDialog_LoadException + e.getMessage()); } finally { if (bomInputStream != null) bomInputStream.close(); } }
From source file:edu.cornell.med.icb.goby.modes.TestReformatCompactReadsMode.java
/** * Validates that setting a maximum read length will propertly exclude reads from * being written to the output.// ww w.j av a 2s . c o m * * @throws IOException if there is a problem reading or writing to the files */ @Test public void excludeReadLengthsOf23() throws IOException { final ReformatCompactReadsMode reformat = new ReformatCompactReadsMode(); final String inputFilename = "test-data/compact-reads/s_1_sequence_short_1_per_chunk.compact-reads"; reformat.setInputFilenames(inputFilename); // there are no reads in the input file longer than 23 reformat.setMaxReadLength(23); final String outputFilename = "test-results/reformat-test-exclude-read-lengths.compact-reads"; reformat.setOutputFile(outputFilename); reformat.execute(); final File inputFile = new File(inputFilename); final File outputFile = new File(outputFilename); assertFalse("The reformatted file should not be the same as the original", FileUtils.contentEquals(inputFile, outputFile)); final ReadsReader reader = new ReadsReader(FileUtils.openInputStream(outputFile)); assertFalse("There should be no reads in this file", reader.hasNext()); }
From source file:com.turn.ttorrent.common.TorrentCreator.java
/** * Return the concatenation of the SHA-1 hashes of a file's pieces. * * <p>// w ww . j a v a 2 s. co m * Hashes the given file piece by piece using the default Torrent piece * length (see {@link #PIECE_LENGTH}) and returns the concatenation of * these hashes, as a string. * </p> * * <p> * This is used for creating Torrent meta-info structures from a file. * </p> * * @param file The file to hash. */ public /* for testing */ static byte[] hashFiles(Executor executor, List<File> files, long nbytes, int pieceLength) throws InterruptedException, IOException { int npieces = (int) Math.ceil((double) nbytes / pieceLength); byte[] out = new byte[Torrent.PIECE_HASH_SIZE * npieces]; CountDownLatch latch = new CountDownLatch(npieces); ByteBuffer buffer = ByteBuffer.allocate(pieceLength); long start = System.nanoTime(); int piece = 0; for (File file : files) { logger.info("Hashing data from {} ({} pieces)...", new Object[] { file.getName(), (int) Math.ceil((double) file.length() / pieceLength) }); FileInputStream fis = FileUtils.openInputStream(file); FileChannel channel = fis.getChannel(); int step = 10; try { while (channel.read(buffer) > 0) { if (buffer.remaining() == 0) { buffer.flip(); executor.execute(new ChunkHasher(out, piece, latch, buffer)); buffer = ByteBuffer.allocate(pieceLength); piece++; } if (channel.position() / (double) channel.size() * 100f > step) { logger.info(" ... {}% complete", step); step += 10; } } } finally { channel.close(); fis.close(); } } // Hash the last bit, if any if (buffer.position() > 0) { buffer.flip(); executor.execute(new ChunkHasher(out, piece, latch, buffer)); piece++; } // Wait for hashing tasks to complete. latch.await(); long elapsed = System.nanoTime() - start; logger.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}ms.", new Object[] { files.size(), nbytes, piece, npieces, String.format("%.1f", elapsed / 1e6) }); return out; }
From source file:de.fosd.jdime.Main.java
/** * Ensures that logging is configured. If the system property is set to an existing file then nothing is done as * that config was already read at JVM startup. If not, a file named {@value LOGGING_CONFIG_FILE} in * the working directory is used if it exists. If it does not, the default configuration file is read from the * classpath.// ww w. java 2 s. c o m */ private static void readLoggingConfig() { { String logConfigProperty = System.getProperty(LOGGING_CONFIG_FILE_PROPERTY); if (logConfigProperty != null && new File(logConfigProperty).exists()) { // The config file was already read at JVM startup. return; } } try { File configFile = new File(LOGGING_CONFIG_FILE); InputStream is; if (configFile.exists()) { is = FileUtils.openInputStream(configFile); } else { System.err.println("Logging configuration file " + configFile + " does not exist. " + "Falling back to defaults."); is = Main.class.getResourceAsStream(DEFAULT_LOGGING_CONFIG_FILE); if (is == null) { System.err.println("Could not find the default logging configuration."); return; } } try { LogManager.getLogManager().readConfiguration(is); } finally { try { is.close(); } catch (IOException ignored) { } } } catch (IOException e) { System.err.println("Failed to configure logging."); e.printStackTrace(); } }
From source file:eu.apenet.dpt.standalone.gui.batch.ConvertAndValidateActionListener.java
public void actionPerformed(ActionEvent event) { labels = dataPreparationToolGUI.getLabels(); continueLoop = true;/*from w w w . j a v a 2 s . c o m*/ dataPreparationToolGUI.disableAllBtnAndItems(); dataPreparationToolGUI.disableEditionTab(); dataPreparationToolGUI.disableRadioButtons(); dataPreparationToolGUI.disableAllBatchBtns(); dataPreparationToolGUI.getAPEPanel().setFilename(""); final Object[] objects = dataPreparationToolGUI.getXmlEadList().getSelectedValues(); final ApexActionListener apexActionListener = this; new Thread(new Runnable() { public void run() { FileInstance uniqueFileInstance = null; String uniqueXslMessage = ""; int numberOfFiles = objects.length; int currentFileNumberBatch = 0; ProgressFrame progressFrame = new ProgressFrame(labels, parent, true, false, apexActionListener); JProgressBar batchProgressBar = progressFrame.getProgressBarBatch(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableConversionBtn(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableValidationBtn(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableConvertAndValidateBtn(); dataPreparationToolGUI.getXmlEadList().setEnabled(false); for (Object oneFile : objects) { if (!continueLoop) { break; } File file = (File) oneFile; FileInstance fileInstance = dataPreparationToolGUI.getFileInstances().get(file.getName()); if (numberOfFiles == 1) { uniqueFileInstance = fileInstance; } if (!fileInstance.isXml()) { fileInstance.setXml(XmlChecker.isXmlParseable(file) == null); if (!fileInstance.isXml()) { if (type == CONVERT || type == CONVERT_AND_VALIDATE) { fileInstance.setConversionErrors(labels.getString("conversion.error.fileNotXml")); } else if (type == VALIDATE || type == CONVERT_AND_VALIDATE) { fileInstance.setValidationErrors(labels.getString("validation.error.fileNotXml")); } dataPreparationToolGUI.enableSaveBtn(); dataPreparationToolGUI.enableRadioButtons(); dataPreparationToolGUI.enableEditionTab(); } } SummaryWorking summaryWorking = new SummaryWorking(dataPreparationToolGUI.getResultArea(), batchProgressBar); summaryWorking.setTotalNumberFiles(numberOfFiles); summaryWorking.setCurrentFileNumberBatch(currentFileNumberBatch); Thread threadRunner = new Thread(summaryWorking); threadRunner.setName(SummaryWorking.class.toString()); threadRunner.start(); JProgressBar progressBar = null; Thread threadProgress = null; CounterThread counterThread = null; CounterCLevelCall counterCLevelCall = null; if (fileInstance.isXml()) { currentFileNumberBatch = currentFileNumberBatch + 1; if (type == CONVERT || type == CONVERT_AND_VALIDATE) { dataPreparationToolGUI.setResultAreaText(labels.getString("converting") + " " + file.getName() + " (" + (currentFileNumberBatch) + "/" + numberOfFiles + ")"); String eadid = ""; boolean doTransformation = true; if (fileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath())) || fileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath()))) { StaxTransformationTool staxTransformationTool = new StaxTransformationTool(file); staxTransformationTool.run(); LOG.debug("file has eadid? " + staxTransformationTool.isFileWithEadid()); if (!staxTransformationTool.isFileWithEadid()) { EadidQueryComponent eadidQueryComponent; if (staxTransformationTool.getUnitid() != null && !staxTransformationTool.getUnitid().equals("")) { eadidQueryComponent = new EadidQueryComponent( staxTransformationTool.getUnitid()); } else { eadidQueryComponent = new EadidQueryComponent(labels); } int result = JOptionPane.showConfirmDialog(parent, eadidQueryComponent.getMainPanel(), labels.getString("enterEADID"), JOptionPane.OK_CANCEL_OPTION); while (StringUtils.isEmpty(eadidQueryComponent.getEntryEadid()) && result != JOptionPane.CANCEL_OPTION) { result = JOptionPane.showConfirmDialog(parent, eadidQueryComponent.getMainPanel(), labels.getString("enterEADID"), JOptionPane.OK_CANCEL_OPTION); } if (result == JOptionPane.OK_OPTION) { eadid = eadidQueryComponent.getEntryEadid(); } else if (result == JOptionPane.CANCEL_OPTION) { doTransformation = false; } } } if (doTransformation) { int counterMax = 0; if (fileInstance.getConversionScriptName() .equals(Utilities.XSL_DEFAULT_APEEAD_NAME)) { progressBar = progressFrame.getProgressBarSingle(); progressBar.setVisible(true); progressFrame .setTitle(labels.getString("progressTrans") + " - " + file.getName()); CountCLevels countCLevels = new CountCLevels(); counterMax = countCLevels.countOneFile(file); if (counterMax > 0) { counterCLevelCall = new CounterCLevelCall(); counterCLevelCall.initializeCounter(counterMax); counterThread = new CounterThread(counterCLevelCall, progressBar, counterMax); threadProgress = new Thread(counterThread); threadProgress.setName(CounterThread.class.toString()); threadProgress.start(); } } try { try { File xslFile = new File(fileInstance.getConversionScriptPath()); File outputFile = new File(Utilities.TEMP_DIR + "temp_" + file.getName()); outputFile.deleteOnExit(); StringWriter xslMessages; HashMap<String, String> parameters = dataPreparationToolGUI.getParams(); parameters.put("eadidmissing", eadid); CheckIsEadFile checkIsEadFile = new CheckIsEadFile(file); checkIsEadFile.run(); if (checkIsEadFile.isEadRoot()) { File outputFile_temp = new File( Utilities.TEMP_DIR + ".temp_" + file.getName()); TransformationTool.createTransformation(FileUtils.openInputStream(file), outputFile_temp, Utilities.BEFORE_XSL_FILE, null, true, true, null, true, null); xslMessages = TransformationTool.createTransformation( FileUtils.openInputStream(outputFile_temp), outputFile, xslFile, parameters, true, true, null, true, counterCLevelCall); outputFile_temp.delete(); } else { xslMessages = TransformationTool.createTransformation( FileUtils.openInputStream(file), outputFile, xslFile, parameters, true, true, null, true, null); } fileInstance.setConversionErrors(xslMessages.toString()); fileInstance .setCurrentLocation(Utilities.TEMP_DIR + "temp_" + file.getName()); fileInstance.setConverted(); fileInstance.setLastOperation(FileInstance.Operation.CONVERT); uniqueXslMessage = xslMessages.toString(); if (xslMessages.toString().equals("")) { if (fileInstance.getConversionScriptName() .equals(Utilities.XSL_DEFAULT_APEEAD_NAME)) { fileInstance.setConversionErrors( labels.getString("conversion.noExcludedElements")); } else { fileInstance.setConversionErrors( labels.getString("conversion.finished")); } } if (!continueLoop) { break; } } catch (Exception e) { fileInstance.setConversionErrors(labels.getString("conversionException") + "\r\n\r\n-------------\r\n" + e.getMessage()); throw new Exception("Error when converting " + file.getName(), e); } if (threadProgress != null) { counterThread.stop(); threadProgress.interrupt(); } if (progressBar != null) { if (counterMax > 0) { progressBar.setValue(counterMax); } progressBar.setIndeterminate(true); } } catch (Exception e) { LOG.error("Error when converting and validating", e); } finally { summaryWorking.stop(); threadRunner.interrupt(); dataPreparationToolGUI.getXmlEadListLabel().repaint(); dataPreparationToolGUI.getXmlEadList().repaint(); if (progressBar != null) { progressBar.setVisible(false); } } } if (numberOfFiles == 1) { uniqueFileInstance = fileInstance; } } if (type == VALIDATE || type == CONVERT_AND_VALIDATE) { try { try { File fileToValidate = new File(fileInstance.getCurrentLocation()); InputStream is = FileUtils.openInputStream(fileToValidate); dataPreparationToolGUI .setResultAreaText(labels.getString("validating") + " " + file.getName() + " (" + currentFileNumberBatch + "/" + numberOfFiles + ")"); XsdObject xsdObject = fileInstance.getValidationSchema(); List<SAXParseException> exceptions; if (xsdObject.getName().equals(Xsd_enum.DTD_EAD_2002.getReadableName())) { exceptions = DocumentValidation.xmlValidationAgainstDtd( fileToValidate.getAbsolutePath(), Utilities.getUrlPathXsd(xsdObject)); } else { exceptions = DocumentValidation.xmlValidation(is, Utilities.getUrlPathXsd(xsdObject), xsdObject.isXsd11()); } if (exceptions == null || exceptions.isEmpty()) { fileInstance.setValid(true); fileInstance.setValidationErrors(labels.getString("validationSuccess")); if (xsdObject.getFileType().equals(FileInstance.FileType.EAD) && xsdObject.getName().equals("apeEAD")) { XmlQualityCheckerCall xmlQualityCheckerCall = new XmlQualityCheckerCall(); InputStream is2 = FileUtils .openInputStream(new File(fileInstance.getCurrentLocation())); TransformationTool.createTransformation(is2, null, Utilities.XML_QUALITY_FILE, null, true, true, null, false, xmlQualityCheckerCall); String xmlQualityStr = createXmlQualityString(xmlQualityCheckerCall); fileInstance.setValidationErrors( fileInstance.getValidationErrors() + xmlQualityStr); fileInstance.setXmlQualityErrors( createXmlQualityErrors(xmlQualityCheckerCall)); } } else { String errors = Utilities.stringFromList(exceptions); fileInstance.setValidationErrors(errors); fileInstance.setValid(false); } fileInstance.setLastOperation(FileInstance.Operation.VALIDATE); } catch (Exception ex) { fileInstance.setValid(false); fileInstance.setValidationErrors(labels.getString("validationException") + "\r\n\r\n-------------\r\n" + ex.getMessage()); throw new Exception("Error when validating", ex); } } catch (Exception e) { LOG.error("Error when validating", e); } finally { summaryWorking.stop(); threadRunner.interrupt(); dataPreparationToolGUI.getXmlEadListLabel().repaint(); dataPreparationToolGUI.getXmlEadList().repaint(); if (progressBar != null) { progressBar.setVisible(false); } } if (numberOfFiles == 1) { uniqueFileInstance = fileInstance; } } } } Toolkit.getDefaultToolkit().beep(); if (progressFrame != null) { try { progressFrame.stop(); } catch (Exception e) { LOG.error("Error when stopping the progress bar", e); } } dataPreparationToolGUI.getFinalAct().run(); if (numberOfFiles > 1) { dataPreparationToolGUI.getXmlEadList().clearSelection(); } else if (uniqueFileInstance != null) { if (type != VALIDATE) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .setConversionErrorText(replaceGtAndLt(uniqueFileInstance.getConversionErrors())); if (uniqueXslMessage.equals("")) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_CONVERSION, Utilities.FLASHING_GREEN_COLOR); } else { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_CONVERSION, Utilities.FLASHING_RED_COLOR); } } if (type != CONVERT) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .setValidationErrorText(uniqueFileInstance.getValidationErrors()); if (uniqueFileInstance.isValid()) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_VALIDATION, Utilities.FLASHING_GREEN_COLOR); if (uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath()))) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableConversionEdmBtn(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableValidationReportBtn(); } else if (uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.DTD_EAD_2002.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAC_SCHEMA.getPath()))) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableConversionBtn(); // dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableValidationReportBtn(); } } else { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_VALIDATION, Utilities.FLASHING_RED_COLOR); if (uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.DTD_EAD_2002.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_EAC_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAC_SCHEMA.getPath()))) { dataPreparationToolGUI.enableConversionBtns(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .enableConvertAndValidateBtn(); } } } dataPreparationToolGUI.enableMessageReportBtns(); } if (continueLoop) { dataPreparationToolGUI.setResultAreaText(labels.getString("finished")); } else { dataPreparationToolGUI.setResultAreaText(labels.getString("aborted")); } dataPreparationToolGUI.enableSaveBtn(); if (type == CONVERT) { dataPreparationToolGUI.enableValidationBtns(); } dataPreparationToolGUI.enableRadioButtons(); dataPreparationToolGUI.enableEditionTab(); } }).start(); }
From source file:com.silverpeas.gallery.web.AbstractGalleryResource.java
/** * Centralization of getting video media thumbnail. * @param expectedMediaType//w w w. j av a2 s . co m * @param mediaId * @param thumbnailId * @return */ protected Response getMediaThumbnail(final MediaType expectedMediaType, final String mediaId, final String thumbnailId) { try { final Media media = getMediaService().getMedia(new MediaPK(mediaId, getComponentId())); checkNotFoundStatus(media); verifyUserMediaAccess(media); // Verifying the physical file exists final SilverpeasFile thumbFile = SilverpeasFileProvider.getFile(FileUtils .getFile(Media.BASE_PATH.getPath(), media.getComponentInstanceId(), media.getWorkspaceSubFolderName(), ThumbnailPeriod.fromIndex(thumbnailId).getFilename()) .getPath()); if (!thumbFile.exists()) { throw new WebApplicationException(Status.NOT_FOUND); } return Response.ok(new StreamingOutput() { @Override public void write(final OutputStream output) throws IOException, WebApplicationException { final InputStream mediaStream; try { mediaStream = FileUtils.openInputStream(thumbFile); } catch (IOException e) { throw new WebApplicationException(Status.NOT_FOUND); } try { IOUtils.copy(mediaStream, output); } finally { IOUtils.closeQuietly(mediaStream); } } }).header("Content-Type", thumbFile.getMimeType()).header("Content-Length", thumbFile.length()) .header("Content-Disposition", "inline; filename=\"" + thumbFile.getName() + "\"").build(); } catch (final WebApplicationException ex) { throw ex; } catch (final Exception ex) { throw new WebApplicationException(ex, Status.SERVICE_UNAVAILABLE); } }
From source file:net.sf.logsaw.ui.impl.LogResourceManagerImpl.java
private synchronized void loadState() throws CoreException { logSet = new CopyOnWriteArraySet<ILogResource>(); if (!stateFile.toFile().exists()) { // Not exists yet return;//from w w w. j a va2 s. c om } IMemento rootElem = null; try { rootElem = XMLMemento.createReadRoot(new BufferedReader( new InputStreamReader(FileUtils.openInputStream(stateFile.toFile()), "UTF-8"))); //$NON-NLS-1$ } catch (IOException e) { // Unexpected exception; wrap with CoreException throw new CoreException(new Status(IStatus.ERROR, UIPlugin.PLUGIN_ID, NLS.bind(Messages.LogResourceManager_error_failedToLoadState, new Object[] { e.getLocalizedMessage() }), e)); } // Check if we can read this Integer compat = rootElem.getInteger(ATTRIB_COMPAT); if ((compat == null) || (compat.intValue() != COMPAT_VERSION)) { throw new CoreException(new Status(IStatus.WARNING, UIPlugin.PLUGIN_ID, Messages.LogResourceManager_warn_stateFileIncompatible)); } List<IStatus> statuses = new ArrayList<IStatus>(); for (IMemento logElem : rootElem.getChildren(ELEM_LOG_RESOURCE)) { String name = null; try { name = logElem.getChild(ELEM_NAME).getTextData(); IMemento dialectElem = logElem.getChild(ELEM_DIALECT); String dialectFactory = dialectElem.getString(ATTRIB_FACTORY); ILogDialectFactory factory = CorePlugin.getDefault().getLogDialectFactory(dialectFactory); ILogDialect dialect = factory.createLogDialect(); // Restore config options of dialect loadConfigOptions(dialectElem, (IConfigurableObject) dialect.getAdapter(IConfigurableObject.class)); String pk = logElem.getChild(ELEM_PK).getTextData(); // TODO Dynamic factory for log resource ILogResource log = SimpleLogResourceFactory.getInstance().createLogResource(); log.setDialect(dialect); log.setName(name); log.setPK(pk); // Restore config options of resource loadConfigOptions(logElem, (IConfigurableObject) log.getAdapter(IConfigurableObject.class)); // Unlock if necessary if (IndexPlugin.getDefault().getIndexService().unlock(log)) { logger.warn("Unlocked log resource " + log.getName()); //$NON-NLS-1$ } // Register log resource registerLogResource(log); } catch (Exception e) { statuses.add(new Status(IStatus.ERROR, UIPlugin.PLUGIN_ID, NLS.bind( Messages.LogResourceManager_error_failedToRestoreLogResource, new Object[] { name }), e)); } } if (!statuses.isEmpty()) { MultiStatus multiStatus = new MultiStatus(UIPlugin.PLUGIN_ID, 0, statuses.toArray(new IStatus[statuses.size()]), Messages.LogResourceManager_error_someLogResourcesCouldNotBeRestored, null); throw new CoreException(multiStatus); } logger.info("Loaded " + logSet.size() + " log resource(s)"); //$NON-NLS-1$ //$NON-NLS-2$ }
From source file:com.boundlessgeo.spatialconnect.stores.GeoJsonStore.java
private String getResourceAsString() { InputStream is = null;/*from w w w.j a v a 2 s .com*/ StringBuilder stringBuilder = null; try { final File geoJsonFile = new File(context.getFilesDir(), geojsonFilePath); is = FileUtils.openInputStream(geoJsonFile); BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(is)); String line; stringBuilder = new StringBuilder(); while ((line = bufferedreader.readLine()) != null) { stringBuilder.append(line); } } catch (IOException e) { Log.e(LOG_TAG, "Couldn't read the stream.", e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { Log.e(LOG_TAG, "Couldn't close the stream.", e); } } return stringBuilder.toString(); }