Java Code Examples for java.io.ByteArrayInputStream

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project addis, under directory /application/src/test/java/org/drugis/addis/entities/.

Source file: DomainManagerTest.java

  20 
vote

@Test @Ignore public void testSaveLoadXml() throws IOException, ClassNotFoundException {
  ExampleData.initDefaultData(d_manager.getDomain());
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  d_manager.saveXMLDomain(bos);
  Domain domain=d_manager.getDomain();
  d_manager.resetDomain();
  ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
  d_manager.loadXMLDomain(bis,2);
  assertDomainEquals(domain,d_manager.getDomain());
}
 

Example 2

From project any23, under directory /core/src/test/java/org/apache/any23/extractor/html/.

Source file: SpanCloserInputStreamTest.java

  19 
vote

private void processInput(String inStr,String expected) throws IOException {
  final ByteArrayInputStream in=new ByteArrayInputStream(inStr.getBytes());
  SpanCloserInputStream scis=new SpanCloserInputStream(in);
  int c;
  final StringBuilder sb=new StringBuilder();
  while ((c=scis.read()) != -1) {
    sb.append((char)c);
  }
  final String out=sb.toString();
  Assert.assertEquals("Unexpected replacement.",expected,out);
}
 

Example 3

From project activejdbc, under directory /javalite-common/src/test/java/org/javalite/common/.

Source file: UtilTest.java

  18 
vote

@Test public void shouldStreamIntoFile() throws IOException {
  String hello="hello world";
  ByteArrayInputStream bin=new ByteArrayInputStream(hello.getBytes());
  Util.saveTo("target/test.txt",bin);
  a(Util.readFile("target/test.txt")).shouldBeEqual(hello);
}
 

Example 4

From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/main/java/alpha/portal/webapp/controller/.

Source file: CardFormController.java

  18 
vote

/** 
 * Gets the payload.
 * @param jspCard the jsp card
 * @param response the response
 * @return the payload
 * @throws IOException Signals that an I/O exception has occurred.
 */
@RequestMapping(method=RequestMethod.POST,params={"payloadGet"}) public String getPayload(final AlphaCard jspCard,final HttpServletResponse response) throws IOException {
  final AlphaCard alphaCard=this.alphaCardManager.get(jspCard.getAlphaCardIdentifier());
  final Payload payload=alphaCard.getPayload();
  if (payload != null) {
    final BufferedInputStream in=new BufferedInputStream(new ByteArrayInputStream(payload.getContent()));
    response.setBufferSize(payload.getContent().length);
    response.setContentType(payload.getMimeType());
    response.setHeader("Content-Disposition","attachment; filename=\"" + payload.getFilename() + "\"");
    response.setContentLength(payload.getContent().length);
    FileCopyUtils.copy(in,response.getOutputStream());
    in.close();
    response.getOutputStream().flush();
    response.getOutputStream().close();
  }
  final AlphaCardIdentifier identifier=alphaCard.getAlphaCardIdentifier();
  return "redirect:/caseform?caseId=" + identifier.getCaseId() + "&activeCardId="+ identifier.getCardId();
}
 

Example 5

From project amplafi-sworddance, under directory /src/test/java/com/sworddance/taskcontrol/.

Source file: TestFutureListenerNotifier.java

  18 
vote

private <F>F serializeDeserialize(F futureResult) throws IOException, ClassNotFoundException {
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  ObjectOutputStream objectOutputStream=new ObjectOutputStream(out);
  objectOutputStream.writeObject(futureResult);
  objectOutputStream.close();
  ByteArrayInputStream in=new ByteArrayInputStream(out.toByteArray());
  ObjectInputStream objectInputStream=new ObjectInputStream(in);
  F f=(F)objectInputStream.readObject();
  assertNotNull(f);
  return f;
}
 

Example 6

From project android-api_1, under directory /android-lib/src/com/android/http/multipart/.

Source file: MultipartEntity.java

  18 
vote

public InputStream getContent() throws IOException, IllegalStateException {
  if (!isRepeatable() && this.contentConsumed) {
    throw new IllegalStateException("Content has been consumed");
  }
  this.contentConsumed=true;
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  Part.sendParts(baos,this.parts,this.multipartBoundary);
  ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
  return bais;
}
 

Example 7

From project android-async-http, under directory /src/com/loopj/android/http/.

Source file: PersistentCookieStore.java

  18 
vote

protected Cookie decodeCookie(String cookieStr){
  byte[] bytes=hexStringToByteArray(cookieStr);
  ByteArrayInputStream is=new ByteArrayInputStream(bytes);
  Cookie cookie=null;
  try {
    ObjectInputStream ois=new ObjectInputStream(is);
    cookie=((SerializableCookie)ois.readObject()).getCookie();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return cookie;
}
 

Example 8

From project android-sdk, under directory /src/test/java/com/mobeelizer/mobile/android/.

Source file: MobeelizerFileImplTest.java

  18 
vote

@Test public void shouldAddFile() throws Exception {
  ByteArrayInputStream stream=new ByteArrayInputStream(new byte[0]);
  when(fileService.addFile(stream)).thenReturn("guid");
  File file=mock(File.class);
  when(file.exists()).thenReturn(true);
  when(file.canRead()).thenReturn(true);
  when(fileService.getFile("guid")).thenReturn(file);
  FileInputStream fileStream=mock(FileInputStream.class);
  PowerMockito.whenNew(FileInputStream.class).withArguments(file).thenReturn(fileStream);
  MobeelizerFileImpl mobeelizerFile=new MobeelizerFileImpl("name",stream);
  assertEquals("guid",mobeelizerFile.getGuid());
  assertEquals("name",mobeelizerFile.getName());
  assertEquals(fileStream,mobeelizerFile.getInputStream());
}
 

Example 9

From project android_external_oauth, under directory /core/src/main/java/net/oauth/signature/.

Source file: RSA_SHA1.java

  18 
vote

private PublicKey getPublicKeyFromPemCert(String certObject) throws GeneralSecurityException {
  CertificateFactory fac=CertificateFactory.getInstance("X509");
  ByteArrayInputStream in=new ByteArrayInputStream(certObject.getBytes());
  X509Certificate cert=(X509Certificate)fac.generateCertificate(in);
  return cert.getPublicKey();
}
 

Example 10

From project archive-commons, under directory /archive-commons/src/test/java/org/archive/format/dns/.

Source file: DNSResponseParserTest.java

  18 
vote

private void verifyResults(String res,String date,String d[][]) throws DNSParseException, IOException {
  ByteArrayInputStream is=new ByteArrayInputStream(res.getBytes("UTF-8"));
  DNSResponse response=new DNSResponse();
  parser.parse(is,response);
  verifyResults(response,date,d);
}
 

Example 11

From project ardverk-commons, under directory /src/test/java/org/ardverk/io/.

Source file: SequenceInputStreamTest.java

  18 
vote

@Test public void read() throws IOException {
  ByteArrayInputStream in1=new ByteArrayInputStream(new byte[]{1});
  ByteArrayInputStream in2=new ByteArrayInputStream(new byte[]{2});
  SequenceInputStream in=new SequenceInputStream(in1,in2);
  TestCase.assertEquals(1,in.read());
  TestCase.assertEquals(2,in.read());
  TestCase.assertEquals(-1,in.read());
  try {
    in.read();
    TestCase.fail("Should have failed!");
  }
 catch (  EOFException expected) {
  }
}
 

Example 12

From project ardverk-dht, under directory /components/store/src/main/java/org/ardverk/dht/storage/.

Source file: Vclock.java

  18 
vote

public static Vclock valueOf(Key key,String value) throws IOException {
  byte[] data=Base64.decodeBase64(value);
  ByteArrayInputStream bais=new ByteArrayInputStream(data);
  InflaterInputStream inflater=new InflaterInputStream(bais);
  try {
    return valueOf(key,inflater);
  }
  finally {
    IoUtils.close(inflater);
  }
}
 

Example 13

From project acceleo-webapp-generator, under directory /plugins/org.eclipse.acceleo.tutorial/src/org/eclipse/acceleo/tutorial/wizard/.

Source file: EclipseConWizard.java

  17 
vote

public static void writeFile(File file,IFolder folder,IProgressMonitor monitor){
  String emtlContent=getFileContent(file);
  IFile newFile=folder.getFile(file.getName());
  if (!newFile.exists()) {
    InputStream contents=new ByteArrayInputStream(emtlContent.getBytes());
    try {
      newFile.create(contents,true,monitor);
    }
 catch (    CoreException e) {
      e.printStackTrace();
    }
  }
}
 

Example 14

From project ACLS-protocol-library, under directory /aclslib/src/test/java/au/edu/uq/cmm/aclslib/message/.

Source file: RequestReaderTest.java

  17 
vote

private InputStream source(String text){
  try {
    return new ByteArrayInputStream(text.getBytes("UTF-8"));
  }
 catch (  UnsupportedEncodingException ex) {
    throw new AssertionError("UTF-8??");
  }
}
 

Example 15

From project action-core, under directory /src/test/java/com/ning/metrics/action/hdfs/data/parser/.

Source file: TestSmileRowSerializer.java

  17 
vote

@Test(groups="fast") public void testToRowsOrderingWithoutRegistrar() throws Exception {
  final Map<String,Object> eventMap=createEventMap();
  final ByteArrayOutputStream out=createSmileEnvelopePayload(eventMap);
  final InputStream stream=new ByteArrayInputStream(out.toByteArray());
  final SmileRowSerializer serializer=new SmileRowSerializer();
  final Rows rows=serializer.toRows(new NullRegistrar(),stream);
  final RowSmile firstRow=(RowSmile)rows.iterator().next();
  final ImmutableMap<String,ValueNode> actual=firstRow.toMap();
  Assert.assertEquals(actual.keySet().size(),eventMap.keySet().size() + 2);
  Assert.assertNotNull(actual.get("eventDate"));
  Assert.assertEquals(actual.get("eventGranularity"),"HOURLY");
  Assert.assertEquals(actual.get("field1"),eventMap.get("field1"));
  Assert.assertEquals(actual.get("field2"),eventMap.get("field2"));
}
 

Example 16

From project activemq-apollo, under directory /apollo-openwire/src/test/scala/org/apache/activemq/apollo/openwire/codec/.

Source file: BooleanStreamTest.java

  17 
vote

protected void assertMarshalBooleans(int count,BooleanValueSet valueSet) throws Exception {
  BooleanStream bs=new BooleanStream();
  for (int i=0; i < count; i++) {
    bs.writeBoolean(valueSet.getBooleanValueFor(i,count));
  }
  ByteArrayOutputStream buffer=new ByteArrayOutputStream();
  DataOutputStream ds=new DataOutputStream(buffer);
  bs.marshal(ds);
  ds.writeInt(endOfStreamMarker);
  ds.close();
  ByteArrayInputStream in=new ByteArrayInputStream(buffer.toByteArray());
  DataInputStream dis=new DataInputStream(in);
  bs=new BooleanStream();
  try {
    bs.unmarshal(dis);
  }
 catch (  Exception e) {
    e.printStackTrace();
    fail("Failed to unmarshal: " + count + " booleans: "+ e);
  }
  for (int i=0; i < count; i++) {
    boolean expected=valueSet.getBooleanValueFor(i,count);
    try {
      boolean actual=bs.readBoolean();
      assertEquals("value of object: " + i + " was: "+ actual,expected,actual);
    }
 catch (    IOException e) {
      e.printStackTrace();
      fail("Failed to parse boolean: " + i + " out of: "+ count+ " due to: "+ e);
    }
  }
  int marker=dis.readInt();
  assertEquals("Marker int when unmarshalling: " + count + " booleans",Integer.toHexString(endOfStreamMarker),Integer.toHexString(marker));
  try {
    byte value=dis.readByte();
    fail("Should have reached the end of the stream");
  }
 catch (  IOException e) {
  }
}
 

Example 17

From project Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/alfresco/.

Source file: AlfrescoKickstartServiceImpl.java

  17 
vote

protected void uploadTaskModel(StringBuilder taskModelsString,String baseFileName){
  Session session=getCmisSession();
  Folder modelFolder=(Folder)session.getObjectByPath(DATA_DICTIONARY_FOLDER);
  String taskModelFileName=baseFileName + "-task-model.xml";
  String taskModelId=UUID.randomUUID().toString();
  String taskModelXML=MessageFormat.format(getTaskModelTemplate(),taskModelId,taskModelsString.toString());
  LOGGER.info("Deploying task model XML:");
  prettyLogXml(taskModelXML);
  ByteArrayInputStream inputStream=new ByteArrayInputStream(taskModelXML.getBytes());
  ContentStream contentStream=new ContentStreamImpl(taskModelFileName,null,"application/xml",inputStream);
  Document taskModelDocument=getDocumentFromFolder(DATA_DICTIONARY_FOLDER,taskModelFileName);
  if (taskModelDocument == null) {
    HashMap<String,Object> properties=new HashMap<String,Object>();
    properties.put("cmis:name",taskModelFileName);
    properties.put("cmis:objectTypeId","D:cm:dictionaryModel");
    properties.put("cm:modelActive",true);
    LOGGER.info("Task model file : " + taskModelFileName);
    modelFolder.createDocument(properties,contentStream,VersioningState.MAJOR);
  }
 else {
    LOGGER.info("Updating content of " + taskModelFileName);
    taskModelDocument.setContentStream(contentStream,true);
  }
}
 

Example 18

From project adbcj, under directory /api/src/test/java/org/adbcj/support/.

Source file: DecoderInputStreamTest.java

  17 
vote

@Test public void boundingTest() throws IOException {
  InputStream in=new ByteArrayInputStream(new byte[]{0,1});
  InputStream din=new DecoderInputStream(in,1);
  din.read();
  try {
    din.read();
    Assert.fail("Should have thrown indicating limit exceeded");
  }
 catch (  IllegalStateException e) {
  }
}
 

Example 19

From project agile, under directory /agile-framework/src/main/java/org/apache/naming/resources/.

Source file: Resource.java

  17 
vote

/** 
 * Content accessor.
 * @return InputStream
 */
public InputStream streamContent() throws IOException {
  if (binaryContent != null) {
    return new ByteArrayInputStream(binaryContent);
  }
  return inputStream;
}
 

Example 20

From project agraph-java-client, under directory /src/com/franz/agraph/http/.

Source file: AGHttpRepoClient.java

  17 
vote

public void uploadJSON(String url,JSONArray rows,Resource... contexts) throws AGHttpException {
  if (rows == null)   return;
  InputStream in;
  try {
    in=new ByteArrayInputStream(rows.toString().getBytes("UTF-8"));
    RequestEntity entity=new InputStreamRequestEntity(in,-1,"application/json");
    upload(url,entity,null,false,null,null,null,contexts);
  }
 catch (  UnsupportedEncodingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 21

From project aio-webos, under directory /component/web/src/test/java/org/exoplatform/webos/services/desktop/test/.

Source file: TestDesktopBackgroundService.java

  17 
vote

@Override protected void setUp() throws Exception {
  userName="testUserName";
  imageName="testImageName";
  mimeType="image/jpeg";
  encoding="UTF-8";
  imgStream=new ByteArrayInputStream(new byte[]{0,1});
  PortalContainer portalContainer=getContainer();
  chromatticManager=(ChromatticManager)portalContainer.getComponentInstanceOfType(ChromatticManager.class);
  desktopBackgroundService=(DesktopBackgroundService)portalContainer.getComponentInstanceOfType(DesktopBackgroundService.class);
  begin();
}
 

Example 22

From project ajah, under directory /ajah-image/src/main/java/com/ajah/image/.

Source file: AutoCrop.java

  17 
vote

/** 
 * Crops an image based on the value of the top left pixel.
 * @param data The image data.
 * @param fuzziness The fuzziness allowed for minor deviations (~5 is recommended).
 * @return The new image data, cropped.
 * @throws IOException If the image could not be read.
 */
public static byte[] autoCrop(final byte[] data,final int fuzziness) throws IOException {
  final BufferedImage image=ImageIO.read(new ByteArrayInputStream(data));
  final BufferedImage cropped=autoCrop(image,fuzziness);
  final ByteArrayOutputStream out=new ByteArrayOutputStream();
  ImageIO.write(cropped,"png",out);
  return out.toByteArray();
}
 

Example 23

From project akubra, under directory /akubra-core/src/test/java/org/akubraproject/impl/.

Source file: TestStreamManager.java

  17 
vote

/** 
 * Managed InputStreams should be tracked when open and forgotten when closed.
 */
@Test(dependsOnGroups={"init"}) public void testManageInputStream() throws Exception {
  InputStream managed=manager.manageInputStream(null,new ByteArrayInputStream(new byte[0]));
  assertEquals(manager.getOpenInputStreamCount(),1);
  managed.close();
  assertEquals(manager.getOpenInputStreamCount(),0);
}
 

Example 24

From project AlbiteREADER, under directory /src/gnu/zip/.

Source file: ZipFile.java

  17 
vote

/** 
 * Decode chars from byte buffer using UTF8 encoding.  This operation is performance-critical since a jar file contains a large number of strings for the name of each file in the archive.  This routine therefore avoids using the expensive utf8Decoder when decoding is straightforward.
 * @param buffer the buffer that contains the encoded characterdata
 * @param pos the index in buffer of the first byte of the encodeddata
 * @param length the length of the encoded data in number ofbytes.
 * @return a String that contains the decoded characters.
 */
private String decodeChars(byte[] buffer,int pos,int length) throws IOException {
  String result;
  int i=length - 1;
  while ((i >= 0) && (buffer[i] <= 0x7f)) {
    i--;
  }
  if (i < 0) {
    result=stringFromSubarray(buffer,0,pos,length);
  }
 else {
    ByteBuffer bufferBuffer=ByteBuffer.wrap(buffer,pos,length);
    ByteArrayInputStream in=new ByteArrayInputStream(buffer);
    AlbiteStreamReader r=new AlbiteStreamReader(in,Encodings.UTF_8);
    char[] characters=r.read(buffer.length);
    result=String.valueOf(characters);
  }
  return result;
}
 

Example 25

From project ALP, under directory /workspace/alp-reporter/src/main/java/com/lohika/alp/mailer/.

Source file: Mailer.java

  17 
vote

public InputStream getInputStream() throws IOException {
  if (html == null) {
    logger.error(new IOException("Null HTML"));
    return new ByteArrayInputStream("".getBytes());
  }
  return new ByteArrayInputStream(html.getBytes("UTF-8"));
}
 

Example 26

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/entity/.

Source file: BufferedHttpEntity.java

  17 
vote

public InputStream getContent() throws IOException {
  if (this.buffer != null) {
    return new ByteArrayInputStream(this.buffer);
  }
 else {
    return wrappedEntity.getContent();
  }
}
 

Example 27

From project android-aac-enc, under directory /src/com/coremedia/iso/boxes/h264/.

Source file: AvcConfigurationBox.java

  17 
vote

public String[] getSPS(){
  ArrayList<String> l=new ArrayList<String>();
  for (  byte[] sequenceParameterSet : sequenceParameterSets) {
    String detail="not parsable";
    try {
      detail=SeqParameterSet.read(new ByteArrayInputStream(sequenceParameterSet)).toString();
    }
 catch (    IOException e) {
    }
    l.add(detail);
  }
  return l.toArray(new String[l.size()]);
}
 

Example 28

From project android-rackspacecloud, under directory /extensions/gae/src/main/java/org/jclouds/gae/.

Source file: GaeHttpCommandExecutorService.java

  17 
vote

@VisibleForTesting protected HttpResponse convert(HTTPResponse gaeResponse){
  HttpResponse response=new HttpResponse();
  response.setStatusCode(gaeResponse.getResponseCode());
  for (  HTTPHeader header : gaeResponse.getHeaders()) {
    response.getHeaders().put(header.getName(),header.getValue());
  }
  if (gaeResponse.getContent() != null) {
    response.setContent(new ByteArrayInputStream(gaeResponse.getContent()));
  }
  return response;
}
 

Example 29

From project AndroidSensorLogger, under directory /src/com/sstp/androidsensorlogger/.

Source file: CameraActivity.java

  17 
vote

public void onPictureTaken(byte[] data,Camera camera){
  Log.d(TAG,"onPictureTaken()");
  int counter=1;
  try {
    Log.d(TAG,"prepare to open fileOutputStream");
    OutputStream fileOutputStream=getContentResolver().openOutputStream(pictureUri);
    Log.d(TAG,"prepare to write data");
    fileOutputStream.write(data);
    Log.d(TAG,"prepare to flush stream");
    fileOutputStream.flush();
    Log.d(TAG,"prepare to close stream");
    fileOutputStream.close();
    saveResult(RESULT_OK);
    Bitmap bm=null;
    ByteArrayInputStream bytes=new ByteArrayInputStream(data);
    BitmapDrawable bmd=new BitmapDrawable(bytes);
    bm=bmd.getBitmap();
    Save_to_SD(bm,"ImageFile" + counter);
  }
 catch (  Exception e) {
    Log.e(TAG,"mPictureCallbackJpeg exception caught: " + e);
  }
  counter++;
}
 

Example 30

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: SOContainer.java

  17 
vote

public static ContainerMessage deserializeContainerMessage(byte[] bytes) throws IOException {
  final ByteArrayInputStream bis=new ByteArrayInputStream(bytes);
  final ObjectInputStream ois=new ObjectInputStream(bis);
  Object obj=null;
  try {
    obj=ois.readObject();
  }
 catch (  final ClassNotFoundException e) {
    Log.i("SOContainer ",Messages.SOContainer_EXCEPTION_CLASS_NOT_FOUND,e);
    printToSystemError("deserializeContainerMessage class not found",e);
    return null;
  }
catch (  final InvalidClassException e) {
    printToSystemError("deserializeContainerMessage invalid class",e);
    return null;
  }
  if (obj instanceof ContainerMessage)   return (ContainerMessage)obj;
  printToSystemError("deserializeContainerMessage invalid container message ",new InvalidObjectException("object " + obj + " not appropriate type"));
  return null;
}
 

Example 31

From project android_external_guava, under directory /src/com/google/common/io/.

Source file: FileBackedOutputStream.java

  17 
vote

private synchronized InputStream openStream() throws IOException {
  if (file != null) {
    return new FileInputStream(file);
  }
 else {
    return new ByteArrayInputStream(memory.getBuffer(),0,memory.getCount());
  }
}
 

Example 32

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/adapter/.

Source file: EmailSyncAdapter.java

  17 
vote

/** 
 * Parses untruncated MIME data, saving away the text parts
 * @param msg the message we're building
 * @param mimeData the MIME data we've received from the server
 * @throws IOException
 */
private void mimeBodyParser(Message msg,String mimeData) throws IOException {
  try {
    ByteArrayInputStream in=new ByteArrayInputStream(mimeData.getBytes());
    MimeMessage mimeMessage=new MimeMessage(in);
    ArrayList<Part> viewables=new ArrayList<Part>();
    ArrayList<Part> attachments=new ArrayList<Part>();
    MimeUtility.collectParts(mimeMessage,viewables,attachments);
    Body tempBody=new Body();
    ConversionUtilities.updateBodyFields(tempBody,msg,viewables);
    msg.mHtml=tempBody.mHtmlContent;
    msg.mText=tempBody.mTextContent;
  }
 catch (  MessagingException e) {
    throw new IOException(e);
  }
}
 

Example 33

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/cache/.

Source file: CacheService.java

  17 
vote

private static final Locale getLocaleForAlbumCache(){
  final byte[] data=sAlbumCache.get(ALBUM_CACHE_LOCALE_INDEX,0);
  if (data != null && data.length > 0) {
    ByteArrayInputStream bis=new ByteArrayInputStream(data);
    DataInputStream dis=new DataInputStream(bis);
    try {
      String country=Utils.readUTF(dis);
      if (country == null)       country="";
      String language=Utils.readUTF(dis);
      if (language == null)       language="";
      String variant=Utils.readUTF(dis);
      if (variant == null)       variant="";
      final Locale locale=new Locale(language,country,variant);
      dis.close();
      bis.close();
      return locale;
    }
 catch (    IOException e) {
      if (DEBUG)       Log.i(TAG,"Error reading locale from cache.");
      return null;
    }
  }
  return null;
}
 

Example 34

From project annotare2, under directory /app/magetab/src/test/java/uk/ac/ebi/fg/annotare2/magetab/base/.

Source file: TsvParserTest.java

  17 
vote

@Test public void emptyTextTest(){
  try {
    (new TsvParser()).parse(new ByteArrayInputStream(" ".getBytes()));
  }
 catch (  IOException e) {
    fail();
  }
}
 

Example 35

From project ant4eclipse, under directory /org.ant4eclipse.lib.core.test/src/org/ant4eclipse/lib/core/util/.

Source file: UtilitiesTest.java

  17 
vote

@Test public void copyStream() throws IOException {
  String text="My Message";
  byte[] input=text.getBytes();
  ByteArrayInputStream instream1=new ByteArrayInputStream(input);
  ByteArrayOutputStream outstream1=new ByteArrayOutputStream();
  try {
    Utilities.copy(instream1,outstream1,new byte[0]);
  }
 catch (  Ant4EclipseException ex) {
    Assert.assertEquals(CoreExceptionCode.PRECONDITION_VIOLATION,ex.getExceptionCode());
  }
 finally {
    Utilities.close(instream1);
    Utilities.close(outstream1);
  }
  ByteArrayInputStream instream2=new ByteArrayInputStream(input);
  ByteArrayOutputStream outstream2=new ByteArrayOutputStream();
  try {
    Utilities.copy(instream2,outstream2,new byte[10]);
  }
  finally {
    Utilities.close(instream2);
    Utilities.close(outstream2);
  }
  Assert.assertEquals(text,new String(outstream2.toByteArray()));
}
 

Example 36

From project apb, under directory /modules/apb-base/src/apb/tasks/.

Source file: JarTask.java

  17 
vote

private void writeMetaInfEntries(JarOutputStream jarOut,Set<String> addedDirs) throws IOException {
  for (  Map.Entry<String,Set<String>> e : services.entrySet()) {
    String fileName="META-INF/services/" + e.getKey();
    StringBuilder buff=new StringBuilder();
    for (    String provider : e.getValue()) {
      buff.append(provider).append("\r\n");
    }
    writeToJar(jarOut,fileName,new ByteArrayInputStream(buff.toString().getBytes()),addedDirs);
  }
}
 

Example 37

From project apps-for-android, under directory /AndroidGlobalTime/src/com/android/globaltime/.

Source file: GlobalTime.java

  17 
vote

private InputStream cache(InputStream is) throws IOException {
  int nbytes=is.available();
  byte[] data=new byte[nbytes];
  int nread=0;
  while (nread < nbytes) {
    nread+=is.read(data,nread,nbytes - nread);
  }
  return new ByteArrayInputStream(data);
}
 

Example 38

From project Archimedes, under directory /br.org.archimedes.batik/src/org/apache/batik/svggen/font/table/.

Source file: GlyfTable.java

  17 
vote

public void init(int numGlyphs,LocaTable loca){
  if (buf == null) {
    return;
  }
  descript=new GlyfDescript[numGlyphs];
  ByteArrayInputStream bais=new ByteArrayInputStream(buf);
  for (int i=0; i < numGlyphs; i++) {
    int len=loca.getOffset((short)(i + 1)) - loca.getOffset(i);
    if (len > 0) {
      bais.reset();
      bais.skip(loca.getOffset(i));
      short numberOfContours=(short)(bais.read() << 8 | bais.read());
      if (numberOfContours >= 0) {
        descript[i]=new GlyfSimpleDescript(this,numberOfContours,bais);
      }
    }
 else {
      descript[i]=null;
    }
  }
  for (int i=0; i < numGlyphs; i++) {
    int len=loca.getOffset((short)(i + 1)) - loca.getOffset(i);
    if (len > 0) {
      bais.reset();
      bais.skip(loca.getOffset(i));
      short numberOfContours=(short)(bais.read() << 8 | bais.read());
      if (numberOfContours < 0) {
        descript[i]=new GlyfCompositeDescript(this,bais);
      }
    }
  }
  buf=null;
}
 

Example 39

From project Arecibo, under directory /util/src/main/java/com/ning/arecibo/util/timeline/samples/.

Source file: SampleCoderImpl.java

  17 
vote

@Override public List<ScalarSample> decompressSamples(final byte[] sampleBytes) throws IOException {
  final List<ScalarSample> returnedSamples=new ArrayList<ScalarSample>();
  final ByteArrayInputStream byteStream=new ByteArrayInputStream(sampleBytes);
  final DataInputStream inputStream=new DataInputStream(byteStream);
  while (true) {
    final int opcodeByte;
    opcodeByte=inputStream.read();
    if (opcodeByte == -1) {
      break;
    }
    final SampleOpcode opcode=SampleOpcode.getOpcodeFromIndex(opcodeByte);
switch (opcode) {
case REPEAT_BYTE:
case REPEAT_SHORT:
      final int repeatCount=opcode == SampleOpcode.REPEAT_BYTE ? inputStream.readUnsignedByte() : inputStream.readUnsignedShort();
    final SampleOpcode repeatedOpcode=SampleOpcode.getOpcodeFromIndex(inputStream.read());
  final Object value=decodeScalarValue(inputStream,repeatedOpcode);
for (int i=0; i < repeatCount; i++) {
  returnedSamples.add(new ScalarSample(repeatedOpcode,value));
}
break;
default :
returnedSamples.add(new ScalarSample(opcode,decodeScalarValue(inputStream,opcode)));
break;
}
}
return returnedSamples;
}
 

Example 40

From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/ui/content/file/.

Source file: FileAttachmentEditorComponent.java

  16 
vote

public Attachment getAttachment() throws InvalidValueException {
  form.commit();
  if (!fileUploaded) {
    InvalidValueException ive=new InvalidValueException(i18nManager.getMessage(Messages.RELATED_CONTENT_TYPE_FILE_REQUIRED));
    form.setComponentError(ive);
    throw ive;
  }
  if (attachment != null) {
    applyValuesToAttachment();
  }
 else {
    attachment=taskService.createAttachment(mimeType,taskId,processInstanceId,getAttachmentName(),getAttachmentDescription(),new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
  }
  return attachment;
}
 

Example 41

From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/api/process/.

Source file: ProcessDefinitionFormGet.java

  16 
vote

/** 
 * Returns a task form
 * @param req The activiti webscript request
 * @param res The webscript response
 */
@Override protected void executeStreamingWebScript(ActivitiRequest req,WebScriptResponse res){
  String processDefinitionId=req.getMandatoryPathParameter("processDefinitionId");
  Object form=getFormService().getRenderedStartForm(processDefinitionId);
  InputStream is=null;
  if (form != null && form instanceof String) {
    is=new ByteArrayInputStream(((String)form).getBytes());
  }
 else   if (form != null && form instanceof InputStream) {
    is=(InputStream)form;
  }
  if (is != null) {
    String mimeType=getMimeType(is);
    try {
      streamResponse(res,is,new Date(0),null,true,processDefinitionId,mimeType);
    }
 catch (    IOException e) {
      throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR,"The form for process definition '" + processDefinitionId + "' failed to render.");
    }
 finally {
      IoUtil.closeSilently(is);
    }
  }
 else   if (form != null) {
    throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR,"The form for process definition '" + processDefinitionId + "' cannot be rendered using the rest api.");
  }
 else {
    throw new WebScriptException(Status.STATUS_NOT_FOUND,"There is no form for process definition '" + processDefinitionId + "'.");
  }
}
 

Example 42

From project aether-core, under directory /aether-connector-wagon/src/main/java/org/eclipse/aether/connector/wagon/.

Source file: WagonRepositoryConnector.java

  16 
vote

private void uploadChecksum(Wagon wagon,File file,String path,String algo,Object checksum){
  try {
    if (checksum instanceof Exception) {
      throw (Exception)checksum;
    }
    String ext=checksumAlgos.get(algo);
    String dst=path + ext;
    String sum=String.valueOf(checksum);
    if (wagon instanceof StreamingWagon) {
      byte[] data=sum.getBytes("UTF-8");
      ((StreamingWagon)wagon).putFromStream(new ByteArrayInputStream(data),dst,data.length,-1);
    }
 else {
      File tmpFile=File.createTempFile("wagon" + UUID.randomUUID().toString().replace("-",""),ext);
      try {
        fileProcessor.write(tmpFile,sum);
        wagon.put(tmpFile,dst);
      }
  finally {
        tmpFile.delete();
      }
    }
  }
 catch (  Exception e) {
    String msg="Failed to upload " + algo + " checksum for "+ file+ ": "+ e.getMessage();
    if (logger.isDebugEnabled()) {
      logger.warn(msg,e);
    }
 else {
      logger.warn(msg);
    }
  }
}
 

Example 43

From project airlift, under directory /jaxrs/src/test/java/io/airlift/jaxrs/.

Source file: TestJsonMapper.java

  16 
vote

@Test public void testEOFExceptionTeturnsWebAppException() throws IOException {
  try {
    JsonMapper jsonMapper=new JsonMapper(new ObjectMapper(),null);
    InputStream is=new ByteArrayInputStream("foo".getBytes());
    jsonMapper.readFrom(Object.class,Object.class,null,null,null,new InputStream(){
      @Override public int read() throws IOException {
        throw new EOFException("forced EOF Exception");
      }
      @Override public int read(      byte[] b) throws IOException {
        throw new EOFException("forced EOF Exception");
      }
      @Override public int read(      byte[] b,      int off,      int len) throws IOException {
        throw new EOFException("forced EOF Exception");
      }
    }
);
    Assert.fail("Should have thrown a WebApplicationException");
  }
 catch (  WebApplicationException e) {
    Assert.assertEquals(e.getResponse().getStatus(),Status.BAD_REQUEST.getStatusCode());
    Assert.assertTrue(((String)e.getResponse().getEntity()).startsWith("Invalid json for Java type"));
  }
}
 

Example 44

From project androidquery, under directory /src/com/androidquery/callback/.

Source file: AbstractAjaxCallback.java

  16 
vote

private static void writeObject(DataOutputStream dos,String name,Object obj) throws IOException {
  if (obj == null)   return;
  if (obj instanceof File) {
    File file=(File)obj;
    writeData(dos,name,file.getName(),new FileInputStream(file));
  }
 else   if (obj instanceof byte[]) {
    writeData(dos,name,name,new ByteArrayInputStream((byte[])obj));
  }
 else   if (obj instanceof InputStream) {
    writeData(dos,name,name,(InputStream)obj);
  }
 else {
    writeField(dos,name,obj.toString());
  }
}
 

Example 45

From project android_packages_apps_Tag, under directory /src/com/android/apps/tag/record/.

Source file: VCardRecord.java

  16 
vote

private ArrayList<VCardEntry> getVCardEntries() throws IOException, VCardException {
  final ArrayList<VCardEntry> entries=Lists.newArrayList();
  final int type=VCardConfig.VCARD_TYPE_UNKNOWN;
  final VCardEntryConstructor constructor=new VCardEntryConstructor(type);
  constructor.addEntryHandler(new VCardEntryHandler(){
    @Override public void onStart(){
    }
    @Override public void onEnd(){
    }
    @Override public void onEntryCreated(    VCardEntry entry){
      entries.add(entry);
    }
  }
);
  VCardParser parser=new VCardParser_V21(type);
  try {
    parser.parse(new ByteArrayInputStream(mVCard),constructor);
  }
 catch (  VCardVersionException e) {
    try {
      parser=new VCardParser_V30(type);
      parser.parse(new ByteArrayInputStream(mVCard),constructor);
    }
  finally {
    }
  }
  return entries;
}
 

Example 46

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/resultview/.

Source file: VisualizerPanel.java

  16 
vote

/** 
 * This Constructor should be used for  {@link ComponentVisualizerPlugin}Visualizer.
 */
public VisualizerPanel(final ResolverEntry entry,SDocument result,List<SToken> token,Set<String> visibleTokenAnnos,Map<SNode,Long> markedAndCovered,@Deprecated Map<String,String> markedAndCoveredMap,@Deprecated Map<String,String> markedExactMap,STextualDS text,String htmlID,String resultID,SingleResultPanel parent,String segmentationName,PluginSystem ps,boolean showTextID) throws IOException {
  super(new ByteArrayInputStream(htmlTemplate.replace(":id",htmlID).getBytes("UTF-8")));
  visPlugin=ps.getVisualizer(entry.getVisType());
  this.ps=ps;
  this.entry=entry;
  this.markersExact=markedExactMap;
  this.markersCovered=markedAndCoveredMap;
  this.result=result;
  this.token=token;
  this.visibleTokenAnnos=visibleTokenAnnos;
  this.markedAndCovered=markedAndCovered;
  this.text=text;
  this.segmentationName=segmentationName;
  this.htmlID=htmlID;
  this.resultID=resultID;
  this.showTextID=showTextID;
  this.addStyleName(ChameleonTheme.PANEL_BORDERLESS);
  this.setWidth("100%");
}
 

Example 47

From project aim3-tu-berlin, under directory /seminar/exercises/datamining/core/src/test/java/de/tuberlin/dima/aim/exercises/one/.

Source file: PrimeNumbersWritableTest.java

  15 
vote

@Test public void writeAndRead() throws IOException {
  PrimeNumbersWritable original=new PrimeNumbersWritable(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97);
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  original.write(new DataOutputStream(out));
  PrimeNumbersWritable clone=new PrimeNumbersWritable();
  clone.readFields(new DataInputStream(new ByteArrayInputStream(out.toByteArray())));
  assertEquals(original,clone);
}
 

Example 48

From project akela, under directory /src/main/java/com/mozilla/hadoop/hbase/mapreduce/.

Source file: MultiScanTableMapReduceUtil.java

  15 
vote

/** 
 * Converts base64 scans string back into a Scan array
 * @param base64
 * @return
 * @throws IOException
 */
public static Scan[] convertStringToScanArray(final String base64) throws IOException {
  final DataInputStream dis=new DataInputStream(new ByteArrayInputStream(Base64.decode(base64)));
  ArrayWritable aw=new ArrayWritable(Scan.class);
  aw.readFields(dis);
  Writable[] writables=aw.get();
  Scan[] scans=new Scan[writables.length];
  for (int i=0; i < writables.length; i++) {
    scans[i]=(Scan)writables[i];
  }
  return scans;
}
 

Example 49

From project alljoyn_java, under directory /test/org/alljoyn/bus/.

Source file: AuthListenerTest.java

  15 
vote

public boolean requested(String mechanism,String authPeer,int count,String userName,AuthRequest[] requests){
  for (  AuthRequest request : requests) {
    if (request instanceof CertificateRequest) {
      ((CertificateRequest)request).setCertificateChain(certificate);
    }
 else     if (request instanceof PrivateKeyRequest) {
      if (privateKey != null) {
        ((PrivateKeyRequest)request).setPrivateKey(privateKey);
      }
    }
 else     if (request instanceof PasswordRequest) {
      if (password != null) {
        ((PasswordRequest)request).setPassword(password);
      }
    }
 else     if (request instanceof VerifyRequest) {
      String subject=null;
      try {
        String chain=((VerifyRequest)request).getCertificateChain();
        BufferedInputStream in=new BufferedInputStream(new ByteArrayInputStream(chain.getBytes()));
        List<X509Certificate> list=new ArrayList<X509Certificate>();
        while (in.available() > 0) {
          list.add((X509Certificate)factory.generateCertificate(in));
        }
        subject=list.get(0).getSubjectX500Principal().getName(X500Principal.CANONICAL).split(",")[0].split("=")[1];
        CertPath path=factory.generateCertPath(list);
        PKIXParameters params=new PKIXParameters(trustAnchors);
        params.setRevocationEnabled(false);
        validator.validate(path,params);
        verified=subject;
      }
 catch (      Exception ex) {
        rejected=subject;
        return false;
      }
    }
  }
  return true;
}
 

Example 50

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/bean/.

Source file: PureJavaReflectionProvider.java

  15 
vote

private Object instantiateUsingSerialization(Class type){
  try {
    byte[] data;
    if (serializedDataCache.containsKey(type)) {
      data=(byte[])serializedDataCache.get(type);
    }
 else {
      ByteArrayOutputStream bytes=new ByteArrayOutputStream();
      DataOutputStream stream=new DataOutputStream(bytes);
      stream.writeShort(ObjectStreamConstants.STREAM_MAGIC);
      stream.writeShort(ObjectStreamConstants.STREAM_VERSION);
      stream.writeByte(ObjectStreamConstants.TC_OBJECT);
      stream.writeByte(ObjectStreamConstants.TC_CLASSDESC);
      stream.writeUTF(type.getName());
      stream.writeLong(ObjectStreamClass.lookup(type).getSerialVersionUID());
      stream.writeByte(2);
      stream.writeShort(0);
      stream.writeByte(ObjectStreamConstants.TC_ENDBLOCKDATA);
      stream.writeByte(ObjectStreamConstants.TC_NULL);
      data=bytes.toByteArray();
      serializedDataCache.put(type,data);
    }
    ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(data));
    return in.readObject();
  }
 catch (  IOException e) {
    throw new ObjectAccessException("Cannot create " + type.getName() + " by JDK serialization",e);
  }
catch (  ClassNotFoundException e) {
    throw new ObjectAccessException("Cannot find class " + e.getMessage());
  }
}
 

Example 51

From project and-bible, under directory /jsword-tweaks/src/main/java/jsword/org/crosswire/jsword/book/sword/.

Source file: ConfigEntryTable.java

  15 
vote

/** 
 * Load the conf from a buffer. This is used to load conf entries from the mods.d.tar.gz file.
 * @param buffer the buffer to load
 * @throws IOException
 */
public void load(byte[] buffer) throws IOException {
  BufferedReader in=null;
  try {
    in=new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buffer),ENCODING_UTF8),buffer.length);
    loadInitials(in);
    loadContents(in);
    in.close();
    in=null;
    if (getValue(ConfigEntryType.ENCODING).equals(ENCODING_LATIN1)) {
      supported=true;
      bookType=null;
      questionable=false;
      readahead=null;
      table.clear();
      extra.clear();
      in=new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buffer),ENCODING_LATIN1),buffer.length);
      loadInitials(in);
      loadContents(in);
      in.close();
      in=null;
    }
    adjustDataPath();
    adjustLanguage();
    adjustBookType();
    adjustName();
    validate();
  }
  finally {
    if (in != null) {
      in.close();
    }
  }
}
 

Example 52

From project android_5, under directory /src/aarddict/.

Source file: Volume.java

  15 
vote

static String decompressBz2(byte[] bytes) throws IOException {
  BZip2CompressorInputStream in=new BZip2CompressorInputStream(new ByteArrayInputStream(bytes));
  int n=0;
  ByteArrayOutputStream out=new ByteArrayOutputStream(bytes.length * 5);
  byte[] buf=new byte[1024];
  try {
    while (-1 != (n=in.read(buf))) {
      out.write(buf,0,n);
    }
  }
  finally {
    in.close();
    out.close();
  }
  return utf8(out.toByteArray());
}
 

Example 53

From project android_external_libphonenumber, under directory /java/test/com/android/i18n/phonenumbers/geocoding/.

Source file: AreaCodeMapTest.java

  15 
vote

/** 
 * Creates a new area code map serializing the provided area code map to a stream and then reading this stream. The resulting area code map is expected to be strictly equal to the provided one from which it was generated.
 */
private static AreaCodeMap createNewAreaCodeMap(AreaCodeMap areaCodeMap) throws IOException {
  ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
  ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
  areaCodeMap.writeExternal(objectOutputStream);
  objectOutputStream.flush();
  AreaCodeMap newAreaCodeMap=new AreaCodeMap();
  newAreaCodeMap.readExternal(new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())));
  return newAreaCodeMap;
}
 

Example 54

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/app/.

Source file: MoviePlayer.java

  15 
vote

public Integer getBookmark(Uri uri){
  try {
    BlobCache cache=CacheManager.getCache(mContext,BOOKMARK_CACHE_FILE,BOOKMARK_CACHE_MAX_ENTRIES,BOOKMARK_CACHE_MAX_BYTES,BOOKMARK_CACHE_VERSION);
    byte[] data=cache.lookup(uri.hashCode());
    if (data == null)     return null;
    DataInputStream dis=new DataInputStream(new ByteArrayInputStream(data));
    String uriString=dis.readUTF(dis);
    int bookmark=dis.readInt();
    int duration=dis.readInt();
    if (!uriString.equals(uri.toString())) {
      return null;
    }
    if ((bookmark < HALF_MINUTE) || (duration < TWO_MINUTES) || (bookmark > (duration - HALF_MINUTE))) {
      return null;
    }
    return Integer.valueOf(bookmark);
  }
 catch (  Throwable t) {
    Log.w(TAG,"getBookmark failed",t);
  }
  return null;
}
 

Example 55

From project appengine-java-mapreduce, under directory /java/src/com/google/appengine/tools/mapreduce/impl/util/.

Source file: SerializationUtil.java

  15 
vote

public static Object deserializeFromByteArray(byte[] bytes){
  ObjectInputStream in;
  try {
    in=new ObjectInputStream(new ByteArrayInputStream(bytes));
  }
 catch (  IOException e) {
    throw new RuntimeException("Deserialization error",e);
  }
  try {
    return in.readObject();
  }
 catch (  IOException e) {
    throw new RuntimeException("Deserialization error",e);
  }
catch (  ClassNotFoundException e) {
    throw new RuntimeException("Deserialization error",e);
  }
 finally {
    try {
      in.close();
    }
 catch (    IOException e) {
      throw new RuntimeException("Deserialization error",e);
    }
  }
}
 

Example 56

From project Application-Builder, under directory /src/main/java/org/silverpeas/xml/.

Source file: ClasspathEntityResolver.java

  15 
vote

private InputSource resolveInClasspath(String publicId,String systemId) throws SAXException, IOException {
  InputSource result=resolveInClasspath(publicId);
  if (result == null) {
    result=resolveInClasspath(systemId);
  }
  if (result == null) {
    result=new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes("UTF-8")));
  }
  return result;
}