Example usage for java.io BufferedInputStream read

List of usage examples for java.io BufferedInputStream read

Introduction

In this page you can find the example usage for java.io BufferedInputStream read.

Prototype

public synchronized int read() throws IOException 

Source Link

Document

See the general contract of the read method of InputStream.

Usage

From source file:mamo.vanillaVotifier.JsonConfig.java

@Override
public synchronized void load() throws IOException, InvalidKeySpecException {
    if (!configFile.exists()) {
        BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json"));
        StringBuilder stringBuilder = new StringBuilder();
        int i;/*  w w  w . j a v a 2 s  . c  o m*/
        while ((i = in.read()) != -1) {
            stringBuilder.append((char) i);
        }
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(configFile));
        for (char c : stringBuilder.toString()
                .replaceAll("\\u000D\\u000A|[\\u000A\\u000B\\u000C\\u000D\\u0085\\u2028\\u2029]",
                        System.getProperty("line.separator"))
                .toCharArray()) {
            out.write((int) c);
        }
        out.flush();
        out.close();
    }
    BufferedInputStream in = new BufferedInputStream(JsonConfig.class.getResourceAsStream("config.json"));
    JSONObject defaultConfig = new JSONObject(new JSONTokener(in));
    in.close();
    JSONObject config = new JSONObject(
            new JSONTokener(new BufferedInputStream(new FileInputStream(configFile))));
    boolean save = JsonUtils.merge(defaultConfig, config);
    configVersion = config.getInt("config-version");
    if (configVersion == 2) {
        v2ToV3(config);
        configVersion = 3;
        save = true;
    }
    logFile = new File(config.getString("log-file"));
    inetSocketAddress = new InetSocketAddress(config.getString("ip"), config.getInt("port"));
    publicKeyFile = new File(config.getJSONObject("key-pair-files").getString("public"));
    privateKeyFile = new File(config.getJSONObject("key-pair-files").getString("private"));
    if (!publicKeyFile.exists() && !privateKeyFile.exists()) {
        KeyPair keyPair = RsaUtils.genKeyPair();
        PemWriter publicPemWriter = new PemWriter(new BufferedWriter(new FileWriter(publicKeyFile)));
        publicPemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
        publicPemWriter.flush();
        publicPemWriter.close();
        PemWriter privatePemWriter = new PemWriter(new BufferedWriter(new FileWriter(privateKeyFile)));
        privatePemWriter.writeObject(new PemObject("RSA PRIVATE KEY", keyPair.getPrivate().getEncoded()));
        privatePemWriter.flush();
        privatePemWriter.close();
    }
    if (!publicKeyFile.exists()) {
        throw new PublicKeyFileNotFoundException();
    }
    if (!privateKeyFile.exists()) {
        throw new PrivateKeyFileNotFoundException();
    }
    PemReader publicKeyPemReader = new PemReader(new BufferedReader(new FileReader(publicKeyFile)));
    PemReader privateKeyPemReader = new PemReader(new BufferedReader(new FileReader(privateKeyFile)));
    PemObject publicPemObject = publicKeyPemReader.readPemObject();
    if (publicPemObject == null) {
        throw new InvalidPublicKeyFileException();
    }
    PemObject privatePemObject = privateKeyPemReader.readPemObject();
    if (privatePemObject == null) {
        throw new InvalidPrivateKeyFileException();
    }
    keyPair = new KeyPair(RsaUtils.bytesToPublicKey(publicPemObject.getContent()),
            RsaUtils.bytesToPrivateKey(privatePemObject.getContent()));
    publicKeyPemReader.close();
    privateKeyPemReader.close();
    rconConfigs = new ArrayList<RconConfig>();
    for (int i = 0; i < config.getJSONArray("rcon-list").length(); i++) {
        JSONObject jsonObject = config.getJSONArray("rcon-list").getJSONObject(i);
        RconConfig rconConfig = new RconConfig(
                new InetSocketAddress(jsonObject.getString("ip"), jsonObject.getInt("port")),
                jsonObject.getString("password"));
        for (int j = 0; j < jsonObject.getJSONArray("commands").length(); j++) {
            rconConfig.getCommands().add(jsonObject.getJSONArray("commands").getString(j));
        }
        rconConfigs.add(rconConfig);
    }
    loaded = true;
    if (save) {
        save();
    }
}

From source file:com.pipinan.githubcrawler.GithubCrawler.java

/**
 *
 * @param username the owner name of respoitory
 * @param reponame the name of respoitory
 * @param path which folder would you like to save the zip file
 * @throws IOException/*  ww w .j  a  v a 2 s.c  o m*/
 */
public void crawlRepoZip(String username, String reponame, String path) throws IOException {
    GHRepository repo = github.getRepository(username + "/" + reponame);

    HttpClient httpclient = getHttpClient();
    //the url pattern is https://github.com/"USER_NAME"/"REPO_NAME"/archive/master.zip
    HttpGet httpget = new HttpGet("https://github.com/" + username + "/" + reponame + "/archive/master.zip");
    HttpResponse response = httpclient.execute(httpget);
    try {
        System.out.println(response.getStatusLine());
        if (response.getStatusLine().toString().contains("200 OK")) {

            //the header "Content-Disposition: attachment; filename=JSON-java-master.zip" can find the filename
            String filename = null;
            Header[] headers = response.getHeaders("Content-Disposition");
            for (Header header : headers) {
                System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue());
                String tmp = header.getValue();
                filename = tmp.substring(tmp.lastIndexOf("filename=") + 9);
            }

            if (filename == null) {
                System.err.println("Can not find the filename in the response.");
                System.exit(-1);
            }

            HttpEntity entity = response.getEntity();

            BufferedInputStream bis = new BufferedInputStream(entity.getContent());
            String filePath = path + filename;
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
            int inByte;
            while ((inByte = bis.read()) != -1) {
                bos.write(inByte);
            }
            bis.close();
            bos.close();

            EntityUtils.consume(entity);
        }
    } finally {

    }

}

From source file:de.luhmer.owncloudnewsreader.async_tasks.GetImageThreaded.java

@Override
public void run() {
    try {//  ww w  .j  a v  a 2 s.c om
        File cacheFile = ImageHandler.getFullPathOfCacheFile(WEB_URL_TO_FILE.toString(), rootPath);

        DatabaseConnectionOrm dbConn = new DatabaseConnectionOrm(cont);
        Feed feed = dbConn.getFeedById(ThreadId);
        if (!cacheFile.isFile() || feed.getAvgColour() == null) {
            File dir = new File(rootPath);
            dir.mkdirs();
            cacheFile = ImageHandler.getFullPathOfCacheFile(WEB_URL_TO_FILE.toString(), rootPath);
            //cacheFile.createNewFile();

            /* Open a connection to that URL. */
            URLConnection urlConn = WEB_URL_TO_FILE.openConnection();

            urlConn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = urlConn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            /*
             * Read bytes to the Buffer until there is nothing more to read(-1).
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            //If the file is not empty
            if (baf.length() > 0) {
                bmp = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.length());

                FileOutputStream fos = new FileOutputStream(cacheFile);
                fos.write(baf.toByteArray());
                fos.close();
            }
        }
        //return cacheFile.getPath();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    //return bmp;

    if (imageDownloadFinished != null)
        imageDownloadFinished.DownloadFinished(ThreadId, bmp);

    super.run();
}

From source file:com.zbrown.droidsteal.activities.UpdateChecker.java

private void checkupdate() {
    if (alertUpdate != null && alertUpdate.isShowing()) {
        // There is already an download message
        return;//  w  w w.ja  va 2s .c  o  m
    }
    Log.v(TAG, "Checking updates...");
    try {
        URL updateURL = new URL(versionUrl);
        URLConnection conn = updateURL.openConnection();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);

        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        final String s = new String(baf.toByteArray());

        /* Get current Version Number */
        String curVersion = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;

        Log.d(TAG, "Current version is: " + curVersion + " and new one is: " + s);
        /* Is a higher version than the current already out? */
        if (!curVersion.equals(s)) {
            /* Post a Handler for the UI to pick up and open the Dialog */
            if (alertUpdate == null || !alertUpdate.isShowing()) {
                if (alertError != null && alertError.isShowing())
                    alertError.dismiss();
                mHandler.post(showUpdate);
            }
        } else
            Log.v(TAG, "The software is updated to the latest version: " + s);
    } catch (Exception e) {
        e.printStackTrace();
        // if(alertError==null || !alertError.isShowing())
        // mHandler.post(showError);
    }
}

From source file:es.prodevelop.gvsig.mini.tasks.namefinder.NameFinderFunc.java

@Override
public boolean execute() {

    NameFinder NFTask = new NameFinder();
    String query = new String(NFTask.URL + NFTask.parms).replaceAll(" ", "%20");

    try {/*from w w w  .j a  v  a  2s . c  o  m*/
        log.log(Level.FINE, query);
        InputStream is = Utils.openConnection(query);
        BufferedInputStream bis = new BufferedInputStream(is);

        /* Read bytes to the Buffer until there is nothing more to read(-1). */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            if (this.isCanceled()) {
                res = TaskHandler.CANCELED;
                return true;
            }
            baf.append((byte) current);

        }

        Vector result = NFTask.parse(baf.toByteArray());

        if (result != null) {
            // handler.sendEmptyMessage(map.POI_SUCCEEDED);
            Named[] searchRes = new Named[result.size()];
            desc = new String[result.size()];
            for (int i = 0; i < result.size(); i++) {
                Named n = (Named) result.elementAt(i);
                desc[i] = n.description;
                searchRes[i] = n;

                if (this.isCanceled()) {
                    res = TaskHandler.CANCELED;
                    return true;
                }
            }

            if (this.isCanceled()) {
                res = TaskHandler.CANCELED;
                return true;
            }
            nm = new NamedMultiPoint(searchRes);

            res = TaskHandler.FINISHED;
        } else {
            res = TaskHandler.CANCELED;
        }
    } catch (IOException e) {
        if (e instanceof UnknownHostException) {
            res = TaskHandler.NO_RESPONSE;
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Namefinder" + e.getMessage(), e);
    } finally {

    }
    return true;
}

From source file:eionet.gdem.utils.Utils.java

/**
 *
 * @param f//from  w  w  w . j  av  a2s.  com
 * @param algorithm
 * @return
 * @throws Exception
 */
public static String digest(File f, String algorithm) throws Exception {

    byte[] dstBytes = new byte[16];

    MessageDigest md;

    md = MessageDigest.getInstance(algorithm);

    BufferedInputStream in = null;

    int theByte = 0;
    try {
        in = new BufferedInputStream(new FileInputStream(f));
        while ((theByte = in.read()) != -1) {
            md.update((byte) theByte);
        }
    } finally {
        try {
            in.close();
        } catch (Exception e) {
        }
    }
    dstBytes = md.digest();
    md.reset();

    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < dstBytes.length; i++) {
        Byte byteWrapper = new Byte(dstBytes[i]);
        int k = byteWrapper.intValue();
        String s = Integer.toHexString(k);
        if (s.length() == 1) {
            s = "0" + s;
        }
        buf.append(s.substring(s.length() - 2));
    }

    return buf.toString();
}

From source file:com.vtls.opensource.jhove.JHOVEDocumentFactory.java

/**
 * Get a JHOVE Document from a {@link URL} source
 * @param _uri  a resource URL/* w  ww . ja  v a 2s .com*/
 * @param _stream an input stream code
 * @return a JDOM Document
 * @throws IOException 
 * @throws JDOMException 
 */
public Document getDocument(InputStream _stream, String _uri) throws IOException, JDOMException {
    RepInfo representation = new RepInfo(_uri);

    File file = File.createTempFile("vtls-jhove-", "");
    file.deleteOnExit();

    BufferedOutputStream output_stream = new BufferedOutputStream(new FileOutputStream(file));
    BufferedInputStream input_stream = new BufferedInputStream(_stream);

    int stream_byte;
    while ((stream_byte = input_stream.read()) != -1) {
        output_stream.write(stream_byte);
    }

    output_stream.flush();
    output_stream.close();
    input_stream.close();

    representation.setSize(file.length());
    representation.setLastModified(new Date());
    populateRepresentation(representation, file);

    file.delete();

    return getDocumentFromRepresentation(representation);
}

From source file:jeffaschenk.tomcat.instance.generator.builders.TomcatInstanceBuilderHelper.java

/**
 * Pull specified Version of Tomcat from Internet Download Site ...
 *
 * @param GENERATION_LOGGER Logger//from w ww  .j av  a2  s. co  m
 * @param tomcatInstance    POJO
 */
protected static boolean pullTomcatVersionFromApacheMirror(GenerationLogger GENERATION_LOGGER,
        TomcatAvailableArchives tomcatAvailableArchives, TomcatInstance tomcatInstance) {
    /**
     * First determine the Latest Release based upon our Short name.
     */
    TomcatArchive tomcatArchive = tomcatAvailableArchives
            .getAvailableArchiveByShortName(tomcatInstance.getTomcatVersion());
    if (tomcatArchive == null || tomcatArchive.getShortVersion() == null) {
        GENERATION_LOGGER.error("Unable to determine a Download Archive for Tomcat Version: "
                + tomcatInstance.getTomcatVersion() + ", Notify Engineering to Support new Version of Tomcat!");
        return false;
    }
    tomcatInstance.setTomcatArchive(tomcatArchive); // Set a Reference to archive used.
    /**
     * Now check to see if the Artifact has already been pulled?
     */
    if (validateTomcatDownloadedVersion(GENERATION_LOGGER, tomcatInstance, false)) {
        GENERATION_LOGGER.info("Using previously Downloaded Archive: " + tomcatArchive.getName() + ".zip");
        return true;
    }
    /**
     * Proceed to Pull Archive ...
     */
    GENERATION_LOGGER.info("Pulling Tomcat Version from Apache Mirror ...");

    URL url = null;
    URLConnection con = null;
    int i;
    try {
        /**
         * Construct the Apache Mirror URL to Pull Tomcat Instance.
         * Assume a V8 version ...
         */
        String tcHeadVersion;
        if (tomcatInstance.getTomcatVersion().startsWith("v8")) {
            tcHeadVersion = DefaultDefinitions.APACHE_TOMCAT_8_MIRROR_HEAD;
        } else if (tomcatInstance.getTomcatVersion().startsWith("v9")) {
            tcHeadVersion = DefaultDefinitions.APACHE_TOMCAT_9_MIRROR_HEAD;
        } else {
            GENERATION_LOGGER.error("Unable to determine a Download URL for Tomcat Version: "
                    + tomcatInstance.getTomcatVersion()
                    + ", Notify Engineering to Support new Version of Tomcat!");
            return false;
        }
        /**
         * Now construct the URL to use to Pull over Internet.
         */
        url = new URL(tomcatAvailableArchives.getApacheMirrorHeadUrl() + "/" + tcHeadVersion + "/v"
                + tomcatArchive.getShortVersion() + "/bin/" + tomcatArchive.getName() + ".zip");
        GENERATION_LOGGER.info("Using URL for Downloading Artifact: " + url.toString());

        con = url.openConnection();
        BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(tomcatInstance.getDestinationFolder().getAbsolutePath() + File.separator
                        + tomcatArchive.getName() + ".zip"));
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.flush();
        bis.close();
        GENERATION_LOGGER.info("Successfully Pulled Tomcat Version from Apache Mirror ...");
        return true;
    } catch (MalformedInputException malformedInputException) {
        malformedInputException.printStackTrace();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
    /**
     * Indicate a Failure has Occurred
     */
    return false;
}

From source file:it.eng.spagobi.analiticalmodel.execution.service.PrintNotesAction.java

public void doService() {
    logger.debug("IN");

    ExecutionInstance executionInstance;
    executionInstance = getContext().getExecutionInstance(ExecutionInstance.class.getName());
    String executionIdentifier = new BIObjectNotesManager()
            .getExecutionIdentifier(executionInstance.getBIObject());
    Integer biobjectId = executionInstance.getBIObject().getId();
    List globalObjNoteList = null;
    try {/* w w w.  j a  v a  2 s . c o m*/
        globalObjNoteList = DAOFactory.getObjNoteDAO().getListExecutionNotes(biobjectId, executionIdentifier);
    } catch (EMFUserError e1) {
        logger.error("Error in retrieving obj notes", e1);
        return;
    } catch (Exception e1) {
        logger.error("Error in retrieving obj notes", e1);
        return;
    }
    //mantains only the personal notes and others one only if they have PUBLIC status
    List objNoteList = new ArrayList();
    UserProfile profile = (UserProfile) this.getUserProfile();
    String userId = (String) profile.getUserId();
    for (int i = 0, l = globalObjNoteList.size(); i < l; i++) {
        ObjNote objNote = (ObjNote) globalObjNoteList.get(i);
        if (objNote.getIsPublic()) {
            objNoteList.add(objNote);
        } else if (objNote.getOwner().equalsIgnoreCase(userId)) {
            objNoteList.add(objNote);
        }
    }

    String outputType = "PDF";
    RequestContainer requestContainer = getRequestContainer();
    SourceBean sb = requestContainer.getServiceRequest();
    outputType = (String) sb.getAttribute(SBI_OUTPUT_TYPE);
    if (outputType == null)
        outputType = "PDF";

    String templateStr = getTemplateTemplate();

    //JREmptyDataSource conn=new JREmptyDataSource(1);
    //Connection conn = getConnection("SpagoBI",getHttpSession(),profile,obj.getId().toString());      
    JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(objNoteList);

    HashedMap parameters = new HashedMap();
    parameters.put("PARAM_OUTPUT_FORMAT", outputType);
    parameters.put("TITLE", executionInstance.getBIObject().getLabel());

    UUIDGenerator uuidGen = UUIDGenerator.getInstance();
    UUID uuid_local = uuidGen.generateTimeBasedUUID();
    String executionId = uuid_local.toString();
    executionId = executionId.replaceAll("-", "");
    //Creta etemp file
    String dirS = System.getProperty("java.io.tmpdir");
    File dir = new File(dirS);
    dir.mkdirs();
    String fileName = "notes" + executionId;
    OutputStream out = null;
    File tmpFile = null;
    try {
        tmpFile = File.createTempFile(fileName, "." + outputType, dir);
        out = new FileOutputStream(tmpFile);
        StringBufferInputStream sbis = new StringBufferInputStream(templateStr);
        logger.debug("compiling report");
        JasperReport report = JasperCompileManager.compileReport(sbis);
        //report.setProperty("", )
        logger.debug("filling report");
        JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, datasource);
        JRExporter exporter = null;
        if (outputType.equalsIgnoreCase("PDF")) {
            exporter = (JRExporter) Class.forName("net.sf.jasperreports.engine.export.JRPdfExporter")
                    .newInstance();
            if (exporter == null)
                exporter = new JRPdfExporter();
        } else {
            exporter = (JRExporter) Class.forName("net.sf.jasperreports.engine.export.JRRtfExporter")
                    .newInstance();
            if (exporter == null)
                exporter = new JRRtfExporter();
        }

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        logger.debug("exporting report");
        exporter.exportReport();

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        return;
    } finally {
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error("Error closing output", e);
        }
    }

    String mimeType;
    if (outputType.equalsIgnoreCase("RTF")) {
        mimeType = "application/rtf";
    } else {
        mimeType = "application/pdf";
    }

    HttpServletResponse response = getHttpResponse();
    response.setContentType(mimeType);
    response.setHeader("Content-Disposition", "filename=\"report." + outputType + "\";");
    response.setContentLength((int) tmpFile.length());
    try {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
        int b = -1;
        while ((b = in.read()) != -1) {
            response.getOutputStream().write(b);
        }
        response.getOutputStream().flush();
        in.close();
    } catch (Exception e) {
        logger.error("Error while writing the content output stream", e);
    } finally {
        tmpFile.delete();
    }

    logger.debug("OUT");

}