java.io.InputStream Java Examples
The following examples show how to use
java.io.InputStream.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: S3ObjectSerializer.java From camel-kafka-connector with Apache License 2.0 | 7 votes |
@Override public byte[] serialize(String topic, S3ObjectInputStream data) { InputStream is = data.getDelegateStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] byteArray = new byte[16384]; try { while ((nRead = is.read(byteArray, 0, byteArray.length)) != -1) { buffer.write(byteArray, 0, nRead); } } catch (IOException e) { LOG.warn("I/O error while serializing data from or to topic {}: {} | {}", topic, e.getMessage(), e); } return buffer.toByteArray(); }
Example #2
Source File: AbstractKeycloakLoginModule.java From keycloak with Apache License 2.0 | 6 votes |
protected KeycloakDeployment resolveDeployment(String keycloakConfigFile) { try { InputStream is = null; if (keycloakConfigFile.startsWith(PROFILE_RESOURCE)) { try { is = new URL(keycloakConfigFile).openStream(); } catch (MalformedURLException mfue) { throw new RuntimeException(mfue); } catch (IOException ioe) { throw new RuntimeException(ioe); } } else { is = FindFile.findFile(keycloakConfigFile); } KeycloakDeployment kd = KeycloakDeploymentBuilder.build(is); return kd; } catch (RuntimeException e) { getLogger().debug("Unable to find or parse file " + keycloakConfigFile + " due to " + e.getMessage(), e); throw e; } }
Example #3
Source File: SessionEstablisher.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
private static long readFile(FileOutputStream fos, InputStream in, long filesize) throws IOException { int foo; long tempfilesize=filesize; while (true) { if (bufs.length < tempfilesize){ foo = bufs.length; }else { foo = (int) tempfilesize; } foo = in.read(bufs, 0, foo); if (foo < 0) { // error break; } fos.write(bufs, 0, foo); tempfilesize -= foo; if (tempfilesize == 0L){ break; } } return tempfilesize; }
Example #4
Source File: UserAttribute362ImplTest.java From portals-pluto with Apache License 2.0 | 6 votes |
/** * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { InputStream in = UserAttribute362ImplTest.class .getClassLoader().getResourceAsStream(XML_FILE); ConfigurationHolder cfp = new ConfigurationHolder(); try { cfp.processPortletDD(in); pad = cfp.getPad(); } catch (Exception e) { e.printStackTrace(); throw e; } }
Example #5
Source File: EmbedPreparedStatement.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** * We do this inefficiently and read it all in here. The target type * is assumed to be a String. * * @param parameterIndex the first parameter is 1, the second is 2, ... * @param x the java input stream which contains the ASCII parameter value * @param length the number of bytes in the stream * @exception SQLException thrown on failure. */ public final void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { checkAsciiStreamConditions(parameterIndex); java.io.Reader r = null; if (x != null) { // Use ISO-8859-1 and not US-ASCII as JDBC seems to define // ASCII as 8 bits. US-ASCII is 7. try { r = new java.io.InputStreamReader(x, "ISO-8859-1"); } catch (java.io.UnsupportedEncodingException uee) { throw new SQLException(uee.getMessage()); } } setCharacterStreamInternal(parameterIndex, r, false, length); }
Example #6
Source File: ClientHttpRequestFactoryFactory.java From spring-vault with Apache License 2.0 | 6 votes |
private static void loadFromPem(KeyStore keyStore, InputStream inputStream) throws IOException, KeyStoreException { List<PemObject> pemObjects = PemObject.parse(new String(FileCopyUtils.copyToByteArray(inputStream))); for (PemObject pemObject : pemObjects) { if (pemObject.isCertificate()) { X509Certificate cert = pemObject.getCertificate(); String alias = cert.getSubjectX500Principal().getName(); if (logger.isDebugEnabled()) { logger.debug(String.format("Adding certificate with alias %s", alias)); } keyStore.setCertificateEntry(alias, cert); } } }
Example #7
Source File: PBImageXmlWriter.java From hadoop with Apache License 2.0 | 6 votes |
private void dumpINodeDirectorySection(InputStream in) throws IOException { out.print("<INodeDirectorySection>"); while (true) { INodeDirectorySection.DirEntry e = INodeDirectorySection.DirEntry .parseDelimitedFrom(in); // note that in is a LimitedInputStream if (e == null) { break; } out.print("<directory>"); o("parent", e.getParent()); for (long id : e.getChildrenList()) { o("inode", id); } for (int refId : e.getRefChildrenList()) { o("inodereference-index", refId); } out.print("</directory>\n"); } out.print("</INodeDirectorySection>\n"); }
Example #8
Source File: PFASQLiteHelper.java From privacy-friendly-weather with GNU General Public License v3.0 | 6 votes |
/** * Fill TABLE_CITIES_TO_WATCH with all the Cities */ private synchronized void fillCityDatabase(SQLiteDatabase db) { long startInsertTime = System.currentTimeMillis(); InputStream inputStream = context.getResources().openRawResource(R.raw.city_list); try { FileReader fileReader = new FileReader(); final List<City> cities = fileReader.readCitiesFromFile(inputStream); addCities(db, cities); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } long endInsertTime = System.currentTimeMillis(); Log.d("debug_info", "Time for insert:" + (endInsertTime - startInsertTime)); }
Example #9
Source File: CommonFileUtils.java From cos-java-sdk with MIT License | 6 votes |
public static byte[] getFileContentByte(InputStream inputStream, long offset, int length) throws Exception { if (offset < 0 || length < 0) { throw new Exception("getFileContent param error"); } byte[] fileContent = null; byte[] tempBuf = new byte[length]; inputStream.skip(offset); int readLen = inputStream.read(tempBuf); if (readLen < 0) { fileContent = new byte[0]; return fileContent; } if (readLen < length) { fileContent = new byte[readLen]; System.arraycopy(tempBuf, 0, fileContent, 0, readLen); } else { fileContent = tempBuf; } return fileContent; }
Example #10
Source File: AopHttpURLConnection.java From ArgusAPM with Apache License 2.0 | 6 votes |
@Override public InputStream getInputStream() throws IOException { NetInfo data = intAndGetMyData(); AopInputStream inputStream; if (DEBUG) { LogX.d(TAG, SUB_TAG, "... ...getInputStream() "); } try { inputStream = new AopInputStream(this.myConnection.getInputStream()); inspectAndInstrumentResponse(data, this.myConnection); // TODO: } catch (IOException e) { // TODO: throw e; } inputStream.setStreamCompleteListener(this); return inputStream; }
Example #11
Source File: ClassFileInstaller.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * @param args The names of the classes to dump * @throws Exception */ public static void main(String... args) throws Exception { for (String arg : args) { ClassLoader cl = ClassFileInstaller.class.getClassLoader(); // Convert dotted class name to a path to a class file String pathName = arg.replace('.', '/').concat(".class"); InputStream is = cl.getResourceAsStream(pathName); // Create the class file's package directory Path p = Paths.get(pathName); Path parent = p.getParent(); if (parent != null) { Files.createDirectories(parent); } // Create the class file Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING); } }
Example #12
Source File: BooleanConverter.java From jstarcraft-core with Apache License 2.0 | 6 votes |
@Override public Object readValueFrom(ProtocolReader context, Type type, ClassDefinition definition) throws IOException { InputStream in = context.getInputStream(); byte information = (byte) in.read(); byte mark = getMark(information); if (mark == NULL_MARK) { return null; } if (mark == FALSE_MARK) { if (type == AtomicBoolean.class) { return new AtomicBoolean(false); } return false; } else if (mark == TRUE_MARK) { if (type == AtomicBoolean.class) { return new AtomicBoolean(true); } return true; } String message = StringUtility.format("类型码[{}]没有对应标记码[{}]", type, mark); throw new CodecConvertionException(message); }
Example #13
Source File: SimpleFileOperations.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Override public StreamMetrics create(final Path path, final InputStream data) throws IOException { checkNotNull(path); checkNotNull(data); // Ensure path exists for new blob Path dir = path.getParent(); checkNotNull(dir, "Null parent for path: %s", path); DirectoryHelper.mkdir(dir); final MetricsInputStream input = new MetricsInputStream(data); try { try (final OutputStream output = Files.newOutputStream(path, StandardOpenOption.CREATE_NEW)) { ByteStreams.copy(input, output); } } finally { // FIXME: Revisit closing stream which is passed in as parameter, this should be the responsibility of the caller data.close(); } return input.getMetrics(); }
Example #14
Source File: BigdataNTriplesParserTestCase.java From database with GNU General Public License v2.0 | 6 votes |
public void testNTriplesFile() throws Exception { RDFParser turtleParser = createRDFParser(); turtleParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE); turtleParser.setRDFHandler(new RDFHandlerBase() { public void handleStatement(Statement st) throws RDFHandlerException { if (log.isInfoEnabled()) log.info("Statement: " + st); } }); // Note: This is a local copy. InputStream in = BigdataNTriplesParser.class.getResourceAsStream(NTRIPLES_TEST_FILE); try { turtleParser.parse(in, NTRIPLES_TEST_URL); } catch (RDFParseException e) { fail("Failed to parse N-Triples test document: " + e.getMessage()); } finally { in.close(); } }
Example #15
Source File: StreamPool50137Test.java From netbeans with Apache License 2.0 | 6 votes |
public void testStreamPoolDeadlock () throws Exception { FileLock fLock = testFo.lock(); OutputStream os = null; InputStream is = null; try { os = testFo.getOutputStream(fLock); os.close(); os = null; is = testFo.getInputStream(); is.close(); is = null; } finally { if (fLock != null) fLock.releaseLock(); if (os != null) os.close(); if (is != null) is.close(); } }
Example #16
Source File: JPGReader.java From icafe with Eclipse Public License 1.0 | 6 votes |
private void readAPP14(InputStream is) throws IOException { String[] app14Info = {"DCTEncodeVersion: ", "APP14Flags0: ", "APP14Flags1: ", "ColorTransform: "}; int expectedLen = 14; // Expected length of this segment is 14. int length = IOUtils.readUnsignedShortMM(is); if (length >= expectedLen) { byte[] data = new byte[length - 2]; IOUtils.readFully(is, data, 0, length - 2); byte[] buf = ArrayUtils.subArray(data, 0, 5); if(Arrays.equals(buf, ADOBE_ID.getBytes())) { for (int i = 0, j = 5; i < 3; i++, j += 2) { LOGGER.info("{}{}", app14Info[i], StringUtils.shortToHexStringMM(IOUtils.readShortMM(data, j))); } LOGGER.debug("{}{}", app14Info[3], (((data[11]&0xff) == 0)? "Unknown (RGB or CMYK)": ((data[11]&0xff) == 1)? "YCbCr":"YCCK" )); } } }
Example #17
Source File: Tutorial.java From rapidminer-studio with GNU Affero General Public License v3.0 | 5 votes |
/** * @return the {@link InputStream} to of this tutorial */ private InputStream getInputStream() throws IOException, RepositoryException { if (path != null) { return Files.newInputStream(path); } else { return Tools.getResourceInputStream(RESOURCES_LOCATION + getGroup().getName() + ".tutorial"); } }
Example #18
Source File: AbstractParser.java From android-chromium with BSD 2-Clause "Simplified" License | 5 votes |
public MessageType parseDelimitedFrom( InputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return checkMessageInitialized( parsePartialDelimitedFrom(input, extensionRegistry)); }
Example #19
Source File: AESEngineNoPaddingTest.java From sambox with Apache License 2.0 | 5 votes |
@Test public void ebcEncryptStream() throws IOException { AESEngineNoPadding victim = AESEngineNoPadding.ecb(); byte[] key = new byte[] { -91, 100, 117, 33, 83, 54, -34, -59, 87, -94, -94, 18, -113, -77, -60, 105, 95, -3, 70, -110, 19, -44, -15, 104, 44, 1, 31, 17, -97, 107, 59, 5 }; byte[] expected = new byte[] { -82, 109, -33, 109, -111, -94, 21, -77, 74, -119, 121, -115, -62, -128, 0, -43 }; try (InputStream inputStream = victim.encryptStream(new ByteArrayInputStream( new byte[] { -4, -1, -1, -1, -1, -1, -1, -1, 84, 97, 100, 98, -19, -29, 119, 38 }), key, null)) { assertArrayEquals(expected, IOUtils.toByteArray(inputStream)); } }
Example #20
Source File: TLRequestPaymentsSendPaymentForm.java From kotlogram with MIT License | 5 votes |
@Override @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"}) public void deserializeBody(InputStream stream, TLContext context) throws IOException { flags = readInt(stream); msgId = readInt(stream); requestedInfoId = (flags & 1) != 0 ? readTLString(stream) : null; shippingOptionId = (flags & 2) != 0 ? readTLString(stream) : null; credentials = readTLObject(stream, context, TLAbsInputPaymentCredentials.class, -1); }
Example #21
Source File: MobileExecuteRoute.java From s2g-zuul with MIT License | 5 votes |
private byte[] getBytes(InputStream is,int contentLength) throws IOException { ByteArrayOutputStream answer = new ByteArrayOutputStream(); // reading the content of the file within a byte buffer byte[] byteBuffer = new byte[contentLength]; int nbByteRead /* = 0 */; try { while ((nbByteRead = is.read(byteBuffer)) != -1) { // appends buffer answer.write(byteBuffer, 0, nbByteRead); } } finally { //closeWithWarning(is); } return answer.toByteArray(); }
Example #22
Source File: AsyncExporter.java From Android-Material-Icons with Apache License 2.0 | 5 votes |
private void copyDirectory(File sourceLocation, File targetLocation) throws IOException { if (sourceLocation.isDirectory()) { if (!targetLocation.exists() && !targetLocation.mkdirs()) { throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath()); } String[] children = sourceLocation.list(); for (String child : children) { copyDirectory(new File(sourceLocation, child), new File(targetLocation, child)); } } else { // make sure the directory we plan to store the recording in exists File directory = targetLocation.getParentFile(); if (directory != null && !directory.exists() && !directory.mkdirs()) { throw new IOException("Cannot create dir " + directory.getAbsolutePath()); } InputStream in = new FileInputStream(sourceLocation); OutputStream out = new FileOutputStream(targetLocation); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } }
Example #23
Source File: JSONList.java From yacy_grid_mcp with GNU Lesser General Public License v2.1 | 5 votes |
public JSONList(InputStream sourceStream) throws IOException { this(); BufferedReader br = new BufferedReader(new InputStreamReader(sourceStream, StandardCharsets.UTF_8)); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() == 0) continue; JSONObject json = new JSONObject(new JSONTokener(line)); this.add(json); } } catch (JSONException e) { throw new IOException(e); } }
Example #24
Source File: AddFilesToZipIT.java From zip4j with Apache License 2.0 | 5 votes |
@Test public void testAddStreamToZipWithCharsetCp949() throws IOException { String koreanFileName = "가나다.abc"; ZipFile zipFile = new ZipFile(generatedZipFile); File fileToAdd = TestUtils.getTestFileFromResources(koreanFileName); InputStream inputStream = new FileInputStream(fileToAdd); ZipParameters zipParameters = new ZipParameters(); zipParameters.setFileNameInZip(fileToAdd.getName()); zipFile.setCharset(CHARSET_CP_949); zipFile.addStream(inputStream, zipParameters); ZipFileVerifier.verifyZipFileByExtractingAllFiles(generatedZipFile, null, outputFolder, 1, true, CHARSET_CP_949); assertThat(zipFile.getFileHeaders().get(0).getFileName()).isEqualTo(koreanFileName); }
Example #25
Source File: AppletAudioClip.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
void createAppletAudioClip(InputStream in) throws IOException { try { audioClip = new JavaSoundAudioClip(in); } catch (Exception e3) { // no matter what happened, we throw an IOException to avoid changing the interfaces.... throw new IOException("Failed to construct the AudioClip: " + e3); } }
Example #26
Source File: SysAttachMainUploadOperationService.java From mPaaS with Apache License 2.0 | 5 votes |
/** * API上传附件 * @return 生成的附件ID */ @Transactional public String addByEntity(SysAttachUploadBytesVO uploadBytesVO) { // 定义使用完整上传模式,上传API附件的函数 Function<InputStream, SysAttachUploadResultVO> uploadFunction = inputStream -> sysAttachEntireUploader.upload(inputStream, uploadBytesVO.getFdEntityName()); // 执行上传操作逻辑 return this.recordBytesUpload(uploadBytesVO, new ByteArrayInputStream(uploadBytesVO.getFdFileData()), uploadBytesVO.getFdEntityId(), uploadBytesVO.getFdEntityKey(), uploadFunction); }
Example #27
Source File: ContentResolver.java From AndroidComponentPlugin with Apache License 2.0 | 5 votes |
/** * Open a stream on to the content associated with a content URI. If there * is no data associated with the URI, FileNotFoundException is thrown. * * <h5>Accepts the following URI schemes:</h5> * <ul> * <li>content ({@link #SCHEME_CONTENT})</li> * <li>android.resource ({@link #SCHEME_ANDROID_RESOURCE})</li> * <li>file ({@link #SCHEME_FILE})</li> * </ul> * * <p>See {@link #openAssetFileDescriptor(Uri, String)} for more information * on these schemes. * * @param uri The desired URI. * @return InputStream * @throws FileNotFoundException if the provided URI could not be opened. * @see #openAssetFileDescriptor(Uri, String) */ public final @Nullable InputStream openInputStream(@NonNull Uri uri) throws FileNotFoundException { Preconditions.checkNotNull(uri, "uri"); String scheme = uri.getScheme(); if (SCHEME_ANDROID_RESOURCE.equals(scheme)) { // Note: left here to avoid breaking compatibility. May be removed // with sufficient testing. OpenResourceIdResult r = getResourceId(uri); try { InputStream stream = r.r.openRawResource(r.id); return stream; } catch (Resources.NotFoundException ex) { throw new FileNotFoundException("Resource does not exist: " + uri); } } else if (SCHEME_FILE.equals(scheme)) { // Note: left here to avoid breaking compatibility. May be removed // with sufficient testing. return new FileInputStream(uri.getPath()); } else { AssetFileDescriptor fd = openAssetFileDescriptor(uri, "r", null); try { return fd != null ? fd.createInputStream() : null; } catch (IOException e) { throw new FileNotFoundException("Unable to create stream"); } } }
Example #28
Source File: Utils.java From java-cloudant with Apache License 2.0 | 5 votes |
/** * Consumes any available content from the stream (effectively sending it to /dev/null). * * @param is the stream to consume, may be {@code null} */ public static void consumeStream(InputStream is) { if (is != null) { try { // Copy the stream to a null destination long copied = IOUtils.copyLarge(is, NullOutputStream.NULL_OUTPUT_STREAM); if (copied > 0) { logger.log(Level.WARNING, "Consumed unused HTTP response error stream."); } } catch (IOException ioe) { // The stream was probably already closed, there's nothing further we can do anyway logger.log(Level.FINEST, "Unable to consume stream.", ioe); } } }
Example #29
Source File: ActionFile.java From Telegram-FOSS with GNU General Public License v2.0 | 5 votes |
/** * Loads {@link DownloadRequest DownloadRequests} from the file. * * @return The loaded {@link DownloadRequest DownloadRequests}, or an empty array if the file does * not exist. * @throws IOException If there is an error reading the file. */ public DownloadRequest[] load() throws IOException { if (!exists()) { return new DownloadRequest[0]; } InputStream inputStream = null; try { inputStream = atomicFile.openRead(); DataInputStream dataInputStream = new DataInputStream(inputStream); int version = dataInputStream.readInt(); if (version > VERSION) { throw new IOException("Unsupported action file version: " + version); } int actionCount = dataInputStream.readInt(); ArrayList<DownloadRequest> actions = new ArrayList<>(); for (int i = 0; i < actionCount; i++) { try { actions.add(readDownloadRequest(dataInputStream)); } catch (UnsupportedRequestException e) { // remove DownloadRequest is not supported. Ignore and continue loading rest. } } return actions.toArray(new DownloadRequest[0]); } finally { Util.closeQuietly(inputStream); } }
Example #30
Source File: ServiceProviderPlaceTest.java From emissary with Apache License 2.0 | 5 votes |
@Test public void testServiceKeyConfig() { try { // TPROXY.TNAME.ID.http://@{TGT_HOST}:@{TGT_PORT}/TPlaceName$5050 InputStream config = new ByteArrayInputStream(configKeyData); PlaceTest tp = new PlaceTest(config, null, "http://example.com:8001/PlaceTest"); assertEquals("Configured place name", "TPlaceName", tp.getPlaceName()); assertEquals("Primary proxy", "TPROXY", tp.getPrimaryProxy()); assertEquals("Key generation", "TPROXY.TNAME.ID.http://localhost:8001/TPlaceName", tp.getKey()); DirectoryEntry de = tp.getDirectoryEntry(); assertNotNull("Directory entry", de); assertEquals("Cost in directory entry", 50, de.getCost()); assertEquals("Quality in directory entry", 50, de.getQuality()); assertEquals("Description in directory entry", "test place", de.getDescription()); Set<String> keys = tp.getKeys(); assertNotNull("Keys as a set", keys); assertEquals("Size of Keys", 1, keys.size()); Set<String> proxies = tp.getProxies(); assertNotNull("Proxies as a set", proxies); assertEquals("Size of proxies set", 1, proxies.size()); assertTrue("Proxies contains original in set", proxies.contains("TPROXY")); } catch (IOException iox) { fail("Place should have configured with SERVICE_KEY: " + iox.getMessage()); } }