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: SelectBestFlavorNPETest.java View source code
public static void main(String[] args) {
    DataFlavor flavor1 = new DataFlavor("text/plain; charset=unicode; class=java.io.InputStream", "Flavor 1");
    DataFlavor flavor2 = new DataFlavor("text/plain; class=java.io.InputStream", "Flavor 2");
    DataFlavor[] flavors = new DataFlavor[] { flavor1, flavor2 };
    try {
        DataFlavor best = DataFlavor.selectBestTextFlavor(flavors);
        System.out.println("best=" + best);
    } catch (NullPointerException e1) {
        throw new RuntimeException("Test FAILED because of NPE in selectBestTextFlavor");
    }
}
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: IOTools.java View source code
public static final String getStringFromStream(InputStream is, String charsetName) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(is, charsetName));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line + System.getProperty("line.separator"));
    }
    br.close();
    return sb.toString();
}
Example 9
Project: ocr-tools-master  File: OptionsReader.java View source code
public static String getLanguages() throws FileNotFoundException, IOException {
    InputStream propsStream = OptionsReader.class.getClassLoader().getResourceAsStream("languages.properties");
    BufferedReader r = new BufferedReader(new InputStreamReader(propsStream));
    String langs = "";
    String[] keyValue = r.readLine().split("\\s*=\\s*");
    langs += "<option selected=\"selected\" value=\"" + keyValue[0] + "\">" + keyValue[1] + "</option>\n";
    String line = "";
    while ((line = r.readLine()) != null) {
        keyValue = line.split("\\s*=\\s*");
        if (keyValue.length == 2) {
            langs += "<option value=\"" + keyValue[0] + "\">" + keyValue[1] + "</option>\n";
        }
    }
    return langs;
}
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: JceKeyAgreeEnvelopedRecipient.java View source code
public RecipientOperator getRecipientOperator(AlgorithmIdentifier keyEncryptionAlgorithm, final AlgorithmIdentifier contentEncryptionAlgorithm, SubjectPublicKeyInfo senderPublicKey, ASN1OctetString userKeyingMaterial, byte[] encryptedContentKey) throws CMSException {
    Key secretKey = extractSecretKey(keyEncryptionAlgorithm, contentEncryptionAlgorithm, senderPublicKey, userKeyingMaterial, encryptedContentKey);
    final Cipher dataCipher = contentHelper.createContentCipher(secretKey, contentEncryptionAlgorithm);
    return new RecipientOperator(new InputDecryptor() {

        public AlgorithmIdentifier getAlgorithmIdentifier() {
            return contentEncryptionAlgorithm;
        }

        public InputStream getInputStream(InputStream dataOut) {
            return new CipherInputStream(dataOut, dataCipher);
        }
    });
}
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: PdfExtractor.java View source code
@Override
public String extractText(String mimeType, InputStream inputStream, String encoding) throws IOException {
    if (canHandle(mimeType)) {
        PDDocument doc = PDDocument.load(inputStream);
        PDFTextStripper stripper = new PDFTextStripper();
        String text = stripper.getText(doc);
        doc.close();
        return text;
    } else {
        return null;
    }
}
Example 22
Project: FireflowEngine20-master  File: ResourceDeserializerTest.java View source code
/**
	 * Test method for [email protected] org.fireflow.model.io.resource.ResourceDeserializer#deserialize(java.io.InputStream)}.
	 */
@Test
public void testDeserialize() throws Exception {
    InputStream in = ResourceDeserializerTest.class.getResourceAsStream("resourcedef.xml");
    List<ResourceDef> resourceList2 = ResourceDeserializer.deserialize(in);
    Assert.assertNotNull(resourceList2);
    Assert.assertEquals(5, resourceList2.size());
    ResourceDef tmpResourceDef = findResource(resourceList2, "var_implement");
    Assert.assertNotNull(tmpResourceDef);
    Assert.assertEquals(ResourceType.VARIABLE_IMPLICATION, tmpResourceDef.getResourceType());
    Assert.assertEquals(1, tmpResourceDef.getExtendedAttributes().size());
    Assert.assertEquals("var1", tmpResourceDef.getValue());
}
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: JsonBuilder.java View source code
public OMElement processDocument(InputStream inputStream, String s, MessageContext messageContext) throws AxisFault {
    OMElement element = JsonUtil.toXml(inputStream, true);
    if (logger.isDebugEnabled()) {
        logger.debug("#processDocument. Built XML payload from JSON stream. MessageID: " + messageContext.getMessageID());
    }
    return element;
}
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: AsciiLineReaderTest.java View source code
/**
     * Test that we read the correct number of lines
     * from a file
     * @throws Exception
     */
@Test
public void testReadLines() throws Exception {
    String filePath = TestUtils.DATA_DIR + "gwas/smallp.gwas";
    InputStream is = new FileInputStream(filePath);
    AsciiLineReader reader = new AsciiLineReader(is);
    int actualLines = 0;
    int expectedNumber = 20;
    String nextLine = "";
    while ((nextLine = reader.readLine()) != null && actualLines < (expectedNumber + 5)) {
        actualLines++;
        //This particular test file has no empty lines
        assertTrue(nextLine.length() > 0);
    }
    assertEquals(expectedNumber, actualLines);
}
Example 27
Project: xmind-master  File: WorkbookMarkerResourceProvider.java View source code
/*
     * (non-Javadoc)
     * 
     * @see
     * org.xmind.core.marker.IMarkerResourceAllocator#allocateMarkerResourcePath
     * (java.io.InputStream, java.lang.String)
     */
public String allocateMarkerResource(InputStream source, String suggestedPath) throws IOException {
    String ext = //$NON-NLS-1$
    suggestedPath == null ? //$NON-NLS-1$
    ".png" : FileUtils.getExtension(suggestedPath);
    String path = Core.getIdFactory().createId() + ext;
    IFileEntry entry = workbook.getManifest().createFileEntry(ArchiveConstants.PATH_MARKERS + path);
    OutputStream target = entry.openOutputStream();
    try {
        FileUtils.transfer(source, target, false);
    } finally {
        target.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: UnicodeLittleDecoder.java View source code
/**
   * @see wonka.decoders.Decoder#cFromStream(java.io.InputStream, char[], int, int)
   */
public int cFromStream(InputStream in, char[] chars, int off, int len) throws IOException {
    if (state == Decoder.LITTLEEND) {
        return super.cFromStream(in, chars, off, len);
    }
    int rd = super.cFromStream(in, chars, off, len);
    if (state != Decoder.LITTLEEND) {
        throw new IOException();
    }
    return rd;
}
Example 30
Project: turmeric-eclipse-master  File: TestPropertiesFileUtil.java View source code
/**
	 * Test method for [email protected] [email protected]etPropertyValueByKey(java.io.InputStream, java.lang.String)}.
	 * @throws IOException 
	 */
@Test
public void testGetPropertyValueByKey() throws IOException {
    File tempFile = null;
    InputStream input = null;
    OutputStream output = null;
    try {
        tempFile = File.createTempFile("nikon", "d80");
        output = new FileOutputStream(tempFile);
        Properties props = new Properties();
        props.put("Nikon", "d80,d90,d700,d3s,d3x");
        props.store(output, "Comments");
        IOUtils.closeQuietly(output);
        input = new FileInputStream(tempFile);
        String value = PropertiesFileUtil.getPropertyValueByKey(input, "Nikon");
        Assert.assertNotNull(value);
        Assert.assertEquals("d80,d90,d700,d3s,d3x", value);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(input);
        tempFile.delete();
    }
}
Example 31
Project: molgenis-master  File: XmlMolgenisUiLoader.java View source code
public Molgenis load() throws IOException {
    InputStream xsdStream = this.getClass().getResourceAsStream(UI_XSD);
    if (xsdStream == null)
        throw new IOException("unable to find " + UI_XSD);
    try {
        InputStream xmlStream = this.getClass().getResourceAsStream(UI_XML);
        if (xmlStream == null)
            throw new IOException("unable to find " + UI_XML);
        try {
            SchemaLoader schemaLoader = new SchemaLoader(xsdStream);
            Schema molgenisUiSchema = schemaLoader.getSchema();
            JAXBContext jaxbContext = JAXBContext.newInstance(Molgenis.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            unmarshaller.setSchema(molgenisUiSchema);
            return unmarshaller.unmarshal(new StreamSource(xmlStream), Molgenis.class).getValue();
        } catch (JAXBException e) {
            throw new IOException(e);
        } finally {
            IOUtils.closeQuietly(xmlStream);
        }
    } finally {
        IOUtils.closeQuietly(xsdStream);
    }
}
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: ByteArrayZipEntryTransformer.java View source code
public void transform(InputStream in, ZipEntry zipEntry, ZipOutputStream out) throws IOException {
    byte[] bytes = IOUtils.toByteArray(in);
    bytes = transform(zipEntry, bytes);
    ByteSource source;
    if (preserveTimestamps()) {
        source = new ByteSource(zipEntry.getName(), bytes, zipEntry.getTime());
    } else {
        source = new ByteSource(zipEntry.getName(), bytes);
    }
    ZipEntrySourceZipEntryTransformer.addEntry(source, out);
}
Example 34
Project: btpka3.github.com-master  File: AntiSamyDemo.java View source code
public static void main(String[] args) throws PolicyException, IOException, ScanException {
    InputStream prolicyIn = AntiSamyDemo.class.getResourceAsStream("antisamy-ebay-1.4.4.xml");
    Policy policy = Policy.getInstance(prolicyIn);
    AntiSamy as = new AntiSamy();
    String drityInput = "<script>alert(1)</script>" + "<a href='#bb' style='z-index:999; width:100%;' onclick='xxx'>aa</a>" + "<iframe src='javascript:xxx'></iframe>" + "<xxx>xxx</xxx>";
    // 输出: <a href="#bb" style="width: 100.0%;">aa</a> xxx
    CleanResults cr = as.scan(drityInput, policy, AntiSamy.SAX);
    String cleanResult = cr.getCleanHTML();
    System.out.println(cleanResult);
}
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: SystemExitTest.java View source code
@Test
public void failureCausesExitCodeOf1() throws Exception {
    String java = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
    String classPath = getClass().getClassLoader().getResource(".").getFile() + File.pathSeparator + System.getProperty("java.class.path");
    String[] cmd = { java, "-cp", classPath, getClass().getName() + "$Exit" };
    Process process = Runtime.getRuntime().exec(cmd);
    InputStream input = process.getInputStream();
    while ((input.read()) != -1) ;
    assertEquals(EXIT_CODE, process.waitFor());
}
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: TestUtil.java View source code
/**
     * Used to read test resource
     * 
     * @param fileName
     * @return
     * @throws Exception
     */
public static String readTestResource(Class cls, String fileName) throws Exception {
    InputStreamReader fr = null;
    BufferedReader br = null;
    try {
        InputStream inputStream = cls.getResourceAsStream(fileName);
        fr = new InputStreamReader(inputStream);
        br = new BufferedReader(fr);
        StringBuffer buffer = new StringBuffer();
        String tmpStr;
        while ((tmpStr = br.readLine()) != null) {
            buffer.append(tmpStr);
        }
        return buffer.toString();
    } finally {
        if (br != null) {
            br.close();
        }
        if (fr != null) {
            fr.close();
        }
    }
}
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();
}