Example usage for java.io InputStream available

List of usage examples for java.io InputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking, which may be 0, or 0 when end of stream is detected.

Usage

From source file:de.quist.samy.remocon.RemoteSession.java

private String initialize() throws UnknownHostException, IOException {
    logger.debug("Creating socket for host " + host + " on port " + port);

    socket = new Socket();
    socket.connect(new InetSocketAddress(host, port), 5000);

    logger.debug("Socket successfully created and connected");
    InetAddress localAddress = socket.getLocalAddress();
    logger.debug("Local address is " + localAddress.getHostAddress());

    logger.debug("Sending registration message");
    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    writer.append((char) 0x00);
    writeText(writer, APP_STRING);/*w  w  w.j  av  a  2  s. c  o m*/
    writeText(writer, getRegistrationPayload(localAddress.getHostAddress()));
    writer.flush();

    InputStream in = socket.getInputStream();
    reader = new InputStreamReader(in);
    String result = readRegistrationReply(reader);
    //sendPart2();
    int i;
    while ((i = in.available()) > 0) {
        in.skip(i);
    }
    return result;
}

From source file:com.clican.pluto.transaction.resources.memory.XAFileSetResourceMemoryImpl.java

public int prepare(Xid xid) throws XAException {
    InputStream is = null;
    try {/*from w w w . j  av a2s.c om*/
        for (File f : modifiedDataMapping.get(xid).keySet()) {
            if (f.exists()) {
                is = new FileInputStream(f);
                byte[] data = new byte[is.available()];
                is.read(data);
                oldDataMapping.get(xid).put(f, data);
            } else {
                oldDataMapping.get(xid).put(f, null);
            }
        }
    } catch (Exception e) {
        log.error("", e);
        throw new XAException(XAException.XA_RBBASE);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }
    return XA_OK;
}

From source file:com.wabacus.config.database.type.AbsDatabaseType.java

public void setBlobValue(int iindex, InputStream in, PreparedStatement pstmt) throws SQLException {
    if (in == null) {
        pstmt.setBinaryStream(iindex, null, 0);
    } else {/*  w w w  .  j  a v  a  2s .c  om*/
        try {
            pstmt.setBinaryStream(iindex, in, in.available());
        } catch (IOException e) {
            throw new WabacusRuntimeException("??", e);
        }
    }
}

From source file:com.qihoo.permmgr.PermManager.java

/**
 * asset/permmgr???/*from  ww w .  j  ava  2s . com*/
 */
private boolean checkFileSize(String paramString, File paramFile) {
    AssetManager assetManager = mContext.getAssets();
    try {
        InputStream is = assetManager.open("permmgr/" + paramString);
        if (is.available() == paramFile.length()) {
            return true;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.funzio.pure2D.atlas.JsonAtlas.java

protected void load(final InputStream stream, final float scale) throws IOException, JSONException {
    Log.v(TAG, "load()");

    final StringBuilder sb = new StringBuilder();
    while (stream.available() > 0) {
        final byte[] bytes = new byte[stream.available()];
        stream.read(bytes);//from   ww  w  .  ja  va2 s .  co  m
        sb.append(new String(bytes));
    }
    stream.close();

    parse(sb.toString(), scale);
}

From source file:cz.zcu.kiv.eegdatabase.wui.core.license.impl.LicenseServiceImpl.java

@Override
@Transactional/*ww  w . j a v  a2s.  c  o  m*/
public void update(License transientObject) {
    try {
        // XXX WORKAROUND for Hibernate pre 4.0, update entity with blob this way.
        License merged = licenseDao.merge(transientObject);
        InputStream fileContentStream = transientObject.getFileContentStream();
        if (fileContentStream != null) {
            Blob createBlob;
            createBlob = licenseDao.getSessionFactory().getCurrentSession().getLobHelper()
                    .createBlob(fileContentStream, fileContentStream.available());
            merged.setAttachmentContent(createBlob);
            licenseDao.update(merged);
        }
    } catch (HibernateException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.hp.octane.integrations.services.coverage.SonarServiceImpl.java

private String getWebhookKey(String ciNotificationUrl, String sonarURL, String token)
        throws SonarIntegrationException {
    try {//from   www .  jav  a  2 s  .  c  o m
        URIBuilder uriBuilder = new URIBuilder(sonarURL + WEBHOOK_LIST_URI);
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(uriBuilder.build());
        setTokenInHttpRequest(request, token);

        HttpResponse response = httpClient.execute(request);
        InputStream content = response.getEntity().getContent();
        // if webhooks exist
        if (content.available() != 0) {
            JsonNode jsonResponse = CIPluginSDKUtils.getObjectMapper().readTree(content);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                ArrayNode webhooksListJson = (ArrayNode) jsonResponse.get("webhooks");
                if (webhooksListJson.size() > 0) {
                    for (JsonNode webhookNode : webhooksListJson) {
                        String entryURL = webhookNode.get("url").textValue();
                        if (entryURL.equals(ciNotificationUrl)) {
                            return webhookNode.get("key").textValue();
                        }
                    }
                }
                return null;
            } else {
                String errorMessage = ""
                        .concat("failed to get webhook key from soanrqube with notification URL: ")
                        .concat(ciNotificationUrl).concat(" with status code: ")
                        .concat(String.valueOf(response.getStatusLine().getStatusCode()))
                        .concat(" with errors: ").concat(jsonResponse.get("errors").toString());
                throw new SonarIntegrationException(errorMessage);

            }
        }
        return null;
    } catch (SonarIntegrationException e) {
        logger.error(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        String errorMessage = "".concat("failed to get webhook key from soanrqube with notification URL: ")
                .concat(ciNotificationUrl);
        logger.error(errorMessage, e);
        throw new SonarIntegrationException(errorMessage, e);
    }
}

From source file:com.erudika.para.rest.Signer.java

private Request<?> buildAWSRequest(HttpServletRequest req, Set<String> headersUsed) {
    Map<String, String> headers = new HashMap<String, String>();
    for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements();) {
        String head = e.nextElement().toLowerCase();
        if (headersUsed.contains(head)) {
            headers.put(head, req.getHeader(head));
        }/*from   w  w  w.  ja v a 2  s .  c  o m*/
    }

    Map<String, String> params = new HashMap<String, String>();
    for (Map.Entry<String, String[]> param : req.getParameterMap().entrySet()) {
        params.put(param.getKey(), param.getValue()[0]);
    }

    String path = req.getRequestURI();
    String endpoint = StringUtils.removeEndIgnoreCase(req.getRequestURL().toString(), path);
    String httpMethod = req.getMethod();
    InputStream entity;
    try {
        entity = new BufferedInputStream(req.getInputStream());
        if (entity.available() <= 0) {
            entity = null;
        }
    } catch (IOException ex) {
        logger.error(null, ex);
        entity = null;
    }

    return buildAWSRequest(httpMethod, endpoint, path, headers, params, entity);
}

From source file:com.clican.pluto.dataprocess.BaseDataProcessTestCase.java

protected void onSetUp() throws Exception {
    super.onSetUp();
    Connection conn = null;//from   w  w  w.j a  v  a  2 s  .c o m
    Statement stat = null;
    InputStream is = null;
    try {
        Class.forName("org.hsqldb.jdbcDriver");
        conn = DriverManager.getConnection("jdbc:hsqldb:.", "sa", "");
        stat = conn.createStatement();

        is = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("ibatis/createtable-dataprocess-test.sql");
        byte[] script = new byte[is.available()];
        is.read(script);

        String sql = new String(script);
        stat.execute(sql);

        databaseTester = new JdbcDatabaseTester("org.hsqldb.jdbcDriver", "jdbc:hsqldb:.", "sa", "");

        // initialize your dataset here
        IDataSet dataSet = getDataSet();
        if (dataSet != null) {
            databaseTester.setDataSet(dataSet);
        }
        // will call default setUpOperation
        databaseTester.onSetup();
    } catch (Exception e) {
        log.error("", e);
        throw e;
    } finally {
        if (stat != null) {
            stat.close();
        }
        if (conn != null) {
            conn.close();
        }
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.datatorrent.stram.StramMiniClusterTest.java

private static String getTestRuntimeClasspath() {

    InputStream classpathFileStream = null;
    BufferedReader reader = null;
    String envClassPath = "";

    LOG.info("Trying to generate classpath for app master from current thread's classpath");
    try {//from w w w. j a  v  a  2  s .c  o m

        // Create classpath from generated classpath
        // Check maven pom.xml for generated classpath info
        // Works in tests where compile time env is same as runtime.
        ClassLoader thisClassLoader = Thread.currentThread().getContextClassLoader();
        String generatedClasspathFile = "mvn-generated-classpath";
        classpathFileStream = thisClassLoader.getResourceAsStream(generatedClasspathFile);
        if (classpathFileStream == null) {
            LOG.info("Could not load classpath resource " + generatedClasspathFile);
            return envClassPath;
        }
        LOG.info("Readable bytes from stream=" + classpathFileStream.available());
        reader = new BufferedReader(new InputStreamReader(classpathFileStream));
        String cp = reader.readLine();
        if (cp != null) {
            envClassPath += cp.trim() + ":";
        }
        // Put the file itself on classpath for tasks.
        envClassPath += thisClassLoader.getResource(generatedClasspathFile).getFile();
    } catch (IOException e) {
        LOG.info("Could not find the necessary resource to generate class path for tests. Error="
                + e.getMessage());
    }

    try {
        if (classpathFileStream != null) {
            classpathFileStream.close();
        }
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
        LOG.info("Failed to close class path file stream or reader. Error=" + e.getMessage());
    }
    return envClassPath;
}