Example usage for java.io BufferedReader ready

List of usage examples for java.io BufferedReader ready

Introduction

In this page you can find the example usage for java.io BufferedReader ready.

Prototype

public boolean ready() throws IOException 

Source Link

Document

Tells whether this stream is ready to be read.

Usage

From source file:org.apache.giraph.rexster.io.formats.TestRexsterLongDoubleFloatIOFormat.java

private ArrayList<Element> getRexsterContent(String name) throws Exception {
    ArrayList<Element> result = new ArrayList<Element>();
    /* get all the vertices */
    URL url = new URL("http://127.0.0.1:18182/graphs/" + name + "/tp/giraph/vertices");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

    InputStream is = conn.getInputStream();
    StringBuffer json = new StringBuffer();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    while (br.ready()) {
        json.append(br.readLine());/*w  w  w  .j av  a2  s . c  om*/
    }
    br.close();
    is.close();

    JSONObject results = new JSONObject(json.toString());
    JSONArray vertices = results.getJSONArray("results");
    for (int i = 0; i < vertices.length(); ++i) {
        JSONObject vertex = vertices.getJSONObject(i);
        long id = getId(vertex, "_id");
        result.add(new Element(id, 0));
    }

    /* get all the edges */
    url = new URL("http://127.0.0.1:18182/graphs/" + name + "/tp/giraph/edges");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

    is = conn.getInputStream();
    json = new StringBuffer();
    br = new BufferedReader(new InputStreamReader(is));
    while (br.ready()) {
        json.append(br.readLine());
    }
    br.close();
    is.close();

    results = new JSONObject(json.toString());
    JSONArray edges = results.getJSONArray("results");
    for (int i = 0; i < edges.length(); ++i) {
        JSONObject edge = edges.getJSONObject(i);
        long inV = getId(edge, "_inV");
        long outV = getId(edge, "_outV");
        long value = edge.getLong("value");

        for (int j = 0; j < result.size(); ++j) {
            Element element = result.get(j);
            if (element.id == outV) {
                element.add("[" + inV + "," + value + "]");
            }
        }
    }
    return result;
}

From source file:it.cnr.icar.eric.server.cms.CanonicalXMLValidationService.java

public ServiceOutput invoke(ServerRequestContext context, ServiceInput input, ServiceType service,
        InvocationController invocationController, UserType user) throws RegistryException {

    ServerRequestContext outputContext = context;

    try {/*w w  w.  j a v a 2s.  c om*/
        //ExtrinsicObjectType eo = (ExtrinsicObjectType)input.getRegistryObject();
        //RepositoryItem repositoryItem = input.getRepositoryItem();
        //DataHandler dh = repositoryItem.getDataHandler();
        InputSource inputSource = null;

        //registryObject MUST be ExrinsicObject or ExternalLink of objectType WSDL
        ExtrinsicObjectType ebExtrinsicObjectType = null;
        ExternalLinkType ebExternalLinkType = null;
        RegistryObjectType ebRegistryObjectType = input.getRegistryObject();
        if (ebRegistryObjectType instanceof ExtrinsicObjectType) {
            ebExtrinsicObjectType = (ExtrinsicObjectType) ebRegistryObjectType;
            RepositoryItem repositoryItem = input.getRepositoryItem();
            if (repositoryItem == null) {
                // Section 8.10 of the [ebRS] spec specifies that the RI
                // is optional. Log message and return
                log.info(ServerResourceBundle.getInstance().getString("message.noRepositoryItemIncluded",
                        new String[] { ebRegistryObjectType.getId() }));
                ServiceOutput so = new ServiceOutput();
                so.setOutput(outputContext);
                return so;
            }
            inputSource = new InputSource(repositoryItem.getDataHandler().getInputStream());
        } else if (ebRegistryObjectType instanceof ExternalLinkType) {
            ebExternalLinkType = (ExternalLinkType) ebRegistryObjectType;
            String urlStr = ebExternalLinkType.getExternalURI();
            urlStr = Utility.absolutize(Utility.getFileOrURLName(urlStr));
            URL url = new URL(urlStr);
            InputStream is = url.openStream();
            inputSource = new InputSource(is);
        } else {
            throw new ValidationException("RegistryObject not ExtrinsicObject or ExternalLink");
        }

        StreamSource schematronInvControlFileSrc = rm.getAsStreamSource(invocationController.getEoId());
        //Commenting out caching until we figure out how to reinit the stream position at begining
        //Currently if we cache then subsequent uses result in error: "Could not compile stylesheet"
        // The schematron XSLT file is expected to be stable and change infrequently. So, cache it.
        //if (schematronXSLTFileSrc == null) {
        schematronXSLTFileSrc = new StreamSource(this.getClass().getClassLoader()
                .getResourceAsStream("it/cnr/icar/eric/server/cms/conf/skeleton1-5.xsl"));
        //}

        if (log.isDebugEnabled()) {
            dumpStream(schematronInvControlFileSrc);
            dumpStream(schematronXSLTFileSrc);
        }

        // Use the Schematron Invocation Control File and Schematron XSLT to
        // create the XSLT Invocation Control File
        File xsltInvocationControlFile = File.createTempFile("InvocationControlFile_WSDLValidation", ".xslt");
        xsltInvocationControlFile.deleteOnExit();
        StreamResult xsltInvocationControlFileSR = new StreamResult(xsltInvocationControlFile);

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(schematronXSLTFileSrc);

        configureTransformer(transformer);

        // This call creates the XSLT Invocation Control File using
        // schematron invocation control file and schematron xslt files
        transformer.transform(schematronInvControlFileSrc, xsltInvocationControlFileSR);

        // Use generated XSLT Invocation Control File to validate the WSDL file(s)
        StreamSource xsltInvocationControlFileSrc = new StreamSource(xsltInvocationControlFile);
        transformer = tFactory.newTransformer(xsltInvocationControlFileSrc);

        configureTransformer(transformer);

        //Set respository item as parameter
        transformer.setParameter("repositoryItem", input.getRegistryObject().getId());

        if ((ebExtrinsicObjectType != null)
                && (ebExtrinsicObjectType.getMimeType().equalsIgnoreCase("application/zip"))) {
            ArrayList<File> files = Utility.unZip(TMP_DIR, inputSource.getByteStream());

            //Now iterate and create ExtrinsicObject - Repository Item pair for each unzipped file
            Iterator<File> iter = files.iterator();
            while (iter.hasNext()) {
                File file = iter.next();
                @SuppressWarnings("resource")
                BufferedReader br = new BufferedReader(new FileReader(file));
                StringBuffer sb = new StringBuffer();
                while (br.ready()) {
                    sb.append(br.readLine());
                }
                StringReader reader = new StringReader(sb.toString());
                StreamSource inputSrc = new StreamSource(reader);
                validateXMLFile(inputSrc, transformer);
            }
        } else {
            //Following will fail if there are unresolved imports in the WSDL
            StreamSource inputSrc = new StreamSource(inputSource.getByteStream());
            //dumpStream(inputSrc);
            //inputSrc = new StreamSource(inputSource.getByteStream());
            validateXMLFile(inputSrc, transformer);
        }
    } catch (ValidationException e) {
        if (outputContext != context) {
            outputContext.rollback();
        }
        log.error(ServerResourceBundle.getInstance().getString("message.errorValidatingXML"), e);
        throw e;
    } catch (Exception e) {
        if (outputContext != context) {
            outputContext.rollback();
        }
        log.error(ServerResourceBundle.getInstance().getString("message.errorValidatingXML"), e);
        throw new RegistryException(e);
    }

    ServiceOutput so = new ServiceOutput();
    so.setOutput(outputContext);

    if (outputContext != context) {
        outputContext.commit();
    }

    return so;
}

From source file:org.wso2.carbon.automation.extensions.servers.webserver.SimpleWebServer.java

public void run() {
    ServerSocket serverSocket = null;
    Socket connectionSocket = null;
    try {//from  w w w  .j  a  v a2s. c o m
        log.info("Trying to bind to localhost on port " + Integer.toString(port) + "...");
        serverSocket = new ServerSocket(port);
        log.info("Running Simple WebServer!\n");
        connectionSocket = serverSocket.accept();
        connectionSocket.setSoTimeout(30000);
        //go in a infinite loop, wait for connections, process request, send response
        while (running) {
            log.info("\nReady, Waiting for requests...\n");
            try {
                //this call waits/blocks until someone connects to the port we
                BufferedReader input;
                if (!connectionSocket.isClosed()) {
                    InetAddress client = connectionSocket.getInetAddress();
                    log.info(client.getHostName() + " connected to server.\n");
                    input = new BufferedReader(
                            new InputStreamReader(connectionSocket.getInputStream(), Charset.defaultCharset()));
                    if (input.ready()) {
                        DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
                        httpHandler(input, output);
                    }
                }
                //Prepare a outputStream. This will be used sending back our response
                //(header + requested file) to the client.
            } catch (Exception e) { //catch any errors, and print them
                log.info("\nError:" + e.getMessage());
                running = false;
            }
        }
    } catch (Exception e) {
        log.error("\nFatal Error:" + e.getMessage());
        running = false;
    } finally {
        try {
            if (connectionSocket != null) {
                connectionSocket.close();
                serverSocket.close();
            }
        } catch (IOException e) {
            log.error("Error while shutting down server sockets", e);
        }
    }
}

From source file:uk.bl.dpt.qa.ProcessIsolatedTika.java

/**
 * Extract the tika-server jar and prepare for execution
 *//* w ww .j  a  v a2  s  . c  om*/
private void init() {

    if (gLocalJar != null)
        return;

    // get tika version from manifest file
    InputStream manifest = ProcessIsolatedTika.class.getClassLoader().getResourceAsStream(MANIFEST);
    if (manifest != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(manifest));
        String line = "";
        try {
            while (reader.ready()) {
                line = reader.readLine();
                if (line.startsWith(TIKA_VER_KEY)) {
                    TIKA_VERSION = line.substring(TIKA_VER_KEY.length() + 2).trim();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (manifest != null) {
                try {
                    manifest.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    TIKA_JAR = "tika-server-" + TIKA_VERSION + ".jar";

    // copy jar from resources folder to temporary space
    try {
        gLocalJar = File.createTempFile("tika-server-", ".jar");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    boolean found = false;
    InputStream jar = ProcessIsolatedTika.class.getClassLoader().getResourceAsStream(TIKA_JAR);
    if (jar != null) {
        gLogger.info("Found server jar: /");
        //Tools.copyStreamToFile(jar, gLocalJar);
        found = true;
    }
    if (!found) {
        jar = ProcessIsolatedTika.class.getClassLoader().getResourceAsStream("lib/" + TIKA_JAR);
        if (jar != null) {
            gLogger.info("Found server jar: lib/");
            //Tools.copyStreamToFile(jar, gLocalJar);
            found = true;
        }
    }
    if (!found) {
        final String JARFILE = "target/resources/" + TIKA_JAR;
        try {
            jar = new FileInputStream(JARFILE);
            gLogger.info("Found jar in filesystem");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            gLogger.info("Cannot find jar");
            e.printStackTrace();
        }
        //IOUtils.copy(new FileInputStream(new File(JARFILE)), new FileOutputStream(gLocalJar));
        found = true;
    }

    try {
        FileOutputStream fos = new FileOutputStream(gLocalJar);
        IOUtils.copy(jar, fos);
        fos.close();
        jar.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    gLocalJar.deleteOnExit();

    gLogger.info("Temp jar: " + gLocalJar.getAbsolutePath() + ", size: " + gLocalJar.length());

}

From source file:com.pseudosudostudios.jdd.activities.GameActivity.java

private void loadGame(Bundle saved) {
    Log.i("Load game", "Loading game");
    if (bg == null)
        bg = new Grid(this);
    File dataFile = new File(getFilesDir(), saveDataFileName);
    try {/* w ww  . j  a  v  a 2  s. c o m*/
        BufferedReader read = new BufferedReader(new FileReader(dataFile));
        String input = "";
        while (read.ready())
            input += read.readLine();
        read.close();

        JSONObject master = new JSONObject(input);
        JSONArray tilesFromFile = master.getJSONArray(arrayKey);
        Tile[][] loadedTile = new Tile[3][3];
        Tile[][] solution = new Tile[3][3];
        int jsonIndex = 0;
        for (int row = 0; row < loadedTile.length; row++) {
            for (int col = 0; col < loadedTile[row].length; col++) {
                JSONObject currTile = tilesFromFile.getJSONObject(jsonIndex);
                Point center = new Point(currTile.getInt(pointX), currTile.getInt(pointY));
                int north = currTile.getInt(northKey);
                int east = currTile.getInt(eastKey);
                int south = currTile.getInt(southKey);
                int west = currTile.getInt(westKey);
                loadedTile[row][col] = new Tile(this, center, north, east, south, west);

                jsonIndex++;
            }
        }
        jsonIndex = 0;
        JSONArray solJSon = master.getJSONArray(onSaveSolution);
        for (int row = 0; row < solution.length; row++) {
            for (int col = 0; col < solution[row].length; col++) {
                JSONObject currTile = solJSon.getJSONObject(jsonIndex);
                Point center = new Point(currTile.getInt(pointX), currTile.getInt(pointY));
                int north = currTile.getInt(northKey);
                int east = currTile.getInt(eastKey);
                int south = currTile.getInt(southKey);
                int west = currTile.getInt(westKey);
                solution[row][col] = new Tile(this, center, north, east, south, west);
                jsonIndex++;
            }
        }
        bg.moves = master.getInt(moveKey);
        bg.setTileArray(loadedTile, solution, master.getInt(moveKey), master.getLong(onSaveTime),
                master.getInt(jsonTileSize));
        bg.setDifficulty(master.getString(levelKey));
        Grid.numberOfColors = master.getInt(numColorsKey);
        Tile.initPaints();
        Log.i("Load game", "Game Loaded");
    } catch (Exception e) {
        Log.i("Load game", "Error loading game");
        if (dataFile != null)
            dataFile.delete();
        e.printStackTrace();
        showInstructions();
    }
    bg.invalidate();
}

From source file:org.apache.maven.plugins.scmpublish.ScmPublishPublishScmMojo.java

/**
 * Copy and normalize newlines.//from   w w  w.j  ava  2 s .  c  o m
 *
 * @param srcFile  the source file
 * @param destFile the destination file
 * @throws IOException
 */
private void copyAndNormalizeNewlines(File srcFile, File destFile) throws IOException {
    BufferedReader in = null;
    PrintWriter out = null;
    try {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile), siteOutputEncoding));
        out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(destFile), siteOutputEncoding));
        String line;
        while ((line = in.readLine()) != null) {
            if (in.ready()) {
                out.println(line);
            } else {
                out.print(line);
            }
        }
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
    }
}

From source file:edu.du.penrose.systems.fedoraApp.tests.UtilModsToFileTest.java

void writeModsToFile(String outputDirName, File inputFile, int fileCount) {

    BufferedReader br = null;
    BufferedWriter bw = null;/*w  w w. j  a va 2s . c  o  m*/
    try {
        File outFile = null;
        FileInputStream fis = new FileInputStream(inputFile);
        FileOutputStream fos = null;

        DataInputStream in = new DataInputStream(fis);
        br = new BufferedReader(new InputStreamReader(in));

        String doucmentType = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        String oneLine = null;
        while (br.ready()) {
            oneLine = br.readLine();
            if (oneLine.contains("<mods:mods")) {

                outFile = new File(outputDirName + "\\mods_" + fileCount + ".xml");
                fos = new FileOutputStream(outFile);

                bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
                bw.write(doucmentType);
                bw.newLine();
                while (!oneLine.contains("</mods:mods")) { // null pointer on premature end of file.
                    bw.write(oneLine);
                    bw.newLine();
                    oneLine = br.readLine();
                }
                bw.write(oneLine);
                bw.newLine();
                bw.close();
                fileCount++;
            }
        } // while
    } catch (Exception e) {
        String errorMsg = "Exception:" + e;
        System.out.println(errorMsg);
    } finally {
        try {
            br.close();
            bw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:de.tudarmstadt.ukp.csniper.webapp.search.cqp.CqpQuery.java

/**
 * Checks the stderr for errors thrown by cqp.
 *///w  ww  .  ja  v  a  2s.  co  m
private void checkError() throws InvalidDataAccessResourceUsageException {
    String line;
    try {
        BufferedReader _br = new BufferedReader(
                new InputStreamReader(cqpProcess.getErrorStream(), engine.getEncoding(corpus)));

        while (_br.ready()) {
            line = _br.readLine();
            if (log.isErrorEnabled()) {
                log.error(line);
            }
            error.add(line);
        }
    } catch (IOException e) {
        throw new InvalidDataAccessResourceUsageException(e.getMessage());
    }

    if (!error.isEmpty()) {
        throw new InvalidDataAccessResourceUsageException(join(error, "\n"));
    }
}

From source file:org.apache.streams.gnip.flickr.test.FlickrEDCSerDeTest.java

@Test
public void Tests() throws Exception {
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);

    InputStream is = FlickrEDCSerDeTest.class.getResourceAsStream("/FlickrEDC.xml");
    if (is == null)
        System.out.println("null");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
    xmlMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
    xmlMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, Boolean.FALSE);

    ObjectMapper jsonMapper = new ObjectMapper();

    try {//from w  w  w. j a v  a  2 s  . c o m
        while (br.ready()) {
            String line = br.readLine();
            //LOGGER.debug(line);

            Object activityObject = xmlMapper.readValue(line, Object.class);

            String jsonObject = jsonMapper.writeValueAsString(activityObject);

            //LOGGER.debug(jsonObject);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    }
}

From source file:petascope.wcps.server.test.GrammarTestOnline.java

/**
 * Send an XML request to the WCPS server. Hopefully it will succeed.
 * Returns a message on error or null otherwise.
 **///from  w  w w.ja  v a 2  s  .  c o m
public String runOneTest(String param, String query) throws MalformedURLException, IOException {

    //        System.out.println("--------------------");
    //        System.out.println(query);
    //        System.out.println("\t--------------------");

    // connect to the servlet
    URL servlet = new URL(PetascopeURL);
    HttpURLConnection conn = (HttpURLConnection) servlet.openConnection();

    // inform the connection that we will send output and accept input
    conn.setDoInput(true);
    conn.setDoOutput(true);

    // Don't use a cached version of URL connection.
    conn.setUseCaches(false);
    conn.setDefaultUseCaches(false);

    // Send POST request
    conn.setRequestMethod("POST");

    // Specify the content type that we will send binary data
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    String data = param + "=" + StringUtil.urlencode(query);
    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.writeBytes(data);
    out.flush();
    out.close();

    BufferedReader cgiOutput = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line1 = cgiOutput.readLine();
    String line2 = cgiOutput.readLine();
    String line3 = cgiOutput.readLine();
    System.out.println("\t" + line1);
    System.out.println("\t" + line2);
    System.out.println("\t" + line3);

    if (line1 != null && line2 != null && line3 != null && line2.equals("<h1>An error has occured</h1>")) {
        while (cgiOutput.ready()) {
            System.out.println("\t" + cgiOutput.readLine());
        }
        //            System.out.println("Error executing query: ");
        String error = line3.substring(10, line3.length() - 4);
        //            System.out.println("\t" + error);
        return error;
    } else {
        return null;
    }

}