javatips.net counter

Java Examples for java.io.InputStream

The following java examples will help you to understand the usage of java.io.InputStream. These source code samples are taken from different open source projects.

Example 1
Project: jdroid-master  File: ZipFileParser.java View source code
/**
	 * @see com.jdroid.java.http.parser.Parser#parse(java.io.InputStream)
	 */
@SuppressWarnings("resource")
@Override
public Object parse(InputStream inputStream) {
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    try {
        ZipEntry entry;
        while ((entry = zipInputStream.getNextEntry()) != null) {
            if (entry.getName().equals(fileName)) {
                LOGGER.debug("Starting to parse " + fileName + " file.");
                return innerParser.parse(zipInputStream);
            }
        }
    } catch (IOException e) {
        throw new UnexpectedException(e);
    }
    return null;
}
Example 2
Project: extFM-Tooling-master  File: MtextStreamUtil.java View source code
public static String getContent(java.io.InputStream inputStream) throws java.io.IOException {
    StringBuffer content = new StringBuffer();
    java.io.InputStreamReader reader = new java.io.InputStreamReader(inputStream);
    int next = -1;
    while ((next = reader.read()) >= 0) {
        content.append((char) next);
    }
    return content.toString();
}
Example 3
Project: openjdk-master  File: FastInfosetReflection.java View source code
public static void DOMDocumentParser_parse(Object parser, Document d, InputStream s) throws Exception {
    if (fiDOMDocumentParser_parse == null) {
        throw new RuntimeException("Unable to locate Fast Infoset implementation");
    }
    fiDOMDocumentParser_parse.invoke(parser, new Object[] { d, s });
}
Example 4
Project: ARKOST-master  File: Utils.java View source code
public static void CopyStream(InputStream is, OutputStream os) {
    final int buffer_size = 1024;
    try {
        byte[] bytes = new byte[buffer_size];
        for (; ; ) {
            int count = is.read(bytes, 0, buffer_size);
            if (count == -1)
                break;
            os.write(bytes, 0, count);
        }
    } catch (Exception ex) {
    }
}
Example 5
Project: CareAndroid-master  File: StreamTool.java View source code
public static String inputStreamToString(InputStream in) throws Exception {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] data = new byte[BUFFER_SIZE];
    int count = -1;
    while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) outStream.write(data, 0, count);
    data = null;
    return new String(outStream.toByteArray(), "ISO-8859-1");
}
Example 6
Project: android-ssl-master  File: IOUtil.java View source code
public static String readFully(InputStream inputStream) throws IOException {
    if (inputStream == null) {
        return "";
    }
    BufferedInputStream bufferedInputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    try {
        bufferedInputStream = new BufferedInputStream(inputStream);
        byteArrayOutputStream = new ByteArrayOutputStream();
        final byte[] buffer = new byte[1024];
        int available = 0;
        while ((available = bufferedInputStream.read(buffer)) >= 0) {
            byteArrayOutputStream.write(buffer, 0, available);
        }
        return byteArrayOutputStream.toString();
    } finally {
        if (bufferedInputStream != null) {
            bufferedInputStream.close();
        }
    }
}
Example 7
Project: korsakow-editor-master  File: PipedExternalEncoder.java View source code
public void encode(Process process, InputStream sourceStream, OutputStream destStream) throws EncoderException {
    AsyncStreamPipe<InputStream, OutputStream> inPiper = new AsyncStreamPipe<InputStream, OutputStream>(sourceStream, process.getOutputStream(), "PipedExternalEncoder.inpipe");
    AsyncStreamPipe<InputStream, OutputStream> outPiper = new AsyncStreamPipe<InputStream, OutputStream>(process.getInputStream(), destStream, "PipedExternalEncoder.outpipe");
    AsyncStreamPipe<InputStream, ByteArrayOutputStream> errPiper = new AsyncStreamPipe<InputStream, ByteArrayOutputStream>(process.getErrorStream(), new ByteArrayOutputStream(), "PipedExternalEncoder.errpipe");
    inPiper.start();
    outPiper.start();
    errPiper.start();
    // we avoid thread issues by basically not doing anything until all pipers have joined.
    try {
        if (0 != process.waitFor()) {
            errPiper.join();
            throw new EncoderException("unknown error: " + errPiper.getOutputStream().toString(), errPiper.getOutputStream().toString(), null);
        }
        inPiper.join();
        outPiper.join();
        errPiper.join();
        process.destroy();
    } catch (InterruptedException e) {
        throw new EncoderException(e);
    }
    if (null != inPiper.getException())
        throw new EncoderException(inPiper.getException());
    if (null != outPiper.getException())
        throw new EncoderException(outPiper.getException());
}
Example 8
Project: Desktop-master  File: DocearServiceResponse.java View source code
private byte[] fill(InputStream contentStream) {
    int max = 8192;
    byte[] buf = new byte[max];
    int b = -1;
    int pos = 0;
    try {
        while ((b = contentStream.read()) > -1) {
            buf[pos++] = (byte) b;
            if (pos >= max) {
                max = pos * 2;
                byte nbuf[] = new byte[max];
                System.arraycopy(buf, 0, nbuf, 0, pos);
                buf = nbuf;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    length = pos;
    return buf;
}
Example 9
Project: ocr-tools-master  File: ResultXmlMergerTest.java View source code
@Test
public void shouldMergeTwoWellFormed() throws XpathException, SAXException, IOException {
    InputStream stream1 = new ByteArrayInputStream(input1.getBytes());
    InputStream stream2 = new ByteArrayInputStream(input2.getBytes());
    List<InputStream> inputs = Arrays.asList(stream1, stream2);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    Merger mergerSut = new ResultXmlMerger();
    mergerSut.mergeBuffered(inputs, output);
    String result = output.toString();
    System.out.println(result);
    assertXpathEvaluatesTo("2", "count(//Statistics)", result);
    assertXpathEvaluatesTo("1500", "sum([email protected])", result);
    assertXpathEvaluatesTo("150", "sum([email protected])", result);
}
Example 10
Project: aws-sdk-android-master  File: DigestValidationInputStream.java View source code
private void validateMD5Digest() {
    /*
         * Some InputStream readers (e.g., java.util.Properties) read more than
         * once at the end of the stream. This class validates the digest once
         * -1 has been read so we must not validate twice.
         */
    if (expectedHash != null && !digestValidated) {
        digestValidated = true;
        if (!Arrays.equals(digest.digest(), expectedHash)) {
            throw new AmazonClientException("Unable to verify integrity of data download.  " + "Client calculated content hash didn't match hash calculated by Amazon S3.  " + "The data may be corrupt.");
        }
    }
}
Example 11
Project: oobd-master  File: BcPKCS12PBEInputDecryptorProviderBuilder.java View source code
public InputDecryptor get(final AlgorithmIdentifier algorithmIdentifier) {
    final PaddedBufferedBlockCipher engine = PKCS12PBEUtils.getEngine(algorithmIdentifier.getAlgorithm());
    PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algorithmIdentifier.getParameters());
    CipherParameters params = PKCS12PBEUtils.createCipherParameters(algorithmIdentifier.getAlgorithm(), digest, engine.getBlockSize(), pbeParams, password);
    engine.init(false, params);
    return new InputDecryptor() {

        public AlgorithmIdentifier getAlgorithmIdentifier() {
            return algorithmIdentifier;
        }

        public InputStream getInputStream(InputStream input) {
            return new CipherInputStream(input, engine);
        }

        public GenericKey getKey() {
            return new GenericKey(PKCS12ParametersGenerator.PKCS12PasswordToBytes(password));
        }
    };
}
Example 12
Project: android-platform-tools-base-master  File: Main.java View source code
public static String getContent() {
    InputStream input = Main.class.getResourceAsStream("/first_pick.txt");
    if (input == null) {
        return "FAILED TO FIND first_pick.txt";
    }
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        return reader.readLine();
    } catch (IOException e) {
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }
    return "FAILED TO READ CONTENT";
}
Example 13
Project: Yarrn-master  File: SslCertificateHelper.java View source code
public static void trustGeotrustCertificate(final Context context) {
    try {
        final KeyStore trustStore = KeyStore.getInstance("BKS");
        final InputStream in = context.getResources().openRawResource(R.raw.geotrust_cert);
        trustStore.load(in, null);
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        final SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(null, tmf.getTrustManagers(), new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
    } catch (final Exception e) {
        AQUtility.report(e);
        e.printStackTrace();
    }
}
Example 14
Project: TestingStuff-master  File: ImageUtils.java View source code
public static void copyStream(InputStream is, OutputStream os) {
    final int buffer_size = 1024;
    try {
        byte[] bytes = new byte[buffer_size];
        for (; ; ) {
            int count = is.read(bytes, 0, buffer_size);
            if (count == -1)
                break;
            os.write(bytes, 0, count);
        }
    } catch (Exception ex) {
    }
}
Example 15
Project: SideScrollerGDW2012-Max-master  File: CompositeImageData.java View source code
/**
	 * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream, boolean, boolean, int[])
	 */
public ByteBuffer loadImage(InputStream is, boolean flipped, boolean forceAlpha, int[] transparent) throws IOException {
    CompositeIOException exception = new CompositeIOException();
    ByteBuffer buffer = null;
    BufferedInputStream in = new BufferedInputStream(is, is.available());
    in.mark(is.available());
    // cycle through our source until one of them works
    for (int i = 0; i < sources.size(); i++) {
        in.reset();
        try {
            LoadableImageData data = (LoadableImageData) sources.get(i);
            buffer = data.loadImage(in, flipped, forceAlpha, transparent);
            picked = data;
            break;
        } catch (Exception e) {
            Log.warn(sources.get(i).getClass() + " failed to read the data", e);
            exception.addException(e);
        }
    }
    if (picked == null) {
        throw exception;
    }
    return buffer;
}
Example 16
Project: polly-master  File: UTF8Control.java View source code
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
    // The below is a copy of the default implementation.
    final String bundleName = toBundleName(baseName, locale);
    //$NON-NLS-1$
    final String resourceName = toResourceName(bundleName, "properties");
    ResourceBundle bundle = null;
    InputStream stream = null;
    if (reload) {
        URL url = loader.getResource(resourceName);
        if (url != null) {
            URLConnection connection = url.openConnection();
            if (connection != null) {
                connection.setUseCaches(false);
                stream = connection.getInputStream();
            }
        }
    } else {
        stream = loader.getResourceAsStream(resourceName);
    }
    if (stream != null) {
        try {
            // Only this line is changed to make it to read properties files as UTF-8.
            bundle = new PropertyResourceBundle(//$NON-NLS-1$
            new InputStreamReader(stream, "UTF-8"));
        } finally {
            stream.close();
        }
    }
    return bundle;
}
Example 17
Project: TFC2-master  File: JSONReader.java View source code
public boolean read(File file) {
    try {
        Gson gson = new Gson();
        InputStream stream;
        if (file == null)
            stream = this.getClass().getResourceAsStream(path);
        else if (file.exists()) {
            stream = Files.asByteSource(file).openStream();
        } else {
            return false;
        }
        InputStreamReader sr = new InputStreamReader(stream);
        JsonReader reader = new JsonReader(sr);
        process(reader);
        reader.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return true;
}
Example 18
Project: tapestry-facebook-master  File: Channel.java View source code
Object onActivate() {
    return new StreamResponse() {

        public String getContentType() {
            return "text/html";
        }

        public InputStream getStream() throws IOException {
            return new ByteArrayInputStream(response.getBytes());
        }

        public void prepareResponse(Response response) {
            Date date = new Date();
            response.setDateHeader("Expires", date.getTime() + (maxAge * 1000));
            response.setHeader("Cache-Control", "max-age=" + maxAge);
            response.setHeader("Pragma", "public");
        }
    };
}
Example 19
Project: solmix-master  File: Version.java View source code
/**
     * @param groupId
     * @param artifactId
     * @return return special version
     */
public static String readFromMaven(String groupId, String artifactId) {
    String propPath = "/META-INF/maven/" + groupId + "/" + artifactId + "/pom.properties";
    InputStream is = Version.class.getResourceAsStream(propPath);
    if (is != null) {
        Properties properties = new Properties();
        try {
            properties.load(is);
            String version = properties.getProperty("version");
            if (version != null) {
                return version;
            }
        } catch (IOException e) {
        } finally {
            IOUtils.closeQuitely(is);
        }
    }
    return "undetermined (please report this as bug)";
}
Example 20
Project: download-manager-master  File: RegularDataTransferer.java View source code
@Override
public DownloadTask.State transferData(DownloadTask.State state, InputStream in) throws StopRequestException {
    DownloadTask.State newState = state;
    try {
        byte[] buffer = new byte[Constants.BUFFER_SIZE];
        int readLast = in.read(buffer);
        while (readLast != Constants.NO_BYTES_READ) {
            newState = dataWriter.write(newState, buffer, readLast);
            readLast = in.read(buffer);
        }
        return newState;
    } catch (IOException e) {
        return newState;
    }
}
Example 21
Project: cms-ce-master  File: MsWordDocxTextExtractor.java View source code
@Override
public Reader extractText(final InputStream stream, final String type, final String encoding) throws IOException {
    try {
        final OPCPackage opcPackage = OPCPackage.open(stream);
        final XWPFWordExtractor xw = new XWPFWordExtractor(opcPackage);
        return new StringReader(xw.getText());
    } catch (Exception e) {
        logger.warn("Failed to extract Word text content", e);
        return new StringReader("");
    }
}
Example 22
Project: FireflowEngine20-master  File: PostSender.java View source code
@Override
public Response send() throws HttpException {
    try {
        openConnection();
        InputStream ins = request.getInputStream();
        setupRequestHeader();
        if (ins != null && request.getHeader() != null && ins instanceof ByteArrayInputStream && this.request.getHeader().get("Content-Length") == null)
            conn.addRequestProperty("Content-Length", "" + ins.available());
        setupDoInputOutputFlag();
        if (null != ins) {
            OutputStream ops = Streams.buff(conn.getOutputStream());
            Streams.write(ops, ins, 8192);
            Streams.safeClose(ins);
            Streams.safeFlush(ops);
            Streams.safeClose(ops);
        }
        return createResponse(getResponseHeader());
    } catch (Exception e) {
        throw new HttpException(request.getUrl().toString(), e);
    }
}
Example 23
Project: wpcleaner-master  File: CheckResponseManager.java View source code
/**
   * @param stream
   * @throws IOException
   * @throws APIException
   * @see org.wikipediacleaner.api.ResponseManager#manageResponse(java.io.InputStream)
   */
@Override
public void manageResponse(InputStream stream) throws IOException, APIException {
    if (stream != null) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                CheckWikiDetection detection = CheckWikiDetection.analyzeLine(line);
                if (detection != null) {
                    detections.add(detection);
                }
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
        }
    }
}
Example 24
Project: wso2-synapse-master  File: XMLConfigurationBuilder.java View source code
public static SynapseConfiguration getConfiguration(InputStream is, Properties properties) throws XMLStreamException {
    log.info("Generating the Synapse configuration model by parsing the XML configuration");
    OMElement definitions = new StAXOMBuilder(is).getDocumentElement();
    definitions.build();
    return ConfigurationFactoryAndSerializerFinder.getInstance().getConfiguration(definitions, properties);
}
Example 25
Project: jade_agents-master  File: HTTPHelper.java View source code
public static JICPPacket readPacketFromHttp(InputStream is) throws IOException {
    HTTPRequest request = new HTTPRequest();
    request.readFrom(is);
    if (request.getMethod().equals("GET")) {
        // This is a CONNECT_MEDIATOR
        String recipientID = request.getField(RECIPIENT_ID_FIELD);
        JICPPacket pkt = new JICPPacket(JICPProtocol.CONNECT_MEDIATOR_TYPE, JICPProtocol.DEFAULT_INFO, recipientID, null);
        return pkt;
    } else {
        // Read the JICPPacket from the HTTP request payload
        ByteArrayInputStream bis = new ByteArrayInputStream(request.getPayload());
        return JICPPacket.readFrom(bis);
    }
}
Example 26
Project: picard-tools-master  File: SamStreams.java View source code
private static int readBytes(final InputStream stream, final byte[] buffer, final int offset, final int length) throws IOException {
    int bytesRead = 0;
    while (bytesRead < length) {
        final int count = stream.read(buffer, offset + bytesRead, length - bytesRead);
        if (count <= 0) {
            break;
        }
        bytesRead += count;
    }
    return bytesRead;
}
Example 27
Project: xmind-master  File: MarkerResourceProvider.java View source code
/*
     * (non-Javadoc)
     * 
     * @see
     * org.xmind.core.marker.IMarkerResourceAllocator#allocateMarkerResourcePath
     * (java.io.InputStream, java.lang.String)
     */
public String allocateMarkerResource(InputStream input, String suggestedPath) throws IOException {
    if (target == null)
        return null;
    String ext = //$NON-NLS-1$
    suggestedPath == null ? //$NON-NLS-1$
    ".png" : FileUtils.getExtension(suggestedPath);
    String path = Core.getIdFactory().createId() + ext;
    if (!target.isEntryAvaialble(path))
        return null;
    OutputStream output = target.openEntryStream(path);
    try {
        FileUtils.transfer(input, output, false);
    } finally {
        output.close();
    }
    return path;
}
Example 28
Project: ARTPart-master  File: SequenceInputStreamTest.java View source code
/**
     * java.io.SequenceInputStream#SequenceInputStream(java.util.Enumeration)
     */
@SuppressWarnings("unchecked")
public void test_ConstructorLjava_util_Enumeration() {
    // Test for method java.io.SequenceInputStream(java.util.Enumeration)
    class StreamEnumerator implements Enumeration {

        InputStream streams[] = new InputStream[2];

        int count = 0;

        public StreamEnumerator() throws UnsupportedEncodingException {
            streams[0] = new ByteArrayInputStream(s1.getBytes("UTF-8"));
            streams[1] = new ByteArrayInputStream(s2.getBytes("UTF-8"));
        }

        public boolean hasMoreElements() {
            return count < streams.length;
        }

        public Object nextElement() {
            return streams[count++];
        }
    }
    try {
        si = new SequenceInputStream(new StreamEnumerator());
        byte buf[] = new byte[s1.length() + s2.length()];
        si.read(buf, 0, s1.length());
        si.read(buf, s1.length(), s2.length());
        assertTrue("Read incorrect bytes: " + new String(buf), new String(buf, "UTF-8").equals(s1 + s2));
    } catch (IOException e) {
        fail("IOException during read test : " + e.getMessage());
    }
}
Example 29
Project: open-mika-master  File: ContentTypeParser.java View source code
public void ReInit(java.io.InputStream stream, String encoding) {
    try {
        jj_input_stream.ReInit(stream, encoding, 1, 1);
    } catch (java.io.UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    token_source.ReInit(jj_input_stream);
    token = new Token();
    jj_ntk = -1;
    jj_gen = 0;
    for (int i = 0; i < 3; i++) jj_la1[i] = -1;
}
Example 30
Project: turmeric-eclipse-master  File: TestWebXMLParser.java View source code
/**
	 * Test method for and
	 * [email protected] [email protected]#addServletElements(org.jdom.Document, java.io.InputStream)}
	 * 
	 * @throws Exception
	 */
@Test
public void testGetSourceDocument() throws Exception {
    InputStream webxmlStreamSource = TestWebXMLParser.class.getResourceAsStream("web_source.xml");
    InputStream webxmlStreamTarget = TestWebXMLParser.class.getResourceAsStream("web_target.xml");
    Document sourceDoc = JDOMUtil.readXML(webxmlStreamSource);
    Document targetDoc = WebXMLParser.addServletElements(sourceDoc, webxmlStreamTarget);
    Element targetRoot = targetDoc.getRootElement();
    // Load web_target_compare.xml for compare
    InputStream webxmlStreamTargetCompare = TestWebXMLParser.class.getResourceAsStream("web_target_compare.xml");
    Document targetDocCompare = JDOMUtil.readXML(webxmlStreamTargetCompare);
    Element compareRoot = targetDocCompare.getRootElement();
    Assert.assertTrue(compareJDOMElement(targetRoot, compareRoot));
}
Example 31
Project: molgenis-master  File: FileStore.java View source code
public File store(InputStream is, String fileName) throws IOException {
    File file = new File(storageDir + separator + fileName);
    FileOutputStream fos = new FileOutputStream(file);
    try {
        IOUtils.copy(is, fos);
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(is);
    }
    return file;
}
Example 32
Project: breakout-master  File: LineUtils.java View source code
public static List<String> readLines(InputStream in) throws IOException {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        List<String> lines = new ArrayList<String>();
        String line;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
        return lines;
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}
Example 33
Project: SmartAndroidSource-master  File: FileZipEntryTransformer.java View source code
public void transform(InputStream in, ZipEntry zipEntry, ZipOutputStream out) throws IOException {
    File inFile = null;
    File outFile = null;
    try {
        inFile = File.createTempFile("zip", null);
        outFile = File.createTempFile("zip", null);
        copy(in, inFile);
        transform(zipEntry, inFile, outFile);
        FileSource source = new FileSource(zipEntry.getName(), outFile);
        ZipEntrySourceZipEntryTransformer.addEntry(source, out);
    } finally {
        FileUtils.deleteQuietly(inFile);
        FileUtils.deleteQuietly(outFile);
    }
}
Example 34
Project: btpka3.github.com-master  File: AntiSamyTest.java View source code
public static void main(String[] args) throws PolicyException, IOException, ScanException {
    final File inputDir = new File("dirtyInput");
    final File outputDir = new File("cleanResult");
    InputStream prolicyIn = AntiSamyTest.class.getResourceAsStream("antisamy-ebay-1.4.4.xml");
    Policy policy = Policy.getInstance(prolicyIn);
    AntiSamy as = new AntiSamy();
    String[] dirtyFiles = inputDir.list(FileFilterUtils.and(FileFilterUtils.suffixFileFilter(".html"), FileFilterUtils.notFileFilter(FileFilterUtils.directoryFileFilter())));
    for (String dirtyFile : dirtyFiles) {
        File inFile = new File(inputDir, dirtyFile);
        File outFile = new File(outputDir, dirtyFile.substring(0, dirtyFile.length() - 5) + ".clean.html");
        System.out.println("Processing file :" + inFile.getAbsolutePath());
        String dirtyInput = IOUtils.toString(new FileInputStream(inFile));
        CleanResults cr = as.scan(dirtyInput, policy, AntiSamy.SAX);
        String cleanResult = cr.getCleanHTML();
        IOUtils.write(cleanResult, new FileOutputStream(outFile));
    }
}
Example 35
Project: Android_Blog_Demos-master  File: LargeImageViewSimpleBak.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_large_image_view);
    mImageView = (ImageView) findViewById(R.id.id_imageview);
    try {
        InputStream inputStream = getAssets().open("tangyan.jpg");
        //获得图片的宽、高
        BitmapFactory.Options tmpOptions = new BitmapFactory.Options();
        tmpOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(inputStream, null, tmpOptions);
        int width = tmpOptions.outWidth;
        int height = tmpOptions.outHeight;
        //设置显示图片的中心区域
        BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = bitmapRegionDecoder.decodeRegion(new Rect(width / 2 - 100, height / 2 - 100, width / 2 + 100, height / 2 + 100), options);
        mImageView.setImageBitmap(bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 36
Project: RoboBuggy-master  File: TextRunnerTest.java View source code
void execTest(String testClass, boolean success) throws Exception {
    String java = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
    String cp = System.getProperty("java.class.path");
    //use -classpath for JDK 1.1.7 compatibility
    String[] cmd = { java, "-classpath", cp, "junit.textui.TestRunner", testClass };
    Process p = Runtime.getRuntime().exec(cmd);
    InputStream i = p.getInputStream();
    while ((i.read()) != -1) //System.out.write(b);
    ;
    assertTrue((p.waitFor() == 0) == success);
    if (success) {
        assertTrue(p.exitValue() == 0);
    } else {
        assertFalse(p.exitValue() == 0);
    }
}
Example 37
Project: vr-toolkit-master  File: DownloadFiles.java View source code
@Override
protected String doInBackground(String... sUrl) {
    try {
        URL url = new URL(sUrl[0]);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();
        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(mPath);
        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            publishProgress((int) (total * 100 / fileLength));
            output.write(data, 0, count);
        }
        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {
    }
    return null;
}
Example 38
Project: SpaceDefence-master  File: InThread.java View source code
@Override
public void run() {
    try {
        InputStream input = connection.getInputStream();
        while (!connection.isClosed()) {
            byte[] intBytes = new byte[4];
            for (int i = 0; i < 4; i++) {
                intBytes[i] = (byte) input.read();
            }
            int msgLen = ByteBuffer.wrap(intBytes).getInt();
            byte[] msg = new byte[msgLen];
            int read = 0, offset = 0, toRead = msgLen;
            while (toRead > 0 && (read = input.read(msg, offset, toRead)) > 0) {
                toRead -= read;
                offset += read;
            }
            if (read >= 0) {
                monitor.putArrayFromServer(msg);
            } else {
                break;
            // TODO: fix when server dies
            }
        }
    } catch (NegativeArraySizeException nsae) {
        Logger.log("NegativeArraySizeException when declaring msg.");
    } catch (SocketException se) {
        Logger.log("(inthread) insocket already closed");
    } catch (IOException e1) {
        Logger.log("Exception: ");
        e1.printStackTrace();
    } finally {
        monitor.closeConnection();
    }
}
Example 39
Project: hdt-java-master  File: TarTest.java View source code
public static void main(String[] args) throws Throwable {
    InputStream input = new ExternalDecompressStream(new File("/Users/mck/rdf/dataset/tgztest.tar.gz"), ExternalDecompressStream.GZIP);
    //		InputStream input = new CountInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream("/Users/mck/rdf/dataset/tgztest.tar.gz"))));
    //		InputStream input = new CountInputStream(new BufferedInputStream(new FileInputStream("/Users/mck/rdf/dataset/tgztest.tar")));
    final TarArchiveInputStream debInputStream = new TarArchiveInputStream(input);
    TarArchiveEntry entry = null;
    NonCloseInputStream nonCloseIn = new NonCloseInputStream(debInputStream);
    while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
        System.out.println(entry.getName());
    }
    debInputStream.close();
}
Example 40
Project: trie4j-master  File: GenHtml.java View source code
public static void main(String[] args) throws Exception {
    String templ = null;
    InputStream temps = GenHtml.class.getResourceAsStream("template.txt");
    try {
        templ = StreamUtil.readAsString(temps, "UTF-8");
    } finally {
        temps.close();
    }
    InputStream res = GenHtml.class.getResourceAsStream("result.txt");
    try {
        BufferedReader r = new BufferedReader(new InputStreamReader(res, "UTF-8"));
        String line = null;
        while ((line = r.readLine()) != null) {
            String[] vals = line.split("[ ]+");
            String name = vals[0].substring(0, vals[0].length() - 1).replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)").trim();
            templ = templ.replaceAll("\\$\\{" + name + "\\.build\\}", String.format("%,d", Integer.valueOf(vals[1].replace(',', ' ').trim()))).replaceAll("\\$\\{" + name + "\\.contains\\}", String.format("%,d", Integer.valueOf(vals[2].replace(',', ' ').trim()))).replaceAll("\\$\\{" + name + "\\.mem\\}", String.format("%.1f", Integer.valueOf(vals[3].replace(',', ' ').trim()) / 1000000.0));
        }
        System.out.println(templ);
    } finally {
        res.close();
    }
}
Example 41
Project: vlc-android-macbuild-master  File: StreamHelper.java View source code
public static String readStreamLineByLine(InputStream inputStream) {
    InputStreamReader reader = new InputStreamReader(inputStream);
    BufferedReader buffReader = new BufferedReader(reader);
    StringBuilder text = new StringBuilder();
    String resultText = null;
    try {
        String line;
        while ((line = buffReader.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
        resultText = text.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            buffReader.close();
            reader.close();
        } catch (Exception e) {
        }
    }
    return resultText;
}
Example 42
Project: property-db-master  File: Socket_SetTimeoutBeforeBlockingInput_1.java View source code
public static void main(String[] args) throws IOException {
    // This program assumes the following socket cannot read input
    // immediately. If this assumption does not hold, this test is
    // meaningless.
    final Socket sock = new Socket("www.illinois.edu", 80);
    // The following method call is fine; after 2 seconds, read() will raise
    // the SocketTimeoutException exception.
    sock.setSoTimeout(2000);
    try {
        InputStream in = sock.getInputStream();
        in.read();
    } catch (SocketTimeoutException expected) {
    }
    // In the following routine, timeout was set while read() is blocking.
    // The property handler should be triggered.
    Thread thread = new Thread() {

        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ignored) {
            }
            try {
                sock.setSoTimeout(1000);
            } catch (SocketException ignored) {
            }
        }
    };
    thread.start();
    InputStream in = sock.getInputStream();
    in.read();
}
Example 43
Project: extension-aws-master  File: Mp4Generator.java View source code
protected InputStream streamBinary(WebPageRequest inReq, Page inPage, InputStream in, long start, long end, long length, Output inOut) throws IOException {
    if (start == -1) {
        //Only used for flash flv files never used for mp4
        String startbytes = inReq.getRequestParameter("start");
        if (startbytes != null) {
            double timeoffset = Double.parseDouble(startbytes);
            OutputStream stream = inOut.getStream();
            getVideoEditor().split(inPage, timeoffset, stream);
            stream.flush();
            return in;
        }
    }
    return super.streamBinary(inReq, inPage, in, start, end, length, inOut);
}
Example 44
Project: tapestry-model-master  File: Blob.java View source code
protected StreamResponse onActivate(Class clazz, String id, String property) throws Exception {
    final Object bean = contextValueEncoder.toValue(clazz, id);
    final TynamoPropertyDescriptor propertyDescriptor = descriptorService.getClassDescriptor(clazz).getPropertyDescriptor(property);
    return new StreamResponse() {

        public String getContentType() {
            return filePersister.getContentType(propertyDescriptor, bean);
        }

        public InputStream getStream() throws IOException {
            return new ByteArrayInputStream(filePersister.getData(propertyDescriptor, bean));
        }

        public void prepareResponse(Response response) {
            String contentDisposition = propertyDescriptor.getExtension(BlobDescriptorExtension.class).getContentDisposition().getValue();
            String fileName = filePersister.getFileName(propertyDescriptor, bean);
            response.setHeader("Content-Disposition", contentDisposition + (fileName != null ? "; filename=" + fileName : ""));
        }
    };
}
Example 45
Project: tmdm-studio-se-master  File: DataModelValidator.java View source code
/*
     * (non-Javadoc)
     * 
     * @see org.eclipse.wst.xml.core.internal.validation.core.AbstractNestedValidator#validate(java.lang.String,
     * java.io.InputStream, org.eclipse.wst.xml.core.internal.validation.core.NestedValidatorContext)
     */
@Override
public ValidationReport validate(String uri, InputStream inputstream, NestedValidatorContext context) {
    //
    DataModelValidationReport report = new DataModelValidationReport(uri);
    List<ModelValidationMessage> messages = modelChecker.toCheck(getFileFromURI(uri));
    report.addMessages(messages);
    return report;
}
Example 46
Project: cdt-master  File: TestUtils.java View source code
public static File saveFile(InputStream st, File testFile) throws FileNotFoundException, IOException {
    BufferedReader r = new BufferedReader(new InputStreamReader(st));
    String line;
    try (PrintStream wr = new PrintStream(testFile)) {
        while ((line = r.readLine()) != null) {
            wr.println(line);
        }
    }
    return testFile;
}
Example 47
Project: aws-toolkit-eclipse-master  File: InstanceTypesParserTest.java View source code
/**
     * Tests the InstanceType parser by loading the fallback instance type
     * descriptions and making sure the loaded instance types look correct.
     *
     * This test requires the etc directory to be on the build-path in order for
     * the fallback file to be loaded.
     */
@Test
public void testInstanceTypesParser() throws Exception {
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream("InstanceTypes.xml");
    assertNotNull(inputStream);
    InstanceTypesParser parser = new InstanceTypesParser(inputStream);
    assertEquals("m1.small", parser.parseDefaultInstanceTypeId());
    List<InstanceType> instanceTypes = parser.parseInstanceTypes();
    assertTrue(instanceTypes.size() > 5);
    for (InstanceType type : instanceTypes) {
        assertNotNull(type.id);
        assertNotNull(type.diskSpaceWithUnits);
        assertNotNull(type.memoryWithUnits);
        assertNotNull(type.architectureBits);
        assertNotNull(type.name);
        assertTrue(type.numberOfVirtualCores > 0);
    }
}
Example 48
Project: android-bankdroid-master  File: CertificateReader.java View source code
public static Certificate[] getCertificates(Context context, int... rawResCerts) {
    List<Certificate> certificates = new ArrayList<>();
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        for (int resId : rawResCerts) {
            InputStream is = new BufferedInputStream(context.getResources().openRawResource(resId));
            try {
                X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
                certificates.add(cert);
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    Timber.w(e, "Failed to close input stream");
                }
            }
        }
    } catch (CertificateException e) {
        Timber.w(e, "Generating certificate failed");
    }
    return certificates.toArray(new Certificate[certificates.size()]);
}
Example 49
Project: Yhb-2.0-master  File: BitmapDecoderHttp.java View source code
@Override
public Bitmap decode(String fileName, Context context) {
    try {
        URL url = new URL(fileName);
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream input = connection.getInputStream();
            if (input != null) {
                try {
                    return BitmapFactory.decodeStream(input, null, OPTIONS);
                } catch (OutOfMemoryError oom) {
                } catch (Exception e) {
                }
            }
        } catch (IOException e) {
        }
    } catch (MalformedURLException e1) {
    }
    return null;
}
Example 50
Project: fdroidclient-master  File: AssetUtils.java View source code
@Nullable
public static File copyAssetToDir(Context context, String assetName, File directory) {
    File tempFile = null;
    InputStream input = null;
    OutputStream output = null;
    try {
        tempFile = File.createTempFile(assetName, ".testasset", directory);
        Log.i(TAG, "Copying asset file " + assetName + " to directory " + directory);
        input = context.getAssets().open(assetName);
        output = new FileOutputStream(tempFile);
        Utils.copy(input, output);
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        Utils.closeQuietly(output);
        Utils.closeQuietly(input);
    }
    return tempFile;
}
Example 51
Project: Tank-master  File: HTTPRequestTrial.java View source code
public static void main(String[] args) throws URISyntaxException, HttpException, IOException {
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    HttpGet httpget = new HttpGet("http://www.google.com/");
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        int l;
        byte[] tmp = new byte[2048];
        while ((l = instream.read(tmp)) != -1) {
            String s = new String(tmp);
            System.out.println(s);
        }
    }
    System.out.println("**************************");
    Header[] elements = response.getAllHeaders();
    for (Header header : elements) {
        System.out.println(header.getName() + " : " + header.getValue());
    }
    System.out.println();
    System.out.println("**************************");
    httpclient.close();
}
Example 52
Project: rayo-server-master  File: PropertiesBasedProvisioningServiceTest.java View source code
@Before
public void setup() throws Exception {
    propsFile = File.createTempFile("temp", ".properties");
    propsFile.deleteOnExit();
    tempProvisioningFile = File.createTempFile("temp", ".properties");
    tempProvisioningFile.deleteOnExit();
    InputStream sourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("test-provisioning.properties");
    Properties sourceProperties = new Properties();
    sourceProperties.load(sourceStream);
    sourceProperties.put(PropertiesBasedStorageServiceClient.ROUTING_PROPERTIES_FILE, propsFile.getAbsolutePath());
    sourceProperties.put(PropertiesBasedStorageServiceClient.PROPERTIES_RELOAD_INTERVAL, "500");
    sourceStream.close();
    FileOutputStream fos = new FileOutputStream(tempProvisioningFile);
    sourceProperties.store(fos, null);
    fos.close();
    propertiesFile = tempProvisioningFile.getAbsolutePath();
    provisioningService = new PropertiesBasedProvisioningAgent();
    super.setup();
}
Example 53
Project: framework-master  File: LinkToPercentage.java View source code
@Override
protected void setup() {
    String filename = "110% Vaadin";
    Resource resource = new StreamResource(new StreamSource() {

        @Override
        public InputStream getStream() {
            return new InputStream() {

                boolean first = true;

                @Override
                public int read() throws IOException {
                    if (first) {
                        first = false;
                        return 'a';
                    } else {
                        return -1;
                    }
                }
            };
        }
    }, filename);
    Link link = new Link("The link", resource);
    addComponent(link);
}
Example 54
Project: factura-electronica-master  File: KeyLoaderFactory.java View source code
public static final KeyLoader createInstance(KeyLoaderEnumeration keyLoaderEnumeration, InputStream keyInputStream, String... keyPassword) {
    KeyLoader keyLoader = null;
    if (keyLoaderEnumeration == KeyLoaderEnumeration.PRIVATE_KEY_LOADER) {
        keyLoader = new PrivateKeyLoader(keyInputStream, keyPassword == null ? null : keyPassword[0]);
    } else if (keyLoaderEnumeration == KeyLoaderEnumeration.PUBLIC_KEY_LOADER) {
        keyLoader = new PublicKeyLoader(keyInputStream);
    }
    return keyLoader;
}
Example 55
Project: BBAW_CMS-master  File: ToRdfTransformer.java View source code
/**
   * Do an transformation job. 
   * The kind of job (XSLT transformation or direct parsing) depends on the subclass. 
   * @param inputUrl - the url of the resource to be transformed.
   * @throws ApplicationException
   */
public void doTransformation(final String inputUrl, final String outputUrl) throws ApplicationException {
    if (inputUrl == null || inputUrl.isEmpty()) {
        throw new ApplicationException("The value for the parameter inputUrl in ToRdfTransformer.doTransformation() mustn't be null or empty!");
    }
    final InputStream inputFileStream = this.resourceReader.read(inputUrl);
    if (this.transformMode.equals(MODE_XSLT)) {
        if (this.getXslInput() == null) {
            throw new ApplicationException("You must specify an XSLT stylesheet before transforming in XSLT mode!");
        }
        final InputStream xslInput = this.resourceReader.read(this.getXslInput());
        final OutputStream xmlOutput = this.resourceWriter.write(outputUrl);
        this.transform(inputFileStream, xslInput, xmlOutput);
    } else if (this.transformMode.equals(MODE_DIRECT)) {
    // Do a direct transformation - this is specified by the subclass
    }
}
Example 56
Project: andlytics-master  File: DataLoader.java View source code
/**
	 * reads the changelog file and returns its content as a String.
	 * 
	 * @param context
	 *            the context.
	 * @param ressourceName
	 *            Name of the ressource to be loaded
	 * @return content of the ressource as a String.
	 * @throws IOException
	 *             if errors occur while reading the changelog file
	 */
public static String loadData(final Context context, final String ressourceName) throws IOException {
    int resourceIdentifier = context.getApplicationContext().getResources().getIdentifier(ressourceName, "raw", context.getApplicationContext().getPackageName());
    if (resourceIdentifier != 0) {
        InputStream inputStream = context.getApplicationContext().getResources().openRawResource(resourceIdentifier);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String line;
        StringBuffer data = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            data.append(line);
        }
        reader.close();
        return data.toString();
    }
    return null;
}
Example 57
Project: sinovoice-voicewake-master  File: AccountInfo.java View source code
/**
     * �����û���ע����Ϣ
     * @param context ������
     * @return ���سɹ�Ϊtrue��ʧ��Ϊfalse
     */
public boolean loadAccountInfo(Context context) {
    boolean isSuccess = true;
    try {
        InputStream ins = context.getResources().getAssets().open("AccountInfo.txt");
        Properties props = new Properties();
        props.load(ins);
        mAccountMap.put("appKey", props.getProperty("appKey"));
        mAccountMap.put("developerKey", props.getProperty("developerKey"));
        mAccountMap.put("cloudUrl", props.getProperty("cloudUrl"));
        mAccountMap.put("capKey", props.getProperty("capKey"));
    } catch (IOException e) {
        e.printStackTrace();
        isSuccess = false;
    }
    return isSuccess;
}
Example 58
Project: TweetLanes-master  File: ContactContentUrlDownloader.java View source code
@Override
public void download(final Context context, final String url, final String filename, final UrlDownloaderCallback callback, final Runnable completion) {
    final AsyncTask<Void, Void, Void> downloader = new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(final Void... params) {
            try {
                final ContentResolver cr = context.getContentResolver();
                InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(cr, Uri.parse(url));
                callback.onDownloadComplete(ContactContentUrlDownloader.this, is, null);
                return null;
            } catch (final Throwable e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(final Void result) {
            completion.run();
        }
    };
    UrlImageViewHelper.executeTask(downloader);
}
Example 59
Project: nmonvisualizer-master  File: VersionInfo.java View source code
private static String loadVersion() {
    InputStream in = VersionInfo.class.getResourceAsStream("/com/ibm/nmon/" + "version.properties");
    if (in != null) {
        Properties properties = new Properties();
        try {
            properties.load(in);
            return properties.getProperty("version");
        } catch (IOException ioe) {
            LOGGER.warn("Error loading " + "version.properties" + " file", ioe);
            return "UNKNOWN";
        } finally {
            try {
                in.close();
            } catch (IOException ioe) {
                LOGGER.warn("Cannot close " + "version.properties");
            }
        }
    } else {
        LOGGER.debug("could not load " + "version.properties" + "; defaulting to '" + "development" + '\'');
        return "development";
    }
}
Example 60
Project: kanqiu_letv-master  File: ImageLoadTask.java View source code
@Override
protected Drawable doInBackground(Void... params) {
    Drawable drawable = null;
    try {
        InputStream in = (InputStream) new URL(url).openConnection().getContent();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // 4K buffer
        byte[] buf = new byte[4 * 1024];
        int bytesRead;
        while ((bytesRead = in.read(buf)) != -1) {
            bos.write(buf, 0, bytesRead);
        }
        byte[] byteArray = bos.toByteArray();
        Bitmap decodeByteArray = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
        drawable = new BitmapDrawable(decodeByteArray);
        in.close();
        bos.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return drawable;
}
Example 61
Project: AndroidPlugin-master  File: MyApplication.java View source code
@Override
protected void loadPluginClients() {
    AssetManager asset = getAssets();
    try {
        for (String s : asset.list("apks")) {
            File dex = getDir("dex", Context.MODE_PRIVATE);
            dex.mkdir();
            File plugin = new File(dex, s);
            InputStream fis = getAssets().open("apks/" + s);
            FileOutputStream fos = new FileOutputStream(plugin);
            byte[] buffer = new byte[0xFF];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fis.close();
            fos.close();
            PluginClientManager.sharedInstance(this).addPluginClient(plugin.getAbsolutePath());
        }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
}
Example 62
Project: modeshape-master  File: MSOfficeMetadataReader.java View source code
public static MSOfficeMetadata instance(InputStream stream) throws Exception {
    POIFSReader r = new POIFSReader();
    MSOfficeMetadata MSOfficeMetadataListener = new MSOfficeMetadata();
    r.registerListener(MSOfficeMetadataListener, "\005SummaryInformation");
    r.read(stream);
    return MSOfficeMetadataListener;
}
Example 63
Project: cbe-master  File: FileLoader2.java View source code
public List<String> loadLines(String filename) {
    BufferedReader bufferedReader = null;
    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    List<String> lines = new ArrayList<String>();
    try {
        inputStream = getClass().getClassLoader().getResourceAsStream(filename);
        inputStreamReader = new InputStreamReader(inputStream);
        bufferedReader = new BufferedReader(inputStreamReader);
        String line = null;
        while ((line = bufferedReader.readLine()) != null) lines.add(line);
        inputStream.close();
        inputStreamReader.close();
        bufferedReader.close();
    } catch (IOException e) {
        System.err.println("Failed to read and/or close file:");
        e.printStackTrace();
    }
    return lines;
}
Example 64
Project: Technomap-master  File: FixedWidthTextTableReader.java View source code
// ------------------------------------------------------------------------
/**
     * @see prefuse.data.io.AbstractTextTableReader#read(java.io.InputStream, prefuse.data.io.TableReadListener)
     */
protected void read(InputStream is, TableReadListener trl) throws IOException, DataParseException {
    String line;
    int lineno = 0;
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    while ((line = br.readLine()) != null) {
        // increment the line number
        ++lineno;
        // split on tab character
        for (int i = 0; i < m_schema.getColumnCount(); ++i) {
            int idx0 = m_schema.getColumnStart(i);
            int idx1 = m_schema.getColumnEnd(i);
            trl.readValue(lineno, i + 1, line.substring(idx0, idx1));
        }
    }
}
Example 65
Project: android_platform_libcore-master  File: CipherInputStreamTest.java View source code
/**
     * javax.crypto.CipherInputStream#close()
     */
public void testClose() throws Exception {
    // Regression for HARMONY-1087
    try {
        new CipherInputStream(new ByteArrayInputStream(new byte[] { 1 }), Cipher.getInstance("DES/CBC/PKCS5Padding")).close();
        fail("IllegalStateException expected!");
    } catch (IllegalStateException e) {
    }
    try {
        new CipherInputStream(new BufferedInputStream((InputStream) null), Cipher.getInstance("DES/CBC/PKCS5Padding")).close();
        fail("IllegalStateException expected!");
    } catch (IllegalStateException e) {
    }
}
Example 66
Project: levelup-java-examples-master  File: InputStreamToString.java View source code
@Test
public void convert_inputstream_to_string_java() throws IOException {
    File file = new File(fileLocation);
    InputStream inputStream = new FileInputStream(file);
    StringBuilder fileContent = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, Charsets.UTF_8));
    String line = bufferedReader.readLine();
    while (line != null) {
        fileContent.append(line);
        line = bufferedReader.readLine();
    }
    bufferedReader.close();
    assertEquals("Inputstream to string", fileContent.toString());
}
Example 67
Project: apache-james-mime4j-groundhog-master  File: MessageBuilder.java View source code
/**
     * @see org.apache.james.mime4j.parser.ContentHandler#body(org.apache.james.mime4j.descriptor.BodyDescriptor, java.io.InputStream)
     */
public void body(BodyDescriptor bd, final InputStream is) throws MimeException, IOException {
    expect(Entity.class);
    final String enc = bd.getTransferEncoding();
    final Body body;
    final InputStream decodedStream;
    if (MimeUtil.ENC_BASE64.equals(enc)) {
        decodedStream = new Base64InputStream(is);
    } else if (MimeUtil.ENC_QUOTED_PRINTABLE.equals(enc)) {
        decodedStream = new QuotedPrintableInputStream(is);
    } else {
        decodedStream = is;
    }
    if (bd.getMimeType().startsWith("text/")) {
        String charset = bd.getCharset();
        if (charset == null)
            charset = defaultCharset;
        body = bodyFactory.textBody(decodedStream, charset);
    } else {
        body = bodyFactory.binaryBody(decodedStream);
    }
    Entity entity = ((Entity) stack.peek());
    entity.setBody(body);
}
Example 68
Project: javalang-master  File: JavadocLinkParser.java View source code
/** Reinitialise. */
public void ReInit(java.io.InputStream stream, String encoding) {
    try {
        jj_input_stream.ReInit(stream, encoding, 1, 1);
    } catch (java.io.UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    token_source.ReInit(jj_input_stream);
    token = new Token();
    jj_ntk = -1;
    jj_gen = 0;
    for (int i = 0; i < 5; i++) jj_la1[i] = -1;
}
Example 69
Project: kabeja-master  File: AbstractSAXParser.java View source code
/*
     * (non-Javadoc)
     * 
     * @see org.kabeja.parser.Parser#parse(java.io.InputStream,
     * java.lang.String)
     */
public void parse(InputStream input, DraftDocument doc, Map properties) throws ParseException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        factory.setNamespaceAware(true);
        SAXParser parser = factory.newSAXParser();
        // start parsing
        this.doc = doc;
        parser.parse(input, this);
    } catch (Exception e) {
        throw new ParseException(e);
    }
}
Example 70
Project: magnificent-mileage-master  File: FileBasedOpenStreetMapProviderImpl.java View source code
@Override
public void readOSM(OpenStreetMapContentHandler handler) {
    try {
        OpenStreetMapParser parser = new OpenStreetMapParser();
        if (_path.getName().endsWith(".gz")) {
            InputStream in = new GZIPInputStream(new FileInputStream(_path));
            parser.parseMap(in, handler);
        } else if (_path.getName().endsWith(".bz2")) {
            BZip2CompressorInputStream in = new BZip2CompressorInputStream(new FileInputStream(_path));
            parser.parseMap(in, handler);
        } else {
            parser.parseMap(_path, handler);
        }
    } catch (Exception ex) {
        throw new IllegalStateException("error loading OSM from path " + _path, ex);
    }
}
Example 71
Project: open-bixi-gpstracker-master  File: InputStreamEntity.java View source code
public void writeTo(final OutputStream outstream) throws IOException {
    if (outstream == null) {
        throw new IllegalArgumentException("Output stream may not be null");
    }
    InputStream instream = this.content;
    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        int l;
        if (this.length < 0) {
            // consume until EOF
            while ((l = instream.read(buffer)) != -1) {
                outstream.write(buffer, 0, l);
            }
        } else {
            // consume no more than length
            long remaining = this.length;
            while (remaining > 0) {
                l = instream.read(buffer, 0, (int) Math.min(BUFFER_SIZE, remaining));
                if (l == -1) {
                    break;
                }
                outstream.write(buffer, 0, l);
                remaining -= l;
            }
        }
    } finally {
        instream.close();
    }
}
Example 72
Project: spring-framework-2.5.x-master  File: BurlapExporter.java View source code
/**
	 * Perform an invocation on the exported object.
	 * @param inputStream the request stream
	 * @param outputStream the response stream
	 * @throws Throwable if invocation failed
	 */
public void invoke(InputStream inputStream, OutputStream outputStream) throws Throwable {
    Assert.notNull(this.skeleton, "Burlap exporter has not been initialized");
    ClassLoader originalClassLoader = overrideThreadContextClassLoader();
    try {
        this.skeleton.invoke(new BurlapInput(inputStream), new BurlapOutput(outputStream));
    } finally {
        try {
            inputStream.close();
        } catch (IOException ex) {
        }
        try {
            outputStream.close();
        } catch (IOException ex) {
        }
        resetThreadContextClassLoader(originalClassLoader);
    }
}
Example 73
Project: voms-api-java-master  File: LegacyVOMSResponseParsingStrategy.java View source code
public VOMSResponse parse(InputStream inputStream) {
    try {
        Document document = documentBuilder.parse(inputStream);
        return new LegacyVOMSResponse(document);
    } catch (Exception e) {
        throw new VOMSError(e.getMessage());
    }
}
Example 74
Project: openjdk8-jdk-master  File: SMPTESequence.java View source code
static boolean test(float divisionType) {
    boolean result = false;
    try {
        log("Testing divisionType == " + divisionType);
        Sequence sequence = new Sequence(divisionType, 16, 1);
        float div1 = sequence.getDivisionType();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        MidiSystem.write(sequence, 1, outStream);
        InputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        sequence = MidiSystem.getSequence(inStream);
        float div2 = sequence.getDivisionType();
        log("After write/read got divisionType == " + div2);
        if (Math.abs(div2 - div1) < 0.001f) {
            result = true;
        }
    } catch (InvalidMidiDataException ex) {
        log(ex);
    } catch (IOException ex) {
        log(ex);
    } catch (IllegalArgumentException ex) {
        log(ex);
    }
    if (result) {
        log("OK");
    } else {
        log("FAIL");
        failed++;
    }
    return result;
}
Example 75
Project: openmap-master  File: GLOBEData.java View source code
public void readDataFromStream(InputStream istream) throws IOException {
    int lines_read = 0;
    BufferedReader buffstream = new BufferedReader(new InputStreamReader(istream), 65536);
    while (true) {
        String line = buffstream.readLine();
        if (line == null)
            break;
        line = line.trim();
        // ignore comments
        if (line.length() == 0 || line.startsWith("#")) {
            continue;
        }
        parseDataFromStream(line);
        lines_read++;
    //          if (lines_read % 1000 == 0) {
    //              System.out.println("Read " + lines_read + " lines");
    //          }
    }
//      System.out.println("Read " + lines_read + " total lines");
}
Example 76
Project: GeoGig-master  File: AbstractGeoJsonCommand.java View source code
protected DataStore getDataStore(String geoJSON) throws FileNotFoundException, IOException {
    try {
        File geoJsonfile = new File(geoJSON);
        checkParameter(geoJsonfile.exists(), "File does not exist '%s'", geoJsonfile);
        InputStream in = new FileInputStream(geoJsonfile);
        FeatureJSON fjson = new FeatureJSON();
        @SuppressWarnings("rawtypes") FeatureCollection fc = fjson.readFeatureCollection(in);
        @SuppressWarnings("unchecked") DataStore dataStore = new MemoryDataStore(fc);
        return dataStore;
    } catch (IOException ioe) {
        throw new CommandFailedException("Error opening GeoJSON: " + ioe.getMessage(), ioe);
    }
}
Example 77
Project: yarn-comment-master  File: TestINode.java View source code
public void testSerializeFileWithSingleBlock() throws IOException {
    Block[] blocks = { new Block(849282477840258181L, 128L) };
    INode inode = new INode(FileType.FILE, blocks);
    assertEquals("Length", 1L + 4 + 16, inode.getSerializedLength());
    InputStream in = inode.serialize();
    INode deserialized = INode.deserialize(in);
    assertEquals("FileType", inode.getFileType(), deserialized.getFileType());
    Block[] deserializedBlocks = deserialized.getBlocks();
    assertEquals("Length", 1, deserializedBlocks.length);
    assertEquals("Id", blocks[0].getId(), deserializedBlocks[0].getId());
    assertEquals("Length", blocks[0].getLength(), deserializedBlocks[0].getLength());
}
Example 78
Project: SRE-RoboCode-master  File: Loader.java View source code
private static void downloadFile(String libraries, String directory, String file) throws IOException {
    URL url = new URL(libraries + file);
    final URLConnection con = url.openConnection();
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        is = con.getInputStream();
        fos = new FileOutputStream(directory + file);
        do {
            final int b = is.read();
            if (b == -1) {
                break;
            } else {
                fos.write(b);
            }
        } while (true);
    } finally {
        if (fos != null) {
            fos.close();
        }
        if (is != null) {
            is.close();
        }
    }
}
Example 79
Project: flink-master  File: TestingFailingBlobServer.java View source code
@Override
public void run() {
    // we do properly the first operation (PUT)
    try {
        new BlobServerConnection(getServerSocket().accept(), this).start();
    } catch (Throwable t) {
        t.printStackTrace();
    }
    // do some failing operations
    for (int num = 0; num < numFailures && !isShutdown(); num++) {
        Socket socket = null;
        try {
            socket = getServerSocket().accept();
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            // just abort everything
            is.close();
            os.close();
            socket.close();
        } catch (IOException e) {
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (Throwable t) {
                }
            }
        }
    }
    // regular runs
    super.run();
}
Example 80
Project: hank-master  File: CurlyMerger.java View source code
@Override
public long[] merge(final CurlyFilePath base, final List<String> deltaRemoteFiles, final PartitionRemoteFileOps partitionRemoteFileOps) throws IOException {
    long[] offsetAdjustments = new long[deltaRemoteFiles.size() + 1];
    offsetAdjustments[0] = 0;
    // Open the base in append mode
    File baseFile = new File(base.getPath());
    FileOutputStream baseOutputStream = new FileOutputStream(baseFile, true);
    try {
        // Loop over deltas and append them to the base in order, keeping track of offset adjustments
        long totalOffset = baseFile.length();
        int i = 1;
        for (String deltaRemoteFile : deltaRemoteFiles) {
            offsetAdjustments[i] = totalOffset;
            InputStream deltaRemoteInputStream = partitionRemoteFileOps.getInputStream(deltaRemoteFile);
            try {
                LOG.info("Merging remote file " + deltaRemoteFile + " into file " + base.getPath());
                long bytesCopied = IOStreamUtils.copy(deltaRemoteInputStream, baseOutputStream);
                totalOffset += bytesCopied;
            } finally {
                deltaRemoteInputStream.close();
            }
            i++;
        }
    } finally {
        // Close base streams
        baseOutputStream.close();
    }
    return offsetAdjustments;
}
Example 81
Project: androiddevice.info-master  File: OtacertsProperty.java View source code
private static HashMap<String, X509Certificate> getTrustedCerts(File keystore) throws IOException, GeneralSecurityException {
    HashMap<String, X509Certificate> certs = new HashMap<String, X509Certificate>();
    ZipFile zip = new ZipFile(keystore);
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            InputStream is = zip.getInputStream(entry);
            try {
                certs.put(entry.getName(), (X509Certificate) cf.generateCertificate(is));
            } finally {
                is.close();
            }
        }
    } finally {
        zip.close();
    }
    return certs;
}
Example 82
Project: mkgmap-master  File: O5mBinMapDataSource.java View source code
@Override
public void load(InputStream is) throws FormatException {
    O5mBinHandler handler = new O5mBinHandler(is);
    setupHandler(handler);
    handler.parse();
    handler = null;
    elementSaver.finishLoading();
    osmReadingHooks.end();
    osmReadingHooks = null;
    // now convert the saved elements
    elementSaver.convert(getConverter());
    addBackground();
}
Example 83
Project: dlna-master  File: FileDownTask.java View source code
private boolean request() {
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(requesetMethod);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setConnectTimeout(CONNECT_TIME_OUT);
        responsCode = conn.getResponseCode();
        if (responsCode != 200) {
            log.d("responsCode = " + responsCode + ", so Fail!!!");
            return false;
        }
        InputStream inputStream = conn.getInputStream();
        isDownloadSuccess = FileHelper.writeFile(saveUri, inputStream);
        log.e("fileDownLoadTask writefile ret = " + isDownloadSuccess + "\nrequestUri = " + requestUrl + "\nsaveUri = " + saveUri);
        inputStream.close();
        return isDownloadSuccess;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        log.e("catch MalformedURLException e = " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        log.e("catch IOException e = " + e.getMessage());
    }
    return false;
}
Example 84
Project: teiid-designer-master  File: ZipReader.java View source code
/**
     * Read entries in zip file and return an [email protected] InputStream} to the
     * file that matches the given fileName or null if there is no file
     *
     * @param fileName
     * @param callback
     *
     * @throws Exception
     */
public void readEntry(String fileName, ZipReaderCallback callback) throws Exception {
    ZipFile zipFile = null;
    InputStream inputStream = null;
    try {
        zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry zipEntry = entries.nextElement();
            if (!zipEntry.getName().equals(fileName))
                continue;
            inputStream = zipFile.getInputStream(zipEntry);
            callback.process(inputStream);
            break;
        }
    } finally {
        if (inputStream != null)
            inputStream.close();
        if (zipFile != null)
            zipFile.close();
    }
}
Example 85
Project: bigpetstore-master  File: TestIOUtils.java View source code
@Test
public void testWrappedReadForCompressedData() throws IOException {
    byte[] buf = new byte[2];
    InputStream mockStream = Mockito.mock(InputStream.class);
    Mockito.when(mockStream.read(buf, 0, 1)).thenReturn(1);
    Mockito.when(mockStream.read(buf, 0, 2)).thenThrow(new java.lang.InternalError());
    try {
        assertEquals("Check expected value", 1, IOUtils.wrappedReadForCompressedData(mockStream, buf, 0, 1));
    } catch (IOException ioe) {
        fail("Unexpected error while reading");
    }
    try {
        IOUtils.wrappedReadForCompressedData(mockStream, buf, 0, 2);
    } catch (IOException ioe) {
        assertTrue("Unexpected exception caught", ioe.getMessage().contains("Error while reading compressed data"));
    }
}
Example 86
Project: WearPomodoro-master  File: PomodoroUtils.java View source code
private static long copy(final InputStream input, final OutputStream output) throws IOException {
    final byte[] buffer = new byte[1024 * 4];
    long count = 0;
    int n;
    int EOF = -1;
    while (EOF != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
        count += n;
    }
    return count;
}
Example 87
Project: sslcertx-master  File: NamedPipeSocket.java View source code
public void connect(SocketAddress endpoint, int timeout) throws IOException {
    String filename;
    if (host == null || host.equals("localhost")) {
        filename = "\\\\.\\pipe\\" + name;
    } else {
        filename = "\\\\" + host + "\\pipe\\" + name;
    }
    file = new RandomAccessFile(filename, "rw");
    is = new InputStream() {

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            return file.read(b, off, len);
        }

        @Override
        public int read() throws IOException {
            return file.read();
        }

        @Override
        public int read(byte[] b) throws IOException {
            return file.read(b);
        }
    };
    os = new OutputStream() {

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            file.write(b, off, len);
        }

        @Override
        public void write(int b) throws IOException {
            file.write(b);
        }

        @Override
        public void write(byte[] b) throws IOException {
            file.write(b);
        }
    };
}
Example 88
Project: speechalyzer-master  File: EmlUtils.java View source code
public static String postAudioToEml(String filename, String emlURL) {
    String result = "";
    try {
        logger.debug("requesting: " + emlURL + " with file: " + filename);
        ClientHttpRequest chr = new ClientHttpRequest(emlURL);
        chr.setParameter("audio", new File(filename));
        InputStream is = chr.post();
        final char[] buffer = new char[0x10000];
        StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(is, FileUtil.ENCODING_ISO8859_1);
        int read;
        do {
            read = in.read(buffer, 0, buffer.length);
            if (read > 0) {
                out.append(buffer, 0, read);
            }
        } while (read >= 0);
        result = out.toString();
        logger.debug("result: " + result);
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
    return result;
}
Example 89
Project: CReader-master  File: VersionParser.java View source code
public static List<VersionData> getPersonsByParseXml(InputStream is) {
    //    	Log.i("pull parser","begin");
    List<VersionData> list = null;
    VersionData r = null;
    String currentTag = null;
    try {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        XmlPullParser parser = factory.newPullParser();
        parser.setInput(is, "utf-8");
        int type = parser.getEventType();
        while (type != XmlPullParser.END_DOCUMENT) {
            String typeName = parser.getName();
            if (type == XmlPullParser.START_TAG) {
                //                Log.v("TAG", "typeName=" + typeName);   
                if ("version".equals(typeName)) {
                    list = new ArrayList<VersionData>();
                    r = new VersionData();
                } else if ("versioncode".equals(typeName)) {
                    currentTag = "versioncode";
                } else if ("content".equals(typeName)) {
                    currentTag = "content";
                } else if ("updateurl".equals(typeName)) {
                    currentTag = "updateurl";
                } else if ("control".equals(typeName)) {
                    currentTag = "control";
                }
            } else if (type == XmlPullParser.END_TAG) {
                if ("version".equals(typeName)) {
                    list.add(r);
                    r = null;
                }
            } else if (type == XmlPullParser.TEXT) {
                String s = parser.getText();
                //                Log.i("text",s);
                if ("versioncode".equals(currentTag)) {
                    r.setVersionCode(s);
                    currentTag = null;
                } else if ("content".equals(currentTag)) {
                    r.setContent(s);
                    currentTag = null;
                } else if ("updateurl".equals(currentTag)) {
                    r.setUpdate_url(s);
                    currentTag = null;
                } else if ("control".equals(currentTag)) {
                    r.setControl(Integer.parseInt(s.trim()));
                    currentTag = null;
                }
            }
            type = parser.next();
        }
    //        Log.v("TAG", "size=" + list.size());   
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;
}
Example 90
Project: AndroidBinding-master  File: TemplateWriter.java View source code
public static String make(InputStream template, Hashtable<String, String> data) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(template));
    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line + "\n");
    }
    String content = builder.toString();
    for (Entry<String, String> entry : data.entrySet()) {
        String replace = "${" + entry.getKey() + "}";
        //			System.out.println("entry: " + replace + ": " + entry.getValue());
        content = content.replace(replace, entry.getValue());
    }
    return content;
}
Example 91
Project: AudioPlayer-master  File: FileHelper.java View source code
public void WriteFile(InputStream instream, String path) throws IOException {
    byte[] buffer = new byte[1024];
    // 写出图片到SD卡
    FileOutputStream outStream = new FileOutputStream(new File(path));
    int len;
    while ((len = instream.read(buffer)) != -1) outStream.write(buffer, 0, len);
    // 关闭
    outStream.close();
    instream.close();
}
Example 92
Project: android-15-master  File: SSLTest.java View source code
public void testCertificate() throws Exception {
    // test www.fortify.net/sslcheck.html
    Socket ssl = SSLCertificateSocketFactory.getDefault().createSocket("www.fortify.net", 443);
    assertNotNull(ssl);
    OutputStream out = ssl.getOutputStream();
    assertNotNull(out);
    InputStream in = ssl.getInputStream();
    assertNotNull(in);
    String get = "GET /sslcheck.html HTTP/1.1\r\nHost: 68.178.217.222\r\n\r\n";
    // System.out.println("going for write...");
    out.write(get.getBytes());
    byte[] b = new byte[1024];
    // System.out.println("going for read...");
    int ret = in.read(b);
// System.out.println(new String(b));
}
Example 93
Project: wisdom-master  File: AssetIT.java View source code
@Test
public void testThatAssetsIncludedInTheWebJarAreServed() throws Exception {
    HttpResponse<String> math = get("/libs/js/math.js").asString();
    assertThat(math.code()).isEqualTo(200);
    math = get("/libs/my-web-resources/1.0-testing/js/math.js").asString();
    assertThat(math.code()).isEqualTo(200);
    math = get("/libs/my-web-resources/js/math.js").asString();
    assertThat(math.code()).isEqualTo(200);
    HttpResponse<String> site = get("/libs/style/site.css").asString();
    assertThat(site.code()).isEqualTo(200);
    site = get("/libs/style/site.less").asString();
    assertThat(site.code()).isEqualTo(200);
    HttpResponse<InputStream> img = get("/libs/owl-small.png").asBinary();
    assertThat(img.code()).isEqualTo(200);
}
Example 94
Project: OsmUi-master  File: mxPngTextDecoder.java View source code
/**
	 * Decodes the zTXt chunk of the given PNG image stream.
	 */
public static Map<String, String> decodeCompressedText(InputStream stream) {
    Map<String, String> result = new Hashtable<String, String>();
    if (!stream.markSupported()) {
        stream = new BufferedInputStream(stream);
    }
    DataInputStream distream = new DataInputStream(stream);
    try {
        long magic = distream.readLong();
        if (magic != 0x89504e470d0a1a0aL) {
            throw new RuntimeException("PNGImageDecoder0");
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("PNGImageDecoder1");
    }
    do {
        try {
            int length = distream.readInt();
            int type = distream.readInt();
            byte[] data = new byte[length];
            distream.readFully(data);
            // Move past the crc
            distream.readInt();
            if (type == PNG_CHUNK_IEND) {
                return result;
            } else if (type == PNG_CHUNK_ZTXT) {
                int currentIndex = 0;
                while ((data[currentIndex++]) != 0) {
                }
                String key = new String(data, 0, currentIndex - 1);
                // TODO Add option to decode uncompressed text
                //byte compressType = data[currentIndex++];
                StringBuffer value = new StringBuffer();
                try {
                    InputStream is = new ByteArrayInputStream(data, currentIndex, length);
                    InputStream iis = new InflaterInputStream(is);
                    int c;
                    while ((c = iis.read()) != -1) {
                        value.append((char) c);
                    }
                    result.put(String.valueOf(key), String.valueOf(value));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    } while (true);
}
Example 95
Project: tinkerpop-master  File: HadoopPoolShimService.java View source code
public Object readClassAndObject(final InputStream source) {
    Kryo k = null;
    try {
        k = HadoopPools.getGryoPool().takeKryo();
        return k.readClassAndObject(new Input(source));
    } finally {
        if (null != k) {
            HadoopPools.getGryoPool().offerKryo(k);
        }
    }
}
Example 96
Project: Inside_Android_Testing-master  File: ApiGateway.java View source code
@Override
protected ApiResponse doInBackground(ApiRequest... apiRequests) {
    ApiRequest apiRequest = apiRequests[0];
    InputStream responseBody = null;
    try {
        Http.Response response;
        if (HttpPost.METHOD_NAME.equals(apiRequest.getMethod())) {
            response = http.post(apiRequest.getUrlString(), apiRequest.getHeaders(), apiRequest.getPostBody(), apiRequest.getUsername(), apiRequest.getPassword());
        } else if (HttpGet.METHOD_NAME.equals(apiRequest.getMethod())) {
            response = http.get(apiRequest.getUrlString(), apiRequest.getHeaders(), apiRequest.getUsername(), apiRequest.getPassword());
        } else {
            throw new RuntimeException("Unsupported Http Method!");
        }
        responseBody = response.getResponseBody();
        ApiResponse apiResponse = apiRequest.createResponse(response.getStatusCode());
        apiResponse.consumeResponse(responseBody);
        return apiResponse;
    } catch (Exception e) {
        return apiRequest.createResponse(-1);
    } finally {
        if (responseBody != null) {
            try {
                responseBody.close();
            } catch (IOException ignored) {
            }
        }
    }
}
Example 97
Project: cdo-master  File: Bugzilla_351067_Test.java View source code
public void testCommitBlob() throws Exception {
    skipStoreWithoutLargeObjects();
    CDOSession session = openSession();
    CDOTransaction transaction = session.openTransaction();
    CDOResource resource = transaction.createResource(getResourcePath("res"));
    InputStream inputStream = null;
    try {
        inputStream = OM.BUNDLE.getInputStream("uml2/Ecore.uml");
        CDOBlob blob = new CDOBlob(inputStream);
        Image image = getModel3Factory().createImage();
        image.setWidth(320);
        image.setHeight(200);
        image.setData(blob);
        resource.getContents().add(image);
        transaction.commit();
    } finally {
        IOUtil.close(inputStream);
    }
    try {
        inputStream = OM.BUNDLE.getInputStream("uml2/Ecore.uml");
        CDOBlob blob = new CDOBlob(inputStream);
        Image image = getModel3Factory().createImage();
        image.setWidth(320);
        image.setHeight(200);
        image.setData(blob);
        resource.getContents().add(image);
        transaction.commit();
    } finally {
        IOUtil.close(inputStream);
    }
}
Example 98
Project: Eclipse-Postfix-Code-Completion-master  File: ClasspathSourceJar.java View source code
public NameEnvironmentAnswer findClass(char[] typeName, String qualifiedPackageName, String qualifiedBinaryFileName, boolean asBinaryOnly) {
    if (!isPackage(qualifiedPackageName))
        // most common case
        return null;
    ZipEntry sourceEntry = this.zipFile.getEntry(qualifiedBinaryFileName.substring(0, qualifiedBinaryFileName.length() - 6) + SUFFIX_STRING_java);
    if (sourceEntry != null) {
        try {
            InputStream stream = null;
            char[] contents = null;
            try {
                stream = this.zipFile.getInputStream(sourceEntry);
                contents = Util.getInputStreamAsCharArray(stream, -1, this.encoding);
            } finally {
                if (stream != null)
                    stream.close();
            }
            return new NameEnvironmentAnswer(new CompilationUnit(contents, qualifiedBinaryFileName.substring(0, qualifiedBinaryFileName.length() - 6) + SUFFIX_STRING_java, this.encoding, this.destinationPath), fetchAccessRestriction(qualifiedBinaryFileName));
        } catch (IOException e) {
        }
    }
    return null;
}
Example 99
Project: geoserver-enterprise-master  File: ComplexTransmuter.java View source code
/**
     * Used to decode external XML documents for use as process inputs
     *
     * @param stream
     * @return
     */
public Object decode(InputStream stream) {
    Object decoded = null;
    Configuration config = null;
    try {
        config = (Configuration) (this.getXMLConfiguration().getConstructor().newInstance());
    } catch (Exception e) {
        throw new WPSException("NoApplicableCode", "Failed to initialize XMLConfiguration");
    }
    org.geotools.xml.Parser parser = new org.geotools.xml.Parser(config);
    try {
        decoded = (Geometry) parser.parse(stream);
    } catch (Exception e) {
        throw new WPSException("NoApplicableCode", "Parsing error " + e);
    }
    return decoded;
}
Example 100
Project: google-web-toolkit-svnmirror-master  File: MockModuleDef.java View source code
@Override
public Resource findPublicFile(String partialPath) {
    if ("onPublicPath.txt".equals(partialPath)) {
        return new Resource() {

            @Override
            public long getLastModified() {
                return 0;
            }

            @Override
            public String getLocation() {
                return "/mock/onPublicPath.txt";
            }

            @Override
            public String getPath() {
                return "onPublicPath.txt";
            }

            @Override
            public InputStream openContents() {
                return new ByteArrayInputStream(Util.getBytes("w00t!"));
            }

            @Override
            public boolean wasRerooted() {
                return false;
            }
        };
    }
    return null;
}
Example 101
Project: platform-friends-android-master  File: BitmapDownloadTask.java View source code
@Override
protected Bitmap doInBackground(String... strings) {
    String pictureId = strings[0];
    try {
        if (pictureId != null) {
            Bitmap bitmap = BaseViewModel.getInstance().getPictureById(UUID.fromString(pictureId));
            if (bitmap != null) {
                return bitmap;
            }
            String url = null;
            RequestResult userImageRequest = BaseViewModel.EverliveAPP.workWith().files().getById(pictureId).executeSync();
            if (userImageRequest.getSuccess()) {
                url = ((File) userImageRequest.getValue()).getUri();
                URL imageUrl = new URL(url);
                InputStream inputStream = imageUrl.openStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
                BaseViewModel.getInstance().addPicture(UUID.fromString(pictureId), bitmap);
                return bitmap;
            }
        }
        switch(this.imageKind) {
            case User:
                {
                    return BitmapFactory.decodeResource(this.context.getResources(), R.drawable.ic_contact_picture_64);
                }
            default:
                {
                    return null;
                }
        }
    } catch (Exception ex) {
        Log.e("Exception when downloading image: ", ex.getMessage().toString());
    }
    return null;
}