Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

In this page you can find the example usage for java.io FileInputStream available.

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:edu.internet2.middleware.shibboleth.common.config.security.FilesystemBasicCredentialBeanDefinitionParser.java

/** {@inheritDoc} */
protected byte[] getEncodedPublicKey(String keyConfigContent) {
    try {//from w w  w. j a v  a 2  s . co m
        FileInputStream ins = new FileInputStream(keyConfigContent);
        byte[] encoded = new byte[ins.available()];
        ins.read(encoded);
        return encoded;
    } catch (IOException e) {
        throw new FatalBeanException("Unable to read public key from file " + keyConfigContent, e);
    }
}

From source file:NCDSearch.NCDSearch.java

private void search(String path, int compression) {

    byte[] filebytes;

    File directory = new File(path);

    File[] files = directory.listFiles();
    double score;

    for (File file : files) {
        if (file.isDirectory()) {
            search(file.getPath(), compression);
        } else {//from  ww w . jav a 2  s. c o m
            try {

                FileInputStream reader = new FileInputStream(file);
                while (reader.available() > 0) {

                    filebytes = new byte[Math.min(reader.available(), 10 * targetbytes.length)];
                    reader.read(filebytes);
                    score = NCD(filebytes, targetbytes, compression);

                    if (score < bestscore) {
                        this.bestscore = score;
                        this.bestpath = file.getPath();
                    }
                }

            } catch (IOException e) {
                System.out.println(e.toString());
                System.out.println("Could not read file!" + file.getPath());
            }
        }
    }
}

From source file:org.sakaiproject.tool.rutgers.LinkTool.java

/**
 * Read our secret key from a file. returns the key
 * // w  w  w  .  j  a  v  a 2s  .  c o  m
 * @param filename
 *        Contains the key in proper binary format
 * @return the secret key object OR null if there is a failure
 */
private static SecretKey readSecretKey(String filename, String alg) {
    SecretKey privkey = null;
    FileInputStream file = null;
    try {
        file = new FileInputStream(filename);
        byte[] bytes = new byte[file.available()];
        file.read(bytes);
        privkey = new SecretKeySpec(bytes, alg);
    } catch (Exception ignore) {
        M_log.error("Unable to read key from " + filename);
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                // tried
            }
        }
    }
    return privkey;
}

From source file:com.ikon.util.impexp.RepositoryImporter.java

/**
 * Import document./*  w  ww. ja v a 2 s  . c o m*/
 */
private static ImpExpStats importDocument(String token, File fs, String fldPath, String fileName, File fDoc,
        String metadata, boolean history, Writer out, InfoDecorator deco)
        throws IOException, RepositoryException, DatabaseException, PathNotFoundException,
        AccessDeniedException, ExtensionException, AutomationException {
    FileInputStream fisContent = new FileInputStream(fDoc);
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    DocumentModule dm = ModuleManager.getDocumentModule();
    ImpExpStats stats = new ImpExpStats();
    int size = fisContent.available();
    Document doc = new Document();
    Gson gson = new Gson();
    boolean api = false;

    try {
        // Metadata
        if (!metadata.equals("none")) {
            boolean isJsonFile = metadata.equals("JSON");
            // Read serialized document metadata
            File jsFile = null;
            if (isJsonFile)
                jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT);
            else
                jsFile = new File(fDoc.getPath() + ".xml");

            log.info("Document Metadata File: {}", jsFile.getPath());

            if (jsFile.exists() && jsFile.canRead()) {
                FileReader fr = new FileReader(jsFile);
                DocumentMetadata dmd = null;

                //for json file metadata
                if (isJsonFile)
                    dmd = gson.fromJson(fr, DocumentMetadata.class);
                else {
                    JAXBContext jaxbContext = JAXBContext.newInstance(DocumentMetadata.class);

                    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                    dmd = (DocumentMetadata) jaxbUnmarshaller.unmarshal(fr);
                }

                doc.setPath(fldPath + "/" + fileName);
                dmd.setPath(doc.getPath());
                IOUtils.closeQuietly(fr);
                log.info("Document Metadata: {}", dmd);

                if (history && containsHistoryFiles(fs, fileName)) {
                    File[] vhFiles = fs.listFiles(new RepositoryImporter.VersionFilenameFilter(fileName));
                    List<File> listFiles = Arrays.asList(vhFiles);
                    Collections.sort(listFiles, FilenameVersionComparator.getInstance());
                    boolean first = true;

                    for (File vhf : vhFiles) {
                        String vhfName = vhf.getName();
                        int idx = vhfName.lastIndexOf('#', vhfName.length() - 2);
                        String verName = vhfName.substring(idx + 2, vhfName.length() - 1);
                        FileInputStream fis = new FileInputStream(vhf);
                        File jsVerFile = new File(vhf.getPath() + Config.EXPORT_METADATA_EXT);
                        log.info("Document Version Metadata File: {}", jsVerFile.getPath());

                        if (jsVerFile.exists() && jsVerFile.canRead()) {
                            FileReader verFr = new FileReader(jsVerFile);
                            VersionMetadata vmd = gson.fromJson(verFr, VersionMetadata.class);
                            IOUtils.closeQuietly(verFr);

                            if (first) {
                                dmd.setVersion(vmd);
                                size = fis.available();
                                ma.importWithMetadata(dmd, fis);
                                first = false;
                            } else {
                                log.info("Document Version Metadata: {}", vmd);
                                size = fis.available();
                                ma.importWithMetadata(doc.getPath(), vmd, fis);
                            }
                        } else {
                            log.warn("Unable to read metadata file: {}", jsVerFile.getPath());
                        }

                        IOUtils.closeQuietly(fis);
                        FileLogger.info(BASE_NAME, "Created document ''{0}'' version ''{1}''", doc.getPath(),
                                verName);
                        log.info("Created document '{}' version '{}'", doc.getPath(), verName);
                    }
                } else {
                    // Apply metadata
                    ma.importWithMetadata(dmd, fisContent);
                    FileLogger.info(BASE_NAME, "Created document ''{0}''", doc.getPath());
                    log.info("Created document '{}'", doc.getPath());
                }
            } else {
                log.warn("Unable to read metadata file: {}", jsFile.getPath());
                api = true;
            }
        } else {
            api = true;
        }

        if (api) {
            doc.setPath(fldPath + "/" + fileName);

            // Version history
            if (history) {
                File[] vhFiles = fs.listFiles(new RepositoryImporter.VersionFilenameFilter(fileName));
                List<File> listFiles = Arrays.asList(vhFiles);
                Collections.sort(listFiles, FilenameVersionComparator.getInstance());
                boolean first = true;

                for (File vhf : vhFiles) {
                    String vhfName = vhf.getName();
                    int idx = vhfName.lastIndexOf('#', vhfName.length() - 2);
                    String verName = vhfName.substring(idx + 2, vhfName.length() - 1);
                    FileInputStream fis = new FileInputStream(vhf);

                    if (first) {
                        dm.create(token, doc, fis);
                        first = false;
                    } else {
                        dm.checkout(token, doc.getPath());
                        dm.checkin(token, doc.getPath(), fis, "Imported from administration");
                    }

                    IOUtils.closeQuietly(fis);
                    FileLogger.info(BASE_NAME, "Created document ''{0}'' version ''{1}''", doc.getPath(),
                            verName);
                    log.info("Created document '{}' version '{}'", doc.getPath(), verName);
                }
            } else {
                dm.create(token, doc, fisContent);
                FileLogger.info(BASE_NAME, "Created document ''{0}''", doc.getPath());
                log.info("Created document ''{}''", doc.getPath());
            }
        }

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), null));
            out.flush();
        }

        // Stats
        stats.setSize(stats.getSize() + size);
        stats.setDocuments(stats.getDocuments() + 1);
    } catch (UnsupportedMimeTypeException e) {
        log.warn("UnsupportedMimeTypeException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", doc.getPath());
    } catch (FileSizeExceededException e) {
        log.warn("FileSizeExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", doc.getPath());
    } catch (UserQuotaExceededException e) {
        log.warn("UserQuotaExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", doc.getPath());
    } catch (VirusDetectedException e) {
        log.warn("VirusWarningException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", doc.getPath());
    } catch (ItemExistsException e) {
        log.warn("ItemExistsException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", doc.getPath());
    } catch (LockException e) {
        log.warn("LockException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Lock"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "LockException ''{0}''", doc.getPath());
    } catch (VersionException e) {
        log.warn("VersionException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Version"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VersionException ''{0}''", doc.getPath());
    } catch (JsonParseException e) {
        log.warn("JsonParseException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", doc.getPath());
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fisContent);
    }

    return stats;
}

From source file:org.globus.examples.services.filebuy.transfer.impl.FileTransferService.java

public TransferResponse transfer(Transfer params) throws RemoteException {
    /* Retrieve parameters */
    String name = params.getName();
    String location = params.getLocation();
    EndpointReferenceType buyerEPR = params.getBuyerEPR();

    /*/*from  w ww .j  a  v a2  s .  c om*/
     * INVOKE TRANSFER OPERATION IN BUYER
     */

    // Get FileBuyer portType
    FileBuyerServiceAddressingLocator buyerLocator;
    buyerLocator = new FileBuyerServiceAddressingLocator();
    FileBuyerPortType buyerPortType = null;
    try {
        buyerPortType = buyerLocator.getFileBuyerPortTypePort(buyerEPR);
    } catch (ServiceException e) {
        logger.error("ERROR: Unable to obtain buyer portType.");
        throw new RemoteException("ERROR: Unable to obtain buyer portType.", e);
    }

    // Read file to transfer
    byte[] fileBytes = null;
    try {
        File file = new File(location);
        FileInputStream fis = new FileInputStream(file);
        fileBytes = new byte[fis.available()];
        fis.read(fileBytes);
    } catch (IOException e) {
        logger.error("ERROR: Unable to open file to transfer.");
        throw new RemoteException("ERROR: Unable to open file to transfer.", e);
    }

    // Create request to Transfer operation
    org.globus.examples.stubs.filebuy.FileBuyer.Transfer transferRequest;
    transferRequest = new org.globus.examples.stubs.filebuy.FileBuyer.Transfer();
    transferRequest.setName(name);
    transferRequest.setData(fileBytes);

    // Perform invocation
    try {
        buyerPortType.transfer(transferRequest);
    } catch (RemoteException e) {
        logger.error("ERROR: Unable to invoke Transfer operation.");
        throw new RemoteException("ERROR: Unable to invoke Transfer operation.", e);

    }

    return new TransferResponse();
}

From source file:org.bigmouth.nvwa.spring.file.FileConfigurator.java

@Override
protected void doInit() {
    if (null != confDirectory) {
        try {// w  ww  .j  a v  a  2  s . c o m
            File dir = confDirectory.getFile();
            if (!dir.isDirectory()) {
                LOGGER.warn("File [{}] does not directory path.", dir.getPath());
                return;
            }

            Collection<File> files = FileUtils.listFiles(dir, null, true);
            for (File file : files) {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Load config file: {}", file.getPath());
                }
                String key = file.getAbsolutePath();
                FileInputStream is = new FileInputStream(file);
                byte[] buffer = new byte[is.available()];
                IOUtils.readFully(is, buffer);
                CONFS.put(convertKey(key), buffer);
            }
        } catch (IOException e) {
            LOGGER.error("init:", e);
        }
    }
}

From source file:org.silverpeas.core.index.indexing.parser.rtfParser.RtfParser.java

public void outPutContent(Writer out, String path, String encoding) throws IOException {

    FileInputStream in = null;
    try {/*from   w  w w .  j  av  a  2s .  co m*/
        in = new FileInputStream(path);
        byte[] buffer = new byte[in.available()];
        in.read(buffer, 0, in.available());

        // RTF always uses ASCII, so we don't need to care about the encoding
        String input = new String(buffer);

        String result = null;
        try {
            // use build in RTF parser from Swing API
            RTFEditorKit rtfEditor = new RTFEditorKit();
            Document doc = rtfEditor.createDefaultDocument();
            rtfEditor.read(new StringReader(input), doc, 0);

            result = doc.getText(0, doc.getLength());
        } catch (Exception e) {
            SilverTrace.warn("indexing", "RtfParser.outPutContent()", "", e);
        }
        out.write(result);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.apache.axis2.deployment.deployers.CustomDeployer.java

/**
 * Process a file and add it to the configuration
 *
 * @param deploymentFileData the DeploymentFileData object to deploy
 * @throws org.apache.axis2.deployment.DeploymentException
 *          if there is a problem/*from w  w w .j  a v a 2 s.co m*/
 */
public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
    log.info("Deploying - " + deploymentFileData.getName());
    try {
        FileInputStream fis = new FileInputStream(deploymentFileData.getFile());
        int x = fis.available();
        byte b[] = new byte[x];
        fis.read(b);
        String content = new String(b);
        if (content.indexOf("George") > -1)
            georgeDeployed = true;
        if (content.indexOf("Mary") > -1)
            maryDeployed = true;
        deployedItems++;
        super.deploy(deploymentFileData);
    } catch (Exception e) {
        throw new DeploymentException(e);
    }
}

From source file:org.silverpeas.search.indexEngine.parser.rtfParser.RtfParser.java

public void outPutContent(Writer out, String path, String encoding) throws IOException {

    FileInputStream in = null;
    try {//from  w w w  . j  av  a 2  s .  c  o m
        in = new FileInputStream(path);
        byte[] buffer = new byte[in.available()];
        in.read(buffer, 0, in.available());

        // RTF always uses ASCII, so we don't need to care about the encoding
        String input = new String(buffer);

        // workaround to remove RTF keywords that cause a NPE in Java 1.4
        // this is a known bug in Java 1.4 that was fixed in 1.5
        // please see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5042109 for
        // the official bug report
        // input = TS_REMOVE_PATTERN.matcher(input).replaceAll("");

        String result = null;
        try {
            // use build in RTF parser from Swing API
            RTFEditorKit rtfEditor = new RTFEditorKit();
            Document doc = rtfEditor.createDefaultDocument();
            rtfEditor.read(new StringReader(input), doc, 0);

            result = doc.getText(0, doc.getLength());
        } catch (Exception e) {
            SilverTrace.warn("indexEngine", "RtfParser.outPutContent()", "", e);
        }

        SilverTrace.debug("indexEngine", "RtfParser.outPutContent", "root.MSG_GEN_EXIT_METHOD", result);

        out.write(result);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:it.marcoberri.mbmeteo.action.chart.GetLastUPie.java

/**
 * Processes requests for both HTTP/*from  w ww. j  a v a  2  s  .  c o m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);

    Meteolog meteolog = ds.find(Meteolog.class).order("-time").limit(1).get();

    final DefaultPieDataset dataset = new DefaultPieDataset();

    dataset.setValue(ChartEnumMinMaxHelper.outdoorHumidityMin.getUm(), meteolog.getOutdoorHumidity());
    dataset.setValue("", 100 - meteolog.getOutdoorHumidity());

    JFreeChart chart = ChartFactory.createPieChart("Humidity %", // chart title
            dataset, // data
            true, // include legend
            true, false);

    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    plot.setNoDataMessage("No data available");
    plot.setCircular(false);
    plot.setLabelGap(0.02);

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    response.setContentType("image/jpeg");
    response.setHeader("Content-Length", "" + f.length());
    response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
    final OutputStream out = response.getOutputStream();
    final FileInputStream in = new FileInputStream(f.toString());
    final int size = in.available();
    final byte[] content = new byte[size];
    in.read(content);
    out.write(content);
    in.close();
    out.close();

}