Example usage for java.io InputStream toString

List of usage examples for java.io InputStream toString

Introduction

In this page you can find the example usage for java.io InputStream toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:edu.jhu.cvrg.services.nodeDataService.DataStaging.java

/** Extracts the files from a zip and puts them in sub-directories based on the subjectID .csv file found in the zip.
 * if a file is not listed in the csv, the filename is converted to lowercase and used as the subjectID.
 * /*from ww w .j av a2s. c  om*/
 * @param parentFolder
 * @param uId
 * @param fileName
 * @param ftpHost
 * @param ftpUser
 * @param ftpPassword
 * @param bExposure
 * @return
 * @throws Exception
 */
private boolean extractZipFile(String parentFolder, String uId, String fileName, String ftpHost, String ftpUser,
        String ftpPassword, boolean bExposure) throws Exception {

    boolean nullCsv = true;
    String fileDir = fileName.substring(0, fileName.lastIndexOf(sep));
    if (fileName.substring(0, 1).equals(sep)) {
        fileName = fileName.substring(1, fileName.length());
    }
    String bareFileName = fileName.substring(fileName.lastIndexOf(sep) + 1);
    System.out.println("beginning file name " + fileName);

    System.out.println(localFtpRoot + sep + fileName);

    //unzip the file
    File zipFile = new File(localFtpRoot + sep + fileName);
    System.out.println("First Zip file length at 0 seconds: " + zipFile.length());
    long firstZipLength = zipFile.length();
    try {
        Thread.currentThread().sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    long secondZipLength = zipFile.length();
    System.out.println("Second Zip file length at 0 seconds: " + zipFile.length());
    int attempt = 0;
    while ((firstZipLength != secondZipLength) && (attempt < 10)) {
        firstZipLength = zipFile.length();
        try {
            Thread.currentThread().sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        secondZipLength = zipFile.length();
        System.out.println("First and second zip file lengths: " + firstZipLength + " " + secondZipLength);
    }
    try {
        org.apache.tools.zip.ZipFile file = new ZipFile(zipFile);

        // find and save the .csv file.
        Enumeration<ZipEntry> enumer = file.getEntries();
        ZipEntry csvFile = null;
        String bareFileNameWithCsv = bareFileName.substring(0, bareFileName.lastIndexOf(".") + 1) + "csv";
        System.out.println("bareFileName entry: " + bareFileNameWithCsv);
        while (enumer.hasMoreElements()) {
            ZipEntry entry = enumer.nextElement();
            String bareEntryFileName = entry.getName().substring(entry.getName().lastIndexOf(sep) + 1);
            System.out.println("zip entry: " + bareEntryFileName);
            if ((bareEntryFileName.equals(bareFileNameWithCsv))) {
                nullCsv = false;
                csvFile = entry;
            }
        }
        enumer = null;
        enumer = file.getEntries();

        //unzip csv file 
        String csvFileName = null;
        System.out.println(nullCsv);
        if (nullCsv) {
        } else {
            nullCsv = false;
            java.io.InputStream in = file.getInputStream(csvFile);
            int sepPosition = csvFile.getName().lastIndexOf("\\");
            if (sepPosition == -1) {
                sepPosition = csvFile.getName().lastIndexOf("/");
            }
            csvFileName = csvFile.getName().substring(sepPosition + 1);
            System.out.println(csvFileName + " input stream " + in.toString());
            FileOutputStream out = new FileOutputStream(
                    localFtpRoot + fileDir + sep + csvFile.getName().substring(sepPosition + 1));
            byte[] buffer = new byte[10240];
            int counter = 0;
            while (true) {
                int bytes = in.read(buffer);
                if (bytes < 0)
                    break;
                out.write(buffer, 0, bytes);
                counter += bytes;
            }
            out.close();
            in.close();
        }

        //unzip rest of files
        while (enumer.hasMoreElements()) {
            ZipEntry entry = enumer.nextElement();
            if ((entry.getName().substring(entry.getName().lastIndexOf(".") + 1).toLowerCase()
                    .matches("dat|rdt|hea|ini|txt|xml"))) {
                System.out.println(entry.getName());
                java.io.InputStream in = file.getInputStream(entry);
                int sepPosition = entry.getName().lastIndexOf("\\");
                if (sepPosition == -1) {
                    sepPosition = entry.getName().lastIndexOf("/");
                }
                String dataFileName = entry.getName().substring(sepPosition + 1);
                String subId = entry.getName().substring(sepPosition + 1, entry.getName().lastIndexOf("."))
                        .toLowerCase();

                //see if file has a subject ID defined in csv header
                if (!nullCsv) {
                    FileInputStream fstream = new FileInputStream(
                            localFtpRoot + sep + fileDir + sep + csvFileName);
                    // Get the object of DataInputStream
                    DataInputStream inCsv = new DataInputStream(fstream);
                    BufferedReader br = new BufferedReader(new InputStreamReader(inCsv));
                    String strLine;
                    //Read CSV File Line By Line looking for a match to the dataFileName
                    while ((strLine = br.readLine()) != null) {
                        // Print the content on the console
                        StringTokenizer tokenizer = new StringTokenizer(strLine, ",");
                        String subjectId = tokenizer.nextToken().toLowerCase();
                        String headerFileName = tokenizer.nextToken();
                        if (dataFileName.equals(headerFileName)) {
                            subId = subjectId;// use the subjectId listed in the csv file instead of the default one 
                            System.out.println("subject ID found in csv file.");
                        }
                    }
                }

                // make sub-dir
                File subdir = new File(localFtpRoot + fileDir + sep + subId);
                subdir.mkdir();

                String subjectUserFileName = dataFileName;
                System.out.println(
                        "Writing: " + localFtpRoot + fileDir + sep + subId + sep + subjectUserFileName);
                FileOutputStream out = new FileOutputStream(
                        localFtpRoot + fileDir + sep + subId + sep + subjectUserFileName);
                byte[] buffer = new byte[10240];
                int counter = 0;
                while (true) {
                    int bytes = in.read(buffer);
                    if (bytes < 0)
                        break;
                    out.write(buffer, 0, bytes);
                    counter += bytes;
                }
                out.close();
                in.close();

                utils.routeToFolder(localFtpRoot + fileDir + sep + subId, subjectUserFileName, uId, subId,
                        subjectUserFileName, ftpHost, ftpUser, ftpPassword, remoteFtpRoot, bExposure);
                System.out.println("---------------------------------------");
            }
        }

    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        throw e1;
    }

    return true;

}

From source file:org.smartfrog.projects.alpine.transport.http.HttpTransmitter.java

/**
 * Transmit a file containing an XML message.
 * the file is not deleted afterwards, so the transport can be used to push up existing messages 
 * @param outputFile file to upload.// www  .  j  ava  2 s  .com
 * @throws AlpineRuntimeException in case of trouble.
 */
public void transmitPayload(File outputFile) {
    String destination = wsa.getDestination();
    log.debug("Posting to " + destination);
    PostMethod method = new ProgressingPostMethod(destination);
    //REVISIT. Its not clear that this method should stay around.
    //method.setFollowRedirects(true);
    method.addRequestHeader("SOAPAction", "");
    method.addRequestHeader("User-Agent", HttpConstants.ALPINE_VERSION);
    //fill in the details
    //1. get the message into a byte array
    //2. add it
    //3. TODO: add files?
    RequestEntity re = null;
    String contentType = HttpConstants.CONTENT_TYPE_TEXT_XML;
    String ctxContentType = (String) tx.getContext().get(ContextConstants.ATTR_SOAP_CONTENT_TYPE);
    if (ctxContentType != null) {
        contentType = ctxContentType;
    }
    re = new ProgressiveFileUploadRequestEntity(tx, request, outputFile, contentType, tx.getUploadFeedback(),
            BLOCKSIZE);
    method.setRequestEntity(re);
    InputStream responseStream = null;
    try {
        int statusCode = httpclient.executeMethod(method);
        final boolean requestFailed = statusCode != HttpStatus.SC_OK;
        boolean responseIsXml;
        //get the content type and drop anything following a semicolon
        //this can be null on an empty response
        contentType = getResponseContentType(method);
        if (contentType != null) {
            contentType = HttpBinder.extractBaseContentType(contentType);
            responseIsXml = HttpBinder.isValidSoapContentType(contentType);
        } else {
            responseIsXml = false;
        }

        if (requestFailed && (!responseIsXml || statusCode != HttpStatus.SC_INTERNAL_SERVER_ERROR)) {
            //TODO: treat 500+text/xml response specially, as it is probably a SOAPFault
            log.error("Method failed: " + method.getStatusLine());
            throw new HttpTransportFault(destination, method);
        }

        //response is 200, but is it HTML?
        if (!responseIsXml) {
            HttpTransportFault fault = new HttpTransportFault(destination, method,
                    "Wrong content type: expected " + HttpConstants.CONTENT_TYPE_TEXT_XML + " or "
                            + HttpConstants.CONTENT_TYPE_SOAP_XML + " but got [" + contentType + ']');
            throw fault;
        }
        //extract the response
        responseStream = new CachingInputStream(method.getResponseBodyAsStream(), "utf8");
        //parse it
        SoapMessageParser parser = tx.getContext().createParser();
        MessageDocument response;
        if (!requestFailed) {
            response = parser.parseStream(responseStream);
            //set our response
            tx.getContext().setResponse(response);
        } else {
            // if is a fault, turn it into an exception.
            try {
                response = parser.parseStream(responseStream);
                //set our response
                tx.getContext().setResponse(response);
            } catch (Exception e) {
                //this is here to catch XML Responses that cannot be
                //parsed, and to avoid the underlying problem 'remote server error'
                //from being lost.
                String text = responseStream.toString();
                SoapException ex = new SoapException("The remote endpoint returned an error,\n"
                        + "but the response could not be parsed\n" + "and turned into a SOAPFault.\n" + "XML:"
                        + text + "\nParse Error:" + e.toString(), e, null);
                ex.addAddressDetails(request);
                throw ex;
            }
            SoapException ex = new SoapException(response);
            throw ex;
        }
    } catch (IOException ioe) {
        throw new HttpTransportFault(destination, ioe);
    } catch (SAXException e) {
        throw new HttpTransportFault(destination, e);
    } catch (ParsingException e) {
        throw new HttpTransportFault(destination, e);
    } finally {
        if (responseStream != null) {
            try {
                responseStream.close();
            } catch (IOException e) {
                //ignore this.
            }
        }
        method.releaseConnection();
    }
}

From source file:org.openmrs.module.ModuleFileParser.java

/**
 * Get the module//from   ww  w. j ava  2  s.c om
 *
 * @return new module object
 */
public Module parse() throws ModuleException {

    Module module = null;
    JarFile jarfile = null;
    InputStream configStream = null;

    try {
        try {
            jarfile = new JarFile(moduleFile);
        } catch (IOException e) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.cannotGetJarFile"),
                    moduleFile.getName(), e);
        }

        // look for config.xml in the root of the module
        ZipEntry config = jarfile.getEntry("config.xml");
        if (config == null) {
            throw new ModuleException(Context.getMessageSourceService().getMessage("Module.error.noConfigFile"),
                    moduleFile.getName());
        }

        // get a config file stream
        try {
            configStream = jarfile.getInputStream(config);
        } catch (IOException e) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.cannotGetConfigFileStream"),
                    moduleFile.getName(), e);
        }

        // turn the config file into an xml document
        Document configDoc = null;
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            db.setEntityResolver(new EntityResolver() {

                @Override
                public InputSource resolveEntity(String publicId, String systemId)
                        throws SAXException, IOException {
                    // When asked to resolve external entities (such as a
                    // DTD) we return an InputSource
                    // with no data at the end, causing the parser to ignore
                    // the DTD.
                    return new InputSource(new StringReader(""));
                }
            });

            configDoc = db.parse(configStream);
        } catch (Exception e) {
            log.error("Error parsing config.xml: " + configStream.toString(), e);

            OutputStream out = null;
            String output = "";
            try {
                out = new ByteArrayOutputStream();
                // Now copy bytes from the URL to the output stream
                byte[] buffer = new byte[4096];
                int bytes_read;
                while ((bytes_read = configStream.read(buffer)) != -1) {
                    out.write(buffer, 0, bytes_read);
                }
                output = out.toString();
            } catch (Exception e2) {
                log.warn("Another error parsing config.xml", e2);
            } finally {
                try {
                    out.close();
                } catch (Exception e3) {
                }
            }

            log.error("config.xml content: " + output);
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.cannotParseConfigFile"),
                    moduleFile.getName(), e);
        }

        Element rootNode = configDoc.getDocumentElement();

        String configVersion = rootNode.getAttribute("configVersion").trim();

        if (!validConfigVersions.contains(configVersion)) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.invalidConfigVersion",
                            new Object[] { configVersion }, Context.getLocale()),
                    moduleFile.getName());
        }

        String name = getElement(rootNode, configVersion, "name").trim();
        String moduleId = getElement(rootNode, configVersion, "id").trim();
        String packageName = getElement(rootNode, configVersion, "package").trim();
        String author = getElement(rootNode, configVersion, "author").trim();
        String desc = getElement(rootNode, configVersion, "description").trim();
        String version = getElement(rootNode, configVersion, "version").trim();

        // do some validation
        if (name == null || name.length() == 0) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.nameCannotBeEmpty"),
                    moduleFile.getName());
        }
        if (moduleId == null || moduleId.length() == 0) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.idCannotBeEmpty"), name);
        }
        if (packageName == null || packageName.length() == 0) {
            throw new ModuleException(
                    Context.getMessageSourceService().getMessage("Module.error.packageCannotBeEmpty"), name);
        }

        // create the module object
        module = new Module(name, moduleId, packageName, author, desc, version);

        // find and load the activator class
        module.setActivatorName(getElement(rootNode, configVersion, "activator").trim());

        module.setRequireDatabaseVersion(
                getElement(rootNode, configVersion, "require_database_version").trim());
        module.setRequireOpenmrsVersion(getElement(rootNode, configVersion, "require_version").trim());
        module.setUpdateURL(getElement(rootNode, configVersion, "updateURL").trim());
        module.setRequiredModulesMap(getRequiredModules(rootNode, configVersion));
        module.setAwareOfModulesMap(getAwareOfModules(rootNode, configVersion));
        module.setStartBeforeModulesMap(getStartBeforeModules(rootNode, configVersion));

        module.setAdvicePoints(getAdvice(rootNode, configVersion, module));
        module.setExtensionNames(getExtensions(rootNode, configVersion));

        module.setPrivileges(getPrivileges(rootNode, configVersion));
        module.setGlobalProperties(getGlobalProperties(rootNode, configVersion));

        module.setMessages(getMessages(rootNode, configVersion, jarfile, moduleId, version));

        module.setMappingFiles(getMappingFiles(rootNode, configVersion, jarfile));
        module.setPackagesWithMappedClasses(getPackagesWithMappedClasses(rootNode, configVersion));

        module.setConfig(configDoc);

        module.setMandatory(getMandatory(rootNode, configVersion, jarfile));

        module.setFile(moduleFile);

        module.setConditionalResources(getConditionalResources(rootNode));
    } finally {
        try {
            jarfile.close();
        } catch (Exception e) {
            log.warn("Unable to close jarfile: " + jarfile, e);
        }
        if (configStream != null) {
            try {
                configStream.close();
            } catch (Exception io) {
                log.error("Error while closing config stream for module: " + moduleFile.getAbsolutePath(), io);
            }
        }
    }

    return module;
}

From source file:org.ejbca.util.CertTools.java

/**
 * Reads a certificate in PEM-format from an InputStream. The stream may contain other things,
 * the first certificate in the stream is read.
 *
 * @param certstream the input stream containing the certificate in PEM-format
 * @return Ordered Collection of Certificate, first certificate first, or empty Collection
 * @exception IOException if the stream cannot be read.
 * @exception CertificateException if the stream does not contain a correct certificate.
 *///from   w  ww.  j a v a2s. c  o  m
public static Collection<Certificate> getCertsFromPEM(InputStream certstream)
        throws IOException, CertificateException {
    if (log.isTraceEnabled()) {
        log.trace(">getCertfromPEM");
    }
    ArrayList<Certificate> ret = new ArrayList<Certificate>();
    String beginKeyTrust = "-----BEGIN TRUSTED CERTIFICATE-----";
    String endKeyTrust = "-----END TRUSTED CERTIFICATE-----";
    BufferedReader bufRdr = null;
    ByteArrayOutputStream ostr = null;
    PrintStream opstr = null;
    try {
        bufRdr = new BufferedReader(new InputStreamReader(certstream));
        while (bufRdr.ready()) {
            ostr = new ByteArrayOutputStream();
            opstr = new PrintStream(ostr);
            String temp;
            while ((temp = bufRdr.readLine()) != null
                    && !(temp.equals(CertTools.BEGIN_CERTIFICATE) || temp.equals(beginKeyTrust))) {
                continue;
            }
            if (temp == null) {
                if (ret.isEmpty()) {
                    // There was no certificate in the file
                    throw new IOException("Error in " + certstream.toString() + ", missing "
                            + CertTools.BEGIN_CERTIFICATE + " boundary");
                } else {
                    // There were certificates, but some blank lines or something in the end
                    // anyhow, the file has ended so we can break here.
                    break;
                }
            }
            while ((temp = bufRdr.readLine()) != null
                    && !(temp.equals(CertTools.END_CERTIFICATE) || temp.equals(endKeyTrust))) {
                opstr.print(temp);
            }
            if (temp == null) {
                throw new IOException("Error in " + certstream.toString() + ", missing "
                        + CertTools.END_CERTIFICATE + " boundary");
            }
            opstr.close();

            byte[] certbuf = Base64.decode(ostr.toByteArray());
            ostr.close();
            // Phweeew, were done, now decode the cert from file back to Certificate object
            Certificate cert = getCertfromByteArray(certbuf);
            ret.add(cert);
        }
    } finally {
        if (bufRdr != null) {
            bufRdr.close();
        }
        if (opstr != null) {
            opstr.close();
        }
        if (ostr != null) {
            ostr.close();
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<getcertfromPEM:" + ret.size());
    }
    return ret;
}

From source file:org.cesecore.util.CertTools.java

/**
 * Reads certificates in PEM-format from an InputStream. 
 * The stream may contain other things between the different certificates.
 * /*from w ww  . j a v a 2  s  . co m*/
 * @param certstream the input stream containing the certificates in PEM-format
 * @return Ordered List of Certificates, first certificate first, or empty List
 * @exception CertificateParsingException if the stream contains an incorrect certificate.
 */
public static List<Certificate> getCertsFromPEM(InputStream certstream) throws CertificateParsingException {
    if (log.isTraceEnabled()) {
        log.trace(">getCertfromPEM");
    }
    ArrayList<Certificate> ret = new ArrayList<Certificate>();
    String beginKeyTrust = "-----BEGIN TRUSTED CERTIFICATE-----";
    String endKeyTrust = "-----END TRUSTED CERTIFICATE-----";
    BufferedReader bufRdr = null;
    ByteArrayOutputStream ostr = null;
    PrintStream opstr = null;
    try {
        try {
            bufRdr = new BufferedReader(new InputStreamReader(certstream));
            while (bufRdr.ready()) {
                ostr = new ByteArrayOutputStream();
                opstr = new PrintStream(ostr);
                String temp;
                while ((temp = bufRdr.readLine()) != null
                        && !(temp.equals(CertTools.BEGIN_CERTIFICATE) || temp.equals(beginKeyTrust))) {
                    continue;
                }
                if (temp == null) {
                    if (ret.isEmpty()) {
                        // There was no certificate in the file
                        throw new CertificateParsingException("Error in " + certstream.toString() + ", missing "
                                + CertTools.BEGIN_CERTIFICATE + " boundary");
                    } else {
                        // There were certificates, but some blank lines or something in the end
                        // anyhow, the file has ended so we can break here.
                        break;
                    }
                }
                while ((temp = bufRdr.readLine()) != null
                        && !(temp.equals(CertTools.END_CERTIFICATE) || temp.equals(endKeyTrust))) {
                    opstr.print(temp);
                }
                if (temp == null) {
                    throw new IllegalArgumentException("Error in " + certstream.toString() + ", missing "
                            + CertTools.END_CERTIFICATE + " boundary");
                }
                opstr.close();

                byte[] certbuf = Base64.decode(ostr.toByteArray());
                ostr.close();
                // Phweeew, were done, now decode the cert from file back to Certificate object
                Certificate cert = getCertfromByteArray(certbuf);
                ret.add(cert);
            }

        } finally {
            if (bufRdr != null) {
                bufRdr.close();
            }
            if (opstr != null) {
                opstr.close();
            }
            if (ostr != null) {
                ostr.close();
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(
                "Exception caught when attempting to read stream, see underlying IOException", e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<getcertfromPEM:" + ret.size());
    }
    return ret;
}