Java Code Examples for java.io.InputStreamReader

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 androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/reporter/.

Source file: PostReporter.java

  35 
vote

/** 
 * Reads an input stream and returns the result as a String.
 * @param in the input stream
 * @return the read String
 * @throws IOException if the stream cannot be read.
 */
public static String read(InputStream in) throws IOException {
  InputStreamReader isReader=new InputStreamReader(in,"UTF-8");
  BufferedReader reader=new BufferedReader(isReader);
  StringBuffer out=new StringBuffer();
  char[] c=new char[4096];
  for (int n; (n=reader.read(c)) != -1; ) {
    out.append(new String(c,0,n));
  }
  reader.close();
  return out.toString();
}
 

Example 2

From project adt-maven-plugin, under directory /src/main/java/com/yelbota/plugins/adt/utils/.

Source file: CleanStream.java

  33 
vote

public void run(){
  try {
    InputStreamReader isr=new InputStreamReader(is);
    BufferedReader br=new BufferedReader(isr);
    String line=null;
    while ((line=br.readLine()) != null) {
      if (log != null) {
        if (type == null) {
          log.info(line);
        }
 else {
          if (type == CleanStreamType.INFO) {
            log.info(line);
          }
 else           if (type == CleanStreamType.DEBUG) {
            log.debug(line);
          }
 else           if (type == CleanStreamType.ERROR) {
            log.error(line);
          }
        }
      }
    }
  }
 catch (  IOException ioe) {
    ioe.printStackTrace();
  }
}
 

Example 3

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/winterwell/jtwitter/.

Source file: InternalUtils.java

  33 
vote

/** 
 * Use a bufferred reader (preferably UTF-8) to extract the contents of the given stream. A convenience method for {@link InternalUtils#toString(Reader)}.
 */
protected static String toString(InputStream inputStream){
  InputStreamReader reader;
  try {
    reader=new InputStreamReader(inputStream,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    reader=new InputStreamReader(inputStream);
  }
  return InternalUtils.toString(reader);
}
 

Example 4

From project addis, under directory /application/src/main/java/org/drugis/addis/util/.

Source file: D80TableGenerator.java

  32 
vote

public static String getTemplate(){
  String html="";
  try {
    InputStreamReader fr=new InputStreamReader(D80TableGenerator.class.getResourceAsStream("TemplateD80Report.html"));
    BufferedReader br=new BufferedReader(fr);
    String line="";
    while ((line=br.readLine()) != null) {
      html+=line;
    }
    br.close();
  }
 catch (  IOException e) {
    throw new RuntimeException("Could not find / load template file.",e);
  }
  return html;
}
 

Example 5

From project ant4eclipse, under directory /org.ant4eclipse.lib.jdt/src/org/ant4eclipse/lib/jdt/internal/model/jre/.

Source file: JavaExecuter.java

  32 
vote

/** 
 * <p> Returns </p>
 * @param inputstream
 * @return
 * @throws IOException
 */
private String[] extractFromInputStream(InputStream inputstream) throws IOException {
  InputStreamReader inputstreamreader=new InputStreamReader(inputstream);
  BufferedReader bufferedreader=new BufferedReader(inputstreamreader);
  List<String> sysOut=new LinkedList<String>();
  String line;
  while ((line=bufferedreader.readLine()) != null) {
    sysOut.add(line);
  }
  return sysOut.toArray(new String[0]);
}
 

Example 6

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

Source file: JavaSystemCaller.java

  32 
vote

/** 
 * Asynchronous read of the input stream. <br /> Will report output as its its displayed.
 * @see java.lang.Thread#run()
 */
@Override public final void run(){
  try {
    final InputStreamReader isr=new InputStreamReader(is);
    final BufferedReader br=new BufferedReader(isr);
    String line;
    while ((line=br.readLine()) != null) {
      System.out.println(type + ">" + line);
      output.append(line).append(System.getProperty("line.separator"));
    }
  }
 catch (  final IOException ioe) {
    ioe.printStackTrace();
  }
}
 

Example 7

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/url/.

Source file: SURT.java

  32 
vote

public static void main(String[] args){
  String line;
  InputStreamReader isr=new InputStreamReader(System.in,Charset.forName("UTF-8"));
  BufferedReader br=new BufferedReader(isr);
  Iterator<String> i=AbstractPeekableIterator.wrapReader(br);
  while (i.hasNext()) {
    line=i.next();
    System.out.println(toSURT(line));
  }
}
 

Example 8

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.

Source file: CommandExecutor.java

  31 
vote

public void run(){
  try {
    InputStreamReader isr=new InputStreamReader(is);
    BufferedReader br=new BufferedReader(isr);
    String line=null;
    while ((line=br.readLine()) != null) {
      if (verbose)       System.out.println(type + ">" + line);
      if (type.equals("OUTPUT"))       reporter.addResultLine(line);
      if (type.equals("ERROR"))       reporter.addErrorLine(line);
    }
  }
 catch (  IOException ioe) {
    ioe.printStackTrace();
  }
}
 

Example 9

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

Source file: EclipseConWizard.java

  31 
vote

/** 
 * Reads and return the content of the given file as a String, given the charset name for this file's content.
 * @param file File we need to read.
 * @param charsetName Name of the charset we should use to read the file's content.
 * @return Content of the file, or the empty String if no such file exists.
 */
private static String readFileContent(File file,String charsetName){
  StringBuffer buffer=new StringBuffer();
  FileInputStream input=null;
  InputStreamReader streamReader=null;
  try {
    input=new FileInputStream(file);
    if (charsetName != null) {
      streamReader=new InputStreamReader(input,charsetName);
    }
 else {
      streamReader=new InputStreamReader(input);
    }
    int size=0;
    final int buffLength=8192;
    char[] buff=new char[buffLength];
    while ((size=streamReader.read(buff)) > 0) {
      buffer.append(buff,0,size);
    }
  }
 catch (  IOException e) {
  }
 finally {
    try {
      if (streamReader != null) {
        streamReader.close();
      }
      if (input != null) {
        input.close();
      }
    }
 catch (    IOException e) {
    }
  }
  return buffer.toString();
}
 

Example 10

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source file: DefaultServlet.java

  31 
vote

/** 
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
 * @param resourceInfo The ResourceInfo object
 * @param writer The writer to write to
 * @param range Range the client wanted to retrieve
 * @exception IOException if an input/output error occurs
 */
protected void copy(CacheEntry cacheEntry,PrintWriter writer,Range range) throws IOException {
  IOException exception=null;
  InputStream resourceInputStream=cacheEntry.resource.streamContent();
  Reader reader;
  if (fileEncoding == null) {
    reader=new InputStreamReader(resourceInputStream);
  }
 else {
    reader=new InputStreamReader(resourceInputStream,fileEncoding);
  }
  exception=copyRange(reader,writer,range.start,range.end);
  reader.close();
  if (exception != null)   throw exception;
}
 

Example 11

From project agraph-java-client, under directory /src/com/franz/openrdf/rio/nquads/.

Source file: NQuadsParser.java

  31 
vote

/** 
 * Implementation of the <tt>parse(InputStream, String)</tt> method defined in the RDFParser interface.
 * @param in The InputStream from which to read the data, must not be <tt>null</tt>. The InputStream is supposed to contain 7-bit US-ASCII characters, as per the N-Triples specification.
 * @param baseURI The URI associated with the data in the InputStream, must not be <tt>null</tt>.
 * @throws IOException If an I/O error occurred while data was read from the InputStream.
 * @throws RDFParseException If the parser has found an unrecoverable parse error.
 * @throws RDFHandlerException If the configured statement handler encountered an unrecoverable error.
 * @throws IllegalArgumentException If the supplied input stream or base URI is <tt>null</tt>.
 */
public synchronized void parse(InputStream in,String baseURI) throws IOException, RDFParseException, RDFHandlerException {
  if (in == null) {
    throw new IllegalArgumentException("Input stream can not be 'null'");
  }
  try {
    parse(new InputStreamReader(in,"US-ASCII"),baseURI);
  }
 catch (  UnsupportedEncodingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 12

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/sensor/external/.

Source file: LineDataReader.java

  31 
vote

public void read(BluetoothSocket socket) throws IOException {
  address=socket.getRemoteDevice().getAddress();
  InputStream stream=socket.getInputStream();
  final Reader finalReader=new InputStreamReader(stream);
  CharStreams.readLines(inputSupplier(finalReader),lineProcessor());
}
 

Example 13

From project airlift, under directory /discovery/src/main/java/io/airlift/discovery/client/.

Source file: HttpDiscoveryAnnouncementClient.java

  31 
vote

private static String getBodyForError(Response response){
  try {
    return CharStreams.toString(new InputStreamReader(response.getInputStream(),Charsets.UTF_8));
  }
 catch (  IOException e) {
    return "(error getting body)";
  }
}
 

Example 14

From project ALP, under directory /workspace/alp-utils/src/main/java/com/lohika/alp/utils/json/validator/.

Source file: ALPJSONValidator.java

  31 
vote

/** 
 * Main function used for validations.
 * @param pathToJSON - where to find file with json to validate
 * @return true if schema valid and false if wrong
 * @throws IOException Signals that an I/O exception has occurred.
 */
public boolean ValidateJSON(String pathToJSON) throws IOException {
  JSONStack.clear();
  ErrorsStack.clear();
  first_try=true;
  Reader in=new InputStreamReader(new FileInputStream(pathToJSON),"UTF-8");
  JsonNode rootObj=JSONMapper.readTree(in);
  LinkedList<String> schemaStack=new LinkedList<String>();
  schemaStack.add(schemaName);
  return validateObject(rootObj,"JSON",schemaStack);
}
 

Example 15

From project android-joedayz, under directory /Proyectos/Archivos/src/net/ivanvega/Archivos/.

Source file: MainActivity.java

  31 
vote

@Override public void onClick(View arg0){
  if (arg0.equals(btnGuardar)) {
    String str=txtTexto.getText().toString();
    FileOutputStream fout=null;
    try {
      fout=openFileOutput("archivoTexto.txt",MODE_WORLD_READABLE);
      OutputStreamWriter ows=new OutputStreamWriter(fout);
      ows.write(str);
      ows.flush();
      ows.close();
    }
 catch (    IOException e) {
      e.printStackTrace();
    }
    Toast.makeText(getBaseContext(),"El archivo se ha almacenado!!!",Toast.LENGTH_SHORT).show();
    txtTexto.setText("");
  }
  if (arg0.equals(btnAbrir)) {
    try {
      FileInputStream fin=openFileInput("archivoTexto.txt");
      InputStreamReader isr=new InputStreamReader(fin);
      char[] inputBuffer=new char[READ_BLOCK_SIZE];
      String str="";
      int charRead;
      while ((charRead=isr.read(inputBuffer)) > 0) {
        String strRead=String.copyValueOf(inputBuffer,0,charRead);
        str+=strRead;
        inputBuffer=new char[READ_BLOCK_SIZE];
      }
      txtTexto.setText(str);
      isr.close();
      Toast.makeText(getBaseContext(),"El archivo ha sido cargado",Toast.LENGTH_SHORT).show();
    }
 catch (    IOException e) {
      e.printStackTrace();
    }
  }
}
 

Example 16

From project Android-RTMP, under directory /android-ffmpeg-prototype/src/com/camundo/media/pipe/.

Source file: FFMPEGAudioInputPipe.java

  31 
vote

@Override public void run(){
  try {
    InputStreamReader isr=new InputStreamReader(inputStream);
    BufferedReader br=new BufferedReader(isr,32);
    String line;
    while ((line=br.readLine()) != null) {
      if (line.indexOf(IO_ERROR) != -1) {
        Log.e(TAG,"IOERRRRRORRRRR -> putting to processStartFailed");
        processStartFailed=true;
      }
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 17

From project android-tether, under directory /src/og/android/tether/.

Source file: TetherApplication.java

  31 
vote

String readLogfile(){
  FileInputStream fis=null;
  InputStreamReader isr=null;
  String data="";
  try {
    File file=new File(this.coretask.DATA_FILE_PATH + "/var/tether.log");
    fis=new FileInputStream(file);
    isr=new InputStreamReader(fis,"utf-8");
    char[] buff=new char[(int)file.length()];
    isr.read(buff);
    data=new String(buff);
  }
 catch (  Exception e) {
    displayToastMessage(getString(R.string.log_activity_nologfile));
  }
 finally {
    try {
      if (isr != null)       isr.close();
      if (fis != null)       fis.close();
    }
 catch (    Exception e) {
    }
  }
  return data;
}
 

Example 18

From project android-xbmcremote, under directory /src/org/xbmc/httpapi/.

Source file: Connection.java

  31 
vote

public byte[] download(String pathToDownload) throws IOException, URISyntaxException {
  try {
    final URL url=new URL(pathToDownload);
    final URLConnection uc=getUrlConnection(url);
    final InputStream is=uc.getInputStream();
    final InputStreamReader isr=new InputStreamReader(is);
    final BufferedReader rd=new BufferedReader(isr,8192);
    final StringBuilder sb=new StringBuilder();
    String line="";
    while ((line=rd.readLine()) != null) {
      sb.append(line);
    }
    rd.close();
    return Base64.decode(sb.toString().replace("<html>","").replace("</html>",""));
  }
 catch (  Exception e) {
    return null;
  }
}
 

Example 19

From project AndroidCommon, under directory /src/com/asksven/android/common/kernelutils/.

Source file: CpuStates.java

  31 
vote

public static ArrayList<State> getTimesInStates(){
  ArrayList<State> states=new ArrayList<State>();
  long totalTime=0;
  try {
    InputStream is=new FileInputStream(TIME_IN_STATE_PATH);
    InputStreamReader ir=new InputStreamReader(is);
    BufferedReader br=new BufferedReader(ir);
    String line;
    while ((line=br.readLine()) != null) {
      String[] nums=line.split(" ");
      State myState=new State(Integer.parseInt(nums[0]),Long.parseLong(nums[1]) * 10);
      totalTime+=myState.m_duration;
      states.add(myState);
    }
    is.close();
  }
 catch (  Exception e) {
    Log.e(TAG,e.getMessage());
    return null;
  }
  long sleepTime=SystemClock.elapsedRealtime() - SystemClock.uptimeMillis();
  states.add(new State(0,sleepTime));
  totalTime+=sleepTime;
  for (int i=0; i < states.size(); i++) {
    states.get(i).setTotal(totalTime);
  }
  return states;
}
 

Example 20

From project Android_1, under directory /GsonJsonWebservice/src/com/novoda/activity/.

Source file: JsonRequest.java

  31 
vote

@Override protected void onResume(){
  super.onResume();
  Toast.makeText(this,"Querying droidcon on Twitter",Toast.LENGTH_SHORT).show();
  Reader reader=new InputStreamReader(retrieveStream(url));
  SearchResponse response=new Gson().fromJson(reader,SearchResponse.class);
  List<String> searches=new ArrayList<String>();
  Iterator<Result> i=response.results.iterator();
  while (i.hasNext()) {
    Result res=(Result)i.next();
    searches.add(res.text);
  }
  ListView v=(ListView)findViewById(R.id.list);
  v.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,searches.toArray(new String[searches.size()])));
}
 

Example 21

From project android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/util/.

Source file: MimeTypeParser.java

  31 
vote

public MimeTypes fromXml(InputStream in) throws XmlPullParserException, IOException {
  XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
  mXpp=factory.newPullParser();
  mXpp.setInput(new InputStreamReader(in));
  return parse();
}
 

Example 22

From project android_packages_apps_Tag, under directory /src/com/android/vcard/.

Source file: VCardParserImpl_V21.java

  31 
vote

public void parse(InputStream is,VCardInterpreter interpreter) throws IOException, VCardException {
  if (is == null) {
    throw new NullPointerException("InputStream must not be null.");
  }
  final InputStreamReader tmpReader=new InputStreamReader(is,mIntermediateCharset);
  mReader=new CustomBufferedReader(tmpReader);
  mInterpreter=(interpreter != null ? interpreter : new EmptyInterpreter());
  final long start=System.currentTimeMillis();
  if (mInterpreter != null) {
    mInterpreter.start();
  }
  parseVCardFile();
  if (mInterpreter != null) {
    mInterpreter.end();
  }
  mTimeTotal+=System.currentTimeMillis() - start;
  if (VCardConfig.showPerformanceLog()) {
    showPerformanceInfo();
  }
}
 

Example 23

From project andstatus, under directory /src/org/andstatus/app/net/.

Source file: ConnectionBasicAuth.java

  31 
vote

/** 
 * Retrieve the input stream from the HTTP connection.
 * @param httpEntity
 * @return String
 */
private String retrieveInputStream(HttpEntity httpEntity){
  int length=(int)httpEntity.getContentLength();
  if (length <= 0) {
    length=1024;
  }
  StringBuffer stringBuffer=new StringBuffer(length);
  try {
    InputStreamReader inputStreamReader=new InputStreamReader(httpEntity.getContent(),HTTP.UTF_8);
    char buffer[]=new char[length];
    int count;
    while ((count=inputStreamReader.read(buffer,0,length - 1)) > 0) {
      stringBuffer.append(buffer,0,count);
    }
  }
 catch (  UnsupportedEncodingException e) {
    Log.e(TAG,e.toString());
  }
catch (  IllegalStateException e) {
    Log.e(TAG,e.toString());
  }
catch (  IOException e) {
    Log.e(TAG,e.toString());
  }
  return stringBuffer.toString();
}
 

Example 24

From project andtweet, under directory /src/com/xorcode/andtweet/net/.

Source file: ConnectionBasicAuth.java

  31 
vote

/** 
 * Retrieve the input stream from the HTTP connection.
 * @param httpEntity
 * @return String
 */
private String retrieveInputStream(HttpEntity httpEntity){
  int length=(int)httpEntity.getContentLength();
  StringBuffer stringBuffer=new StringBuffer(length);
  try {
    InputStreamReader inputStreamReader=new InputStreamReader(httpEntity.getContent(),HTTP.UTF_8);
    char buffer[]=new char[length];
    int count;
    while ((count=inputStreamReader.read(buffer,0,length - 1)) > 0) {
      stringBuffer.append(buffer,0,count);
    }
  }
 catch (  UnsupportedEncodingException e) {
    Log.e(TAG,e.toString());
  }
catch (  IllegalStateException e) {
    Log.e(TAG,e.toString());
  }
catch (  IOException e) {
    Log.e(TAG,e.toString());
  }
  return stringBuffer.toString();
}
 

Example 25

From project annotare2, under directory /app/om/src/main/java/uk/ac/ebi/fg/annotare2/dao/dummy/.

Source file: DummyData.java

  31 
vote

private static Submission createSubmission(User user,SubmissionStatus status,String idfName,String accession,String title) throws IOException {
  Submission submission=new ExperimentSubmission(user,submissionAcl);
  submission.setStatus(status);
  submission.setInvestigation(CharStreams.toString(new InputStreamReader(DummyData.class.getResourceAsStream(idfName),Charsets.UTF_8)));
  submission.setTitle(title);
  submission.setAccession(accession);
  save(submission);
  return submission;
}
 

Example 26

From project AntiCheat, under directory /src/main/java/net/h31ix/anticheat/util/yaml/.

Source file: CommentedConfiguration.java

  31 
vote

@Override public void load(InputStream stream) throws IOException, InvalidConfigurationException {
  InputStreamReader reader=new InputStreamReader(stream);
  StringBuilder builder=new StringBuilder();
  BufferedReader input=new BufferedReader(reader);
  try {
    String line;
    int i=0;
    while ((line=input.readLine()) != null) {
      i++;
      if (line.contains(COMMENT_PREFIX)) {
        comments.put(i,line);
      }
      builder.append(line);
      builder.append('\n');
    }
  }
  finally {
    input.close();
  }
  loadFromString(builder.toString());
}
 

Example 27

From project any23, under directory /nquads/src/main/java/org/apache/any23/io/nquads/.

Source file: NQuadsParser.java

  31 
vote

public synchronized void parse(InputStream is,String baseURI) throws IOException, RDFParseException, RDFHandlerException {
  if (is == null) {
    throw new NullPointerException("inputStream cannot be null.");
  }
  if (baseURI == null) {
    throw new NullPointerException("baseURI cannot be null.");
  }
  this.parse(new InputStreamReader(is,Charset.forName("UTF-8")),baseURI);
}
 

Example 28

From project ARCInputFormat, under directory /src/org/commoncrawl/util/shared/.

Source file: ArcFileReader.java

  31 
vote

/** 
 * construct a reader given a list of ByteBuffers 
 */
private static InputStreamReader readerFromScanBufferList(LinkedList<ByteBuffer> buffers,Charset charset) throws IOException {
  Vector<InputStream> inputStreams=new Vector<InputStream>();
  for (  ByteBuffer buffer : buffers) {
    inputStreams.add(newInputStream(buffer));
  }
  buffers.clear();
  SequenceInputStream seqInputStream=new SequenceInputStream(inputStreams.elements());
  ;
  return new InputStreamReader(seqInputStream,charset);
}
 

Example 29

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

Source file: InterpreterFactory.java

  31 
vote

public static Reader createCommandLineReader(){
  try {
    Class<?> clazz=Class.forName("bsh.CommandLineReader");
    Constructor<?> constructor=clazz.getConstructor(Reader.class);
    constructor.setAccessible(true);
    return (Reader)constructor.newInstance(new InputStreamReader(System.in));
  }
 catch (  Exception err) {
    throw new IllegalStateException("Exception",err);
  }
}
 

Example 30

From project accesointeligente, under directory /src/org/accesointeligente/server/robots/.

Source file: SGS.java

  30 
vote

@Override public RequestStatus checkRequestStatus(Request request) throws Exception {
  if (!loggedIn) {
    login();
  }
  HttpGet get;
  HttpResponse response;
  TagNode document, statusCell;
  String statusLabel;
  try {
    if (request.getRemoteIdentifier() == null || request.getRemoteIdentifier().length() == 0) {
      throw new RobotException("Invalid remote identifier");
    }
    get=new HttpGet(baseUrl + requestViewAction + "&folio="+ request.getRemoteIdentifier());
    get.addHeader("Referer",baseUrl + requestListAction);
    response=client.execute(get);
    document=cleaner.clean(new InputStreamReader(response.getEntity().getContent(),characterEncoding));
    statusCell=document.findElementByAttValue("width","36%",true,true);
    if (statusCell == null) {
      throw new RobotException("Invalid status text cell");
    }
    statusLabel=statusCell.getText().toString().trim();
    if (statusLabel.equals("En Proceso")) {
      return RequestStatus.PENDING;
    }
 else     if (statusLabel.equals("Respondida")) {
      return RequestStatus.RESPONDED;
    }
 else {
      return null;
    }
  }
 catch (  Exception ex) {
    logger.error(ex.getMessage(),ex);
    throw ex;
  }
}
 

Example 31

From project amber, under directory /oauth-2.0/common/src/main/java/org/apache/amber/oauth2/common/utils/.

Source file: OAuthUtils.java

  30 
vote

/** 
 * Get the entity content as a String, using the provided default character set if none is found in the entity. If defaultCharset is null, the default "UTF-8" is used.
 * @param is             input stream to be saved as string
 * @param defaultCharset character set to be applied if none found in the entity
 * @return the entity content as a String
 * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
 * @throws IOException              if an error occurs reading the input stream
 */
public static String toString(final InputStream is,final String defaultCharset) throws IOException {
  if (is == null) {
    throw new IllegalArgumentException("InputStream may not be null");
  }
  String charset=defaultCharset;
  if (charset == null) {
    charset=DEFAULT_CONTENT_CHARSET;
  }
  Reader reader=new InputStreamReader(is,charset);
  StringBuilder sb=new StringBuilder();
  int l;
  try {
    char[] tmp=new char[4096];
    while ((l=reader.read(tmp)) != -1) {
      sb.append(tmp,0,l);
    }
  }
  finally {
    reader.close();
  }
  return sb.toString();
}
 

Example 32

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

Source file: EntityUtils.java

  30 
vote

/** 
 * Get the entity content as a String, using the provided default character set if none is found in the entity. If defaultCharset is null, the default "ISO-8859-1" is used.
 * @param entity must not be null
 * @param defaultCharset character set to be applied if none found in the entity
 * @return the entity content as a String. May be null if{@link HttpEntity#getContent()} is null.
 * @throws ParseException if header elements cannot be parsed
 * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
 * @throws IOException if an error occurs reading the input stream
 */
public static String toString(final HttpEntity entity,final String defaultCharset) throws IOException, ParseException {
  if (entity == null) {
    throw new IllegalArgumentException("HTTP entity may not be null");
  }
  InputStream instream=entity.getContent();
  if (instream == null) {
    return null;
  }
  try {
    if (entity.getContentLength() > Integer.MAX_VALUE) {
      throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
    }
    int i=(int)entity.getContentLength();
    if (i < 0) {
      i=4096;
    }
    String charset=getContentCharSet(entity);
    if (charset == null) {
      charset=defaultCharset;
    }
    if (charset == null) {
      charset=HTTP.DEFAULT_CONTENT_CHARSET;
    }
    Reader reader=new InputStreamReader(instream,charset);
    CharArrayBuffer buffer=new CharArrayBuffer(i);
    char[] tmp=new char[1024];
    int l;
    while ((l=reader.read(tmp)) != -1) {
      buffer.append(tmp,0,l);
    }
    return buffer.toString();
  }
  finally {
    instream.close();
  }
}
 

Example 33

From project and-bible, under directory /AndBackendTest/src/net/bible/android/.

Source file: TestUtil.java

  30 
vote

public static String convertStreamToString(InputStream is) throws IOException {
  if (is != null) {
    StringBuilder sb=new StringBuilder();
    String line;
    try {
      BufferedReader reader=new BufferedReader(new InputStreamReader(is,"UTF-8"));
      while ((line=reader.readLine()) != null) {
        sb.append(line).append("\n");
      }
    }
  finally {
      is.close();
    }
    return sb.toString();
  }
 else {
    return "";
  }
}
 

Example 34

From project android-client_1, under directory /src/com/googlecode/asmack/connection/impl/.

Source file: XmppInputStream.java

  30 
vote

/** 
 * Attach to an underlying input stream, usually done during feature negotiation as some features require stream resets.
 * @param in InputStream The new underlying input stream.
 * @throws XmppTransportException In case of a transport error.
 */
public void attach(InputStream in) throws XmppTransportException {
  Log.d(TAG,"attach");
  this.inputStream=in;
  try {
    parser=XMLUtils.getXMLPullParser();
    parser.setInput(new InputStreamReader(in,"UTF-8"));
  }
 catch (  XmlPullParserException e) {
    Log.e(TAG,"attach failed",e);
    throw new XmppTransportException("Can't initialize pull parser",e);
  }
catch (  UnsupportedEncodingException e) {
    Log.e(TAG,"attach failed",e);
    throw new XmppTransportException("Can't initialize pull parser",e);
  }
  Log.d(TAG,"attached");
}
 

Example 35

From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/provider/.

Source file: GoogleBooksStore.java

  30 
vote

@Override void parseResponse(InputStream in,ResponseParser responseParser) throws IOException {
  final XmlPullParser parser=Xml.newPullParser();
  try {
    parser.setInput(new InputStreamReader(in));
    int type;
    while ((type=parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) {
    }
    if (type != XmlPullParser.START_TAG) {
      throw new InflateException(parser.getPositionDescription() + ": No start tag found!");
    }
    String name=parser.getName();
    if (RESPONSE_TAG_FEED.equals(name)) {
      responseParser.parseResponse(parser);
    }
  }
 catch (  XmlPullParserException e) {
    final IOException ioe=new IOException("Could not parse the response");
    ioe.initCause(e);
    throw ioe;
  }
}
 

Example 36

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

Source file: ArticleViewActivity.java

  30 
vote

private String readFile(String name) throws IOException {
  final char[] buffer=new char[0x1000];
  StringBuilder out=new StringBuilder();
  InputStream is=getResources().getAssets().open(name);
  Reader in=new InputStreamReader(is,"UTF-8");
  int read;
  do {
    read=in.read(buffer,0,buffer.length);
    if (read > 0) {
      out.append(buffer,0,read);
    }
  }
 while (read >= 0);
  return out.toString();
}
 

Example 37

From project android_8, under directory /src/com/defuzeme/network/.

Source file: Connector.java

  30 
vote

private boolean connectSocket(StreamAuthObject object){
  Network._socketAddress=new InetSocketAddress(object.ip,object.port);
  try {
    Network._socket=SocketFactory.getDefault().createSocket();
    Network._socket.connect(Network._socketAddress,Settings._TimeOut);
    Network._socket.setSoTimeout(Settings._TimeOut);
    Network._input=new InputStreamReader(Network._socket.getInputStream());
    Network._output=new DataOutputStream(Network._socket.getOutputStream());
    return true;
  }
 catch (  IOException exception) {
    Log.w(this.getClass().getName(),exception.toString());
  }
  return false;
}
 

Example 38

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

Source file: OAuthMessage.java

  30 
vote

/** 
 * Read all the data from the given stream, and close it.
 * @return null if from is null, or the data from the stream converted to aString
 */
public static String readAll(InputStream from,String encoding) throws IOException {
  if (from == null) {
    return null;
  }
  try {
    StringBuilder into=new StringBuilder();
    Reader r=new InputStreamReader(from,encoding);
    char[] s=new char[512];
    for (int n; 0 < (n=r.read(s)); ) {
      into.append(s,0,n);
    }
    return into.toString();
  }
  finally {
    from.close();
  }
}
 

Example 39

From project apps-for-android, under directory /Photostream/src/com/google/android/photostream/.

Source file: Flickr.java

  30 
vote

/** 
 * Parses a valid Flickr XML response from the specified input stream. When the Flickr response contains the OK tag, the response is sent to the specified response parser.
 * @param in The input stream containing the response sent by Flickr.
 * @param responseParser The parser to use when the response is valid.
 * @throws IOException
 */
private void parseResponse(InputStream in,ResponseParser responseParser) throws IOException {
  final XmlPullParser parser=Xml.newPullParser();
  try {
    parser.setInput(new InputStreamReader(in));
    int type;
    while ((type=parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) {
    }
    if (type != XmlPullParser.START_TAG) {
      throw new InflateException(parser.getPositionDescription() + ": No start tag found!");
    }
    String name=parser.getName();
    if (RESPONSE_TAG_RSP.equals(name)) {
      final String value=parser.getAttributeValue(null,RESPONSE_ATTR_STAT);
      if (!RESPONSE_STATUS_OK.equals(value)) {
        throw new IOException("Wrong status: " + value);
      }
    }
    responseParser.parseResponse(parser);
  }
 catch (  XmlPullParserException e) {
    final IOException ioe=new IOException("Could not parser the response");
    ioe.initCause(e);
    throw ioe;
  }
}
 

Example 40

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

Source file: ResponseReaderImpl.java

  29 
vote

public Response read(InputStream source) throws AclsException {
  BufferedReader br=new BufferedReader(new InputStreamReader(source));
  try {
    return readResponse(createLineScanner(br));
  }
 catch (  IOException ex) {
    throw new AclsCommsException("IO error while reading response",ex);
  }
}
 

Example 41

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

Source file: RowTextFileContentsIterator.java

  29 
vote

public RowTextFileContentsIterator(final String pathname,final RowParser rowParser,final Registrar registrar,final InputStream origStream,final boolean rawContents) throws IOException {
  super(pathname,rowParser,registrar,rawContents);
  final String[] tokenizedPathname=StringUtils.split(pathname,".");
  String suffix=tokenizedPathname[tokenizedPathname.length - 1];
  final InputStream stream=DecompressedStreamFactory.wrapStream(suffix,origStream);
  if (stream != null) {
    in=stream;
    suffix=tokenizedPathname[tokenizedPathname.length - 2];
  }
 else {
    in=origStream;
  }
  binary=suffix.equals("smile") || suffix.equals("thrift");
  if (suffix.equals("smile")) {
    reader=null;
    streamReader=new BufferedSmileReader(registrar,in);
  }
 else   if (suffix.equals("thrift")) {
    reader=null;
    streamReader=new BufferedThriftReader(registrar,in);
  }
 else {
    streamReader=null;
    reader=new BufferedReader(new InputStreamReader(in));
  }
}
 

Example 42

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

Source file: EmailDetailPanel.java

  29 
vote

public EmailDetailPanel(Attachment attachment){
  setSizeFull();
  ((AbstractLayout)getContent()).setMargin(true);
  ((SpacingHandler)getContent()).setSpacing(true);
  addStyleName(Reindeer.PANEL_LIGHT);
  this.attachment=attachment;
  this.i18nManager=ExplorerApp.get().getI18nManager();
  this.taskService=ProcessEngines.getDefaultProcessEngine().getTaskService();
  gridLayout=new GridLayout(2,4);
  gridLayout.setSpacing(true);
  addComponent(gridLayout);
  InputStream contentStream=taskService.getAttachmentContent(attachment.getId());
  JSONObject emailJson=new JSONObject(new JSONTokener(new InputStreamReader(contentStream)));
  String html=emailJson.getString(Constants.EMAIL_HTML_CONTENT);
  String subject=emailJson.getString(Constants.EMAIL_SUBJECT);
  String recipients=emailJson.getString(Constants.EMAIL_RECIPIENT);
  String sentDate=emailJson.getString(Constants.EMAIL_SENT_DATE);
  String receivedDate=emailJson.getString(Constants.EMAIL_RECEIVED_DATE);
  addSimpleRow(Messages.EMAIL_SUBJECT,subject);
  addSimpleRow(Messages.EMAIL_RECIPIENTS,recipients);
  addSimpleRow(Messages.EMAIL_SENT_DATE,sentDate);
  addSimpleRow(Messages.EMAIL_RECEIVED_DATE,receivedDate);
  addHtmlContent(html);
}
 

Example 43

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

Source file: AlfrescoKickstartServiceImpl.java

  29 
vote

public String getWorkflowMetaData(String processDefinitionId,String metadataKey){
  String metadataFile=processDefinitionId;
  if (metadataKey.equals(MetaDataKeys.WORKFLOW_JSON_SOURCE)) {
    metadataFile=metadataFile + ".json";
  }
  Document document=getDocumentFromFolder(WORKFLOW_DEFINITION_FOLDER,metadataFile);
  StringBuilder strb=new StringBuilder();
  BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(document.getContentStream().getStream()));
  try {
    String line=bufferedReader.readLine();
    while (line != null) {
      strb.append(line);
      line=bufferedReader.readLine();
    }
  }
 catch (  Exception e) {
    LOGGER.log(Level.SEVERE,"Could not read metadata '" + metadataKey + "' : "+ e.getMessage());
    e.printStackTrace();
  }
 finally {
    if (bufferedReader != null) {
      try {
        bufferedReader.close();
      }
 catch (      IOException e) {
        e.printStackTrace();
      }
    }
  }
  return strb.toString();
}
 

Example 44

From project AdminCmd, under directory /src/main/java/be/Balor/Manager/Terminal/Commands/.

Source file: UnixTerminalCommand.java

  29 
vote

@Override public void execute(final CommandSender sender){
  try {
    ProcessBuilder pb;
    if (args != null) {
      pb=new ProcessBuilder(execution,args);
    }
 else {
      pb=new ProcessBuilder(execution);
    }
    pb.redirectErrorStream(true);
    pb.directory(workingDir);
    final Process p=pb.start();
    final BufferedReader in=new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line=null;
    while ((line=in.readLine()) != null) {
      sender.sendMessage(line);
    }
  }
 catch (  final Throwable e) {
    sender.sendMessage("CMD ERROR : " + e.getMessage());
    e.printStackTrace();
  }
}
 

Example 45

From project adt-cdt, under directory /com.android.ide.eclipse.adt.cdt/src/com/android/ide/eclipse/adt/cdt/internal/discovery/.

Source file: NDKDiscoveryUpdater.java

  29 
vote

private void checkIncludes(InputStream in){
  try {
    List<String> includes=new ArrayList<String>();
    boolean inIncludes1=false;
    boolean inIncludes2=false;
    BufferedReader reader=new BufferedReader(new InputStreamReader(in));
    String line=reader.readLine();
    while (line != null) {
      if (!inIncludes1) {
        if (line.equals("#include \"...\" search starts here:"))         inIncludes1=true;
      }
 else {
        if (!inIncludes2) {
          if (line.equals("#include <...> search starts here:"))           inIncludes2=true;
 else           includes.add(line.trim());
        }
 else {
          if (line.equals("End of search list.")) {
            pathInfo.setIncludePaths(includes);
          }
 else {
            includes.add(line.trim());
          }
        }
      }
      line=reader.readLine();
    }
  }
 catch (  IOException e) {
  }
}
 

Example 46

From project aether-core, under directory /aether-test-util/src/main/java/org/eclipse/aether/internal/test/util/.

Source file: DependencyGraphParser.java

  29 
vote

/** 
 * Parse multiple graphs in one resource, divided by "---".
 */
public List<DependencyNode> parseMultiple(String resource) throws IOException {
  URL res=this.getClass().getClassLoader().getResource(prefix + resource);
  if (res == null) {
    throw new IOException("Could not find classpath resource " + prefix + resource);
  }
  BufferedReader reader=new BufferedReader(new InputStreamReader(res.openStream(),"UTF-8"));
  List<DependencyNode> ret=new ArrayList<DependencyNode>();
  DependencyNode root=null;
  while ((root=parse(reader)) != null) {
    ret.add(root);
  }
  return ret;
}
 

Example 47

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.

Source file: ViewTools.java

  29 
vote

public String getCommitUrl() throws IOException, CantDoThatException {
  String commitFileName=this.request.getSession().getServletContext().getRealPath("/lastcommit.txt");
  File commitFile=new File(commitFileName);
  try {
    InputStream inputStream=new FileInputStream(commitFileName);
    BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream,Charset.forName("UTF-8")));
    String commitLine=reader.readLine();
    String commitId=commitLine.replace("commit ","");
    inputStream.close();
    return "https://github.com/okohll/agileBase/commit/" + commitId;
  }
 catch (  FileNotFoundException fnfex) {
    logger.error("Commit file " + commitFileName + " not found: "+ fnfex);
    throw new CantDoThatException("Commit log not found");
  }
}
 

Example 48

From project Agot-Java, under directory /src/main/java/got/utility/.

Source file: PointFileReaderWriter.java

  29 
vote

/** 
 * Returns a map of the form String -> Point.
 */
public static Map<String,Point> readOneToOne(final InputStream stream) throws IOException {
  if (stream == null)   return Collections.emptyMap();
  final Map<String,Point> mapping=new HashMap<String,Point>();
  LineNumberReader reader=null;
  try {
    reader=new LineNumberReader(new InputStreamReader(stream));
    String current=reader.readLine();
    while (current != null) {
      if (current.trim().length() != 0) {
        readSingle(current,mapping);
      }
      current=reader.readLine();
    }
  }
  finally {
    if (reader != null)     reader.close();
  }
  return mapping;
}
 

Example 49

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

Source file: HadoopAndPactTestcase.java

  29 
vote

public List<String> readLines(String path) throws IOException {
  List<String> lines=new ArrayList<String>();
  BufferedReader reader=null;
  try {
    reader=new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(path)));
    String line;
    while ((line=reader.readLine()) != null) {
      lines.add(line);
    }
  }
  finally {
    IOUtils.quietClose(reader);
  }
  return lines;
}
 

Example 50

From project Airports, under directory /src/com/nadmm/airports/notams/.

Source file: NotamService.java

  29 
vote

private ArrayList<String> parseNotamsFromHtml(InputStream in) throws IOException {
  ArrayList<String> notams=new ArrayList<String>();
  BufferedReader reader=new BufferedReader(new InputStreamReader(in));
  String line=null;
  boolean inside=false;
  StringBuilder builder=null;
  while ((line=reader.readLine()) != null) {
    if (!inside) {
      if (line.toUpperCase().contains("<PRE>")) {
        builder=new StringBuilder();
        inside=true;
      }
    }
    if (inside) {
      builder.append(line + " ");
      if (line.toUpperCase().contains("</PRE>")) {
        inside=false;
        int start=builder.indexOf("!");
        if (start >= 0) {
          int end=builder.indexOf("SOURCE:");
          String notam=builder.substring(start,end).trim();
          notams.add(notam);
        }
      }
    }
  }
  return notams;
}
 

Example 51

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

Source file: Backup.java

  29 
vote

/** 
 * Load a list of paths from a file
 * @param fs
 * @param inputPath
 * @return
 * @throws IOException
 */
public static List<Path> loadPaths(FileSystem fs,Path inputPath) throws IOException {
  List<Path> retPaths=new ArrayList<Path>();
  BufferedReader reader=null;
  try {
    reader=new BufferedReader(new InputStreamReader(fs.open(inputPath)));
    String line=null;
    while ((line=reader.readLine()) != null) {
      retPaths.add(new Path(line));
    }
  }
 catch (  IOException e) {
    LOG.error("Exception in loadPaths for inputPath: " + inputPath.toString());
  }
 finally {
    checkAndClose(reader);
  }
  return retPaths;
}
 

Example 52

From project aksunai, under directory /src/org/androidnerds/app/aksunai/net/.

Source file: ConnectionThread.java

  29 
vote

public void run(){
  try {
    if (AppConstants.DEBUG)     Log.d(AppConstants.NET_TAG,"Connecting to... " + mServerDetail.mUrl + ":"+ mServerDetail.mPort);
    mSock=new Socket(mServerDetail.mUrl,mServerDetail.mPort);
  }
 catch (  UnknownHostException e) {
    if (AppConstants.DEBUG)     Log.d(AppConstants.NET_TAG,"UnknownHostException caught, terminating connection process");
  }
catch (  IOException e) {
    if (AppConstants.DEBUG)     Log.d(AppConstants.NET_TAG,"IOException caught on socket creation. (Server) " + mServer + ", (Exception) "+ e.toString());
  }
  try {
    mWriter=new BufferedWriter(new OutputStreamWriter(mSock.getOutputStream()));
    mReader=new BufferedReader(new InputStreamReader(mSock.getInputStream()));
  }
 catch (  IOException e) {
    if (AppConstants.DEBUG)     Log.d(AppConstants.NET_TAG,"IOException caught grabbing input/output streams. (Server) " + mServer + ", (Exception) "+ e.toString());
  }
  mServer.init(mServerDetail.mPass,mServerDetail.mNick,mServerDetail.mUser,mServerDetail.mRealName);
  try {
    while (!shouldKill()) {
      String message=mReader.readLine();
      if (AppConstants.DEBUG)       Log.d(AppConstants.NET_TAG,"Received message: " + message);
      mServer.receiveMessage(message);
    }
  }
 catch (  IOException e) {
    if (AppConstants.DEBUG)     Log.d(AppConstants.NET_TAG,"IOException caught handling messages. (Server) " + mServer + ", (Exception) "+ e.toString());
  }
  return;
}
 

Example 53

From project AlarmApp-Android, under directory /src/org/alarmapp/web/http/.

Source file: HttpUtil.java

  29 
vote

private static String read(InputStream stream) throws IOException {
  BufferedReader br=new BufferedReader(new InputStreamReader(stream));
  StringBuilder stringBuilder=new StringBuilder();
  String line=null;
  while ((line=br.readLine()) != null) {
    stringBuilder.append(line);
  }
  return stringBuilder.toString();
}
 

Example 54

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/webservice/.

Source file: AVService.java

  29 
vote

private String convertStreamToString(final InputStream is) throws AVServiceErrorException {
  final StringBuilder sb=new StringBuilder();
  try {
    final BufferedReader reader=new BufferedReader(new InputStreamReader(is,"UTF-8"));
    String line=null;
    while ((line=reader.readLine()) != null) {
      sb.append(line + '\n');
    }
  }
 catch (  final IOException e) {
    throw new AVServiceErrorException(999);
  }
 finally {
    try {
      is.close();
    }
 catch (    final IOException e) {
      throw new AVServiceErrorException(999);
    }
  }
  return sb.toString();
}
 

Example 55

From project alfredo, under directory /alfredo/src/test/java/com/cloudera/alfredo/client/.

Source file: AuthenticatorTestCase.java

  29 
vote

protected void _testAuthentication(Authenticator authenticator,boolean doPost) throws Exception {
  start();
  try {
    URL url=new URL(getBaseURL());
    AuthenticatedURL.Token token=new AuthenticatedURL.Token();
    AuthenticatedURL aUrl=new AuthenticatedURL(authenticator);
    HttpURLConnection conn=aUrl.openConnection(url,token);
    String tokenStr=token.toString();
    if (doPost) {
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
    }
    conn.connect();
    if (doPost) {
      Writer writer=new OutputStreamWriter(conn.getOutputStream());
      writer.write(POST);
      writer.close();
    }
    assertEquals(HttpURLConnection.HTTP_OK,conn.getResponseCode());
    if (doPost) {
      BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String echo=reader.readLine();
      assertEquals(POST,echo);
      assertNull(reader.readLine());
    }
    aUrl=new AuthenticatedURL();
    conn=aUrl.openConnection(url,token);
    conn.connect();
    assertEquals(HttpURLConnection.HTTP_OK,conn.getResponseCode());
    assertEquals(tokenStr,token.toString());
  }
  finally {
    stop();
  }
}
 

Example 56

From project Amantech, under directory /Android/CloudAppStudioAndroid/src/com/cloudappstudio/utility/.

Source file: CloudOAuth.java

  29 
vote

private String readTextFromHttpResponse(HttpResponse response) throws IllegalStateException, IOException {
  BufferedReader reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
  StringBuffer sb=new StringBuffer();
  String line;
  while ((line=reader.readLine()) != null) {
    sb.append(line);
  }
  reader.close();
  return sb.toString();
}
 

Example 57

From project anarchyape, under directory /src/main/java/ape/.

Source file: NetworkDisconnectCommand.java

  29 
vote

/** 
 * This method writes to the Stand output
 */
private boolean writeSTDOut(Process p){
  BufferedReader stdInput=new BufferedReader(new InputStreamReader(p.getInputStream()));
  int count;
  CharBuffer cbuf=CharBuffer.allocate(99999);
  try {
    count=stdInput.read(cbuf);
    if (count != -1)     cbuf.array()[count]='\0';
 else     if (cbuf.array()[0] != '\0')     count=cbuf.array().length;
 else     count=0;
    for (int i=0; i < count; i++)     System.out.print(cbuf.get(i));
  }
 catch (  IOException e) {
    System.err.println("Writing Stdout in NetworkDisconnectCommand catches an exception, Turn on the VERBOSE flag to see the stack trace");
    e.printStackTrace();
    return false;
  }
  try {
    stdInput.close();
  }
 catch (  IOException e) {
    System.err.println("Unable to close the IOStream");
    e.printStackTrace();
    return false;
  }
  return true;
}
 

Example 58

From project andlytics, under directory /src/com/github/andlyticsproject/.

Source file: DeveloperConsole.java

  29 
vote

private String getGwtRpcResponse(String developerPostData,URL aURL) throws IOException, ProtocolException, ConnectException {
  String result;
  HttpsURLConnection connection=(HttpsURLConnection)aURL.openConnection();
  connection.setHostnameVerifier(new AllowAllHostnameVerifier());
  connection.setDoOutput(true);
  connection.setDoInput(true);
  connection.setRequestMethod("POST");
  connection.setConnectTimeout(4000);
  connection.setRequestProperty("Host","play.google.com");
  connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; de; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
  connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  connection.setRequestProperty("Accept-Language","en-us,en;q=0.5");
  connection.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
  connection.setRequestProperty("Keep-Alive","115");
  connection.setRequestProperty("Cookie",cookie);
  connection.setRequestProperty("Connection","keep-alive");
  connection.setRequestProperty("Content-Type","text/x-gwt-rpc; charset=utf-8");
  connection.setRequestProperty("X-GWT-Permutation",getGwtPermutation());
  connection.setRequestProperty("X-GWT-Module-Base","https://play.google.com/apps/publish/gwt-play/");
  connection.setRequestProperty("Referer","https://play.google.com/apps/publish/Home");
  OutputStreamWriter streamToAuthorize=new java.io.OutputStreamWriter(connection.getOutputStream());
  streamToAuthorize.write(developerPostData);
  streamToAuthorize.flush();
  streamToAuthorize.close();
  InputStream resultStream=connection.getInputStream();
  BufferedReader aReader=new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
  StringBuffer aResponse=new StringBuffer();
  String aLine=aReader.readLine();
  while (aLine != null) {
    aResponse.append(aLine + "\n");
    aLine=aReader.readLine();
  }
  resultStream.close();
  result=aResponse.toString();
  return result;
}
 

Example 59

From project android-aac-enc, under directory /src/com/googlecode/mp4parser/srt/.

Source file: SrtParser.java

  29 
vote

public static TextTrackImpl parse(InputStream is) throws IOException {
  LineNumberReader r=new LineNumberReader(new InputStreamReader(is,"UTF-8"));
  TextTrackImpl track=new TextTrackImpl();
  String numberString;
  while ((numberString=r.readLine()) != null) {
    String timeString=r.readLine();
    String lineString="";
    String s;
    while (!((s=r.readLine()) == null || s.trim().equals(""))) {
      lineString+=s + "\n";
    }
    long startTime=parse(timeString.split("-->")[0]);
    long endTime=parse(timeString.split("-->")[1]);
    track.getSubs().add(new TextTrackImpl.Line(startTime,endTime,lineString));
  }
  return track;
}
 

Example 60

From project android-api_1, under directory /android-lib/src/com/catchnotes/api/.

Source file: CatchAPI.java

  29 
vote

private static String istreamToString(InputStream inputStream) throws IOException {
  StringBuilder outputBuilder=new StringBuilder();
  String string;
  if (inputStream != null) {
    BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream,ENCODING));
    while (null != (string=reader.readLine())) {
      outputBuilder.append(string).append('\n');
    }
    reader.close();
  }
  return outputBuilder.toString();
}
 

Example 61

From project android-client, under directory /xwiki-android-rest/src/org/xwiki/android/rest/.

Source file: HttpConnector.java

  29 
vote

/** 
 * Perform HTTP Get method execution and return the response as a String
 * @param Uri URL of XWiki RESTful API
 * @return Response data of the HTTP connection as a String
 */
public String getResponse(String Uri) throws RestConnectionException, RestException {
  initialize();
  BufferedReader in=null;
  HttpGet request=new HttpGet();
  String responseText=new String();
  try {
    requestUri=new URI(Uri);
  }
 catch (  URISyntaxException e) {
    e.printStackTrace();
  }
  setCredentials();
  request.setURI(requestUri);
  Log.d("GET Request URL",Uri);
  try {
    response=client.execute(request);
    Log.d("Response status",response.getStatusLine().toString());
    in=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer sb=new StringBuffer("");
    String line="";
    String NL=System.getProperty("line.separator");
    while ((line=in.readLine()) != null) {
      sb.append(line + NL);
    }
    in.close();
    responseText=sb.toString();
    Log.d("Response","response: " + responseText);
    validate(response.getStatusLine().getStatusCode());
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
    throw new RestConnectionException(e);
  }
  return responseText;
}
 

Example 62

From project android-context, under directory /defunct/shared/.

Source file: PrefsActivity.java

  29 
vote

@Override protected Dialog onCreateDialog(int id){
switch (id) {
case DIALOG_CHANGELOG:
    StringBuilder changelog=new StringBuilder();
  BufferedReader input;
try {
  InputStream is=getResources().openRawResource(R.raw.changelog);
  input=new BufferedReader(new InputStreamReader(is));
  String line;
  while ((line=input.readLine()) != null) {
    changelog.append(line);
    changelog.append("<br/>");
  }
  input.close();
}
 catch (IOException e) {
  e.printStackTrace();
}
return new AlertDialog.Builder(this).setTitle(R.string.changelog_title).setMessage(Html.fromHtml(changelog.toString())).setPositiveButton(R.string.close,null).create();
}
return null;
}
 

Example 63

From project android-share-menu, under directory /src/com/eggie5/.

Source file: post_to_eggie5.java

  29 
vote

private void SendRequest(String data_string){
  try {
    String xmldata="<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<photo><photo>" + data_string + "</photo><caption>via android - "+ new Date().toString()+ "</caption></photo>";
    String hostname="eggie5.com";
    String path="/photos";
    int port=80;
    InetAddress addr=InetAddress.getByName(hostname);
    Socket sock=new Socket(addr,port);
    BufferedWriter wr=new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
    wr.write("POST " + path + " HTTP/1.1\r\n");
    wr.write("Host: eggie5.com\r\n");
    wr.write("Content-Length: " + xmldata.length() + "\r\n");
    wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n");
    wr.write("Accept: text/xml\r\n");
    wr.write("\r\n");
    wr.write(xmldata);
    wr.flush();
    BufferedReader rd=new BufferedReader(new InputStreamReader(sock.getInputStream()));
    String line;
    while ((line=rd.readLine()) != null) {
      Log.v(this.getClass().getName(),line);
    }
  }
 catch (  Exception e) {
    Log.e(this.getClass().getName(),"Upload failed",e);
  }
}
 

Example 64

From project Android-SyncAdapter-JSON-Server-Example, under directory /src/com/puny/android/network/util/.

Source file: DrupalJSONServerNetworkUtilityBase.java

  29 
vote

protected static String convertStreamToString(InputStream is){
  BufferedReader reader=new BufferedReader(new InputStreamReader(is));
  StringBuilder sb=new StringBuilder();
  String line=null;
  try {
    while ((line=reader.readLine()) != null) {
      sb.append(line + "\n");
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
 finally {
    try {
      is.close();
    }
 catch (    IOException e) {
      e.printStackTrace();
    }
  }
  return sb.toString();
}
 

Example 65

From project AndroidLab, under directory /samples/AndroidLdapClient/src/com/unboundid/android/ldap/client/.

Source file: ServerInstance.java

  29 
vote

/** 
 * Retrieves a map of all defined server instances, mapped from the instance ID to the instance object.
 * @param context  The application context.  It must not be {@code null}.
 * @return  A map of all defined server instances.
 * @throws IOException  If a problem occurs while reading information aboutthe defined instances.
 */
public static Map<String,ServerInstance> getInstances(final Context context) throws IOException {
  logEnter(LOG_TAG,"getInstances",context);
  final LinkedHashMap<String,ServerInstance> instances=new LinkedHashMap<String,ServerInstance>(1);
  BufferedReader reader=null;
  try {
    try {
      logDebug(LOG_TAG,"getInstances","Attempting to open file {0} for reading",INSTANCE_FILE_NAME);
      reader=new BufferedReader(new InputStreamReader(context.openFileInput(INSTANCE_FILE_NAME)),1024);
    }
 catch (    final FileNotFoundException fnfe) {
      logException(LOG_TAG,"getInstances",fnfe);
      return logReturn(LOG_TAG,"getInstances",Collections.unmodifiableMap(instances));
    }
    while (true) {
      final String line=reader.readLine();
      logDebug(LOG_TAG,"getInstances","read line {0}",line);
      if (line == null) {
        break;
      }
      if (line.length() == 0) {
        continue;
      }
      final ServerInstance i=decode(line);
      instances.put(i.getID(),i);
    }
    return logReturn(LOG_TAG,"getInstances",Collections.unmodifiableMap(instances));
  }
  finally {
    if (reader != null) {
      logDebug(LOG_TAG,"getInstances","closing reader");
      reader.close();
    }
  }
}
 

Example 66

From project androidtracks, under directory /src/org/sfcta/cycletracks/.

Source file: TripUploader.java

  29 
vote

private static String convertStreamToString(InputStream is){
  BufferedReader reader=new BufferedReader(new InputStreamReader(is));
  StringBuilder sb=new StringBuilder();
  String line=null;
  try {
    while ((line=reader.readLine()) != null) {
      sb.append(line + "\n");
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
 finally {
    try {
      is.close();
    }
 catch (    IOException e) {
      e.printStackTrace();
    }
  }
  return sb.toString();
}
 

Example 67

From project androidZenWriter, under directory /src/com/javaposse/android/zenwriter/.

Source file: AndroidZenWriterActivity.java

  29 
vote

protected void loadFile(String filename){
  FileInputStream fis=null;
  BufferedReader br=null;
  File file=getFileStreamPath(filename);
  StringBuilder content=new StringBuilder();
  if (file.exists()) {
    EditText editText=(EditText)findViewById(R.id.editText1);
    try {
      fis=openFileInput(filename);
      br=new BufferedReader(new InputStreamReader(fis));
      while (br.ready()) {
        content.append(br.readLine()).append("\n");
      }
      editText.setText(content.toString());
      editText.setSelection(content.length());
    }
 catch (    IOException e) {
      Log.e("SaveFile","Failed to save file: ",e);
    }
 finally {
      if (br != null) {
        try {
          br.close();
        }
 catch (        IOException e) {
        }
      }
      if (fis != null) {
        try {
          fis.close();
        }
 catch (        IOException e) {
        }
      }
    }
  }
}
 

Example 68

From project android_build, under directory /tools/signapk/.

Source file: SignApk.java

  29 
vote

/** 
 * Reads the password from stdin and returns it as a string.
 * @param keyFile The file containing the private key.  Used to prompt the user.
 */
private static String readPassword(File keyFile){
  System.out.print("Enter password for " + keyFile + " (password will not be hidden): ");
  System.out.flush();
  BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
  try {
    return stdin.readLine();
  }
 catch (  IOException ex) {
    return null;
  }
}
 

Example 69

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

Source file: CharStreams.java

  29 
vote

/** 
 * Returns a factory that will supply instances of  {@link InputStreamReader}, using the given  {@link InputStream} factory and character set.
 * @param in the factory that will be used to open input streams
 * @param charset the character set used to decode the input stream
 * @return the factory
 */
public static InputSupplier<InputStreamReader> newReaderSupplier(final InputSupplier<? extends InputStream> in,final Charset charset){
  Preconditions.checkNotNull(in);
  Preconditions.checkNotNull(charset);
  return new InputSupplier<InputStreamReader>(){
    public InputStreamReader getInput() throws IOException {
      return new InputStreamReader(in.getInput(),charset);
    }
  }
;
}
 

Example 70

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

Source file: FolderSyncParserTests.java

  29 
vote

public MockFolderSyncParser(String fileName,AbstractSyncAdapter adapter) throws IOException {
  super(null,adapter);
  AssetManager am=mContext.getAssets();
  InputStream is=am.open(fileName);
  if (is != null) {
    mReader=new BufferedReader(new InputStreamReader(is));
  }
  mInUnitTest=true;
}
 

Example 71

From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/.

Source file: InfoFragment.java

  29 
vote

@Override protected Void doInBackground(Void... arg){
  publishProgress(0,Util.getSuperuserVersionInfo(getActivity()));
  publishProgress(1,Util.elitePresent(getActivity(),false,0));
  String suPath=Util.whichSu();
  if (suPath != null) {
    publishProgress(2,Util.getSuVersionInfo());
    String suTools=Util.ensureSuTools(getActivity());
    try {
      Process process=new ProcessBuilder(suTools,"ls","-l",suPath).redirectErrorStream(true).start();
      BufferedReader is=new BufferedReader(new InputStreamReader(process.getInputStream()));
      process.waitFor();
      String inLine=is.readLine();
      String bits[]=inLine.split("\\s+");
      publishProgress(3,bits[0],String.format("%s %s",bits[1],bits[2]),suPath);
    }
 catch (    IOException e) {
      Log.w(TAG,"Binary information could not be read");
    }
catch (    InterruptedException e) {
      e.printStackTrace();
    }
  }
 else {
    publishProgress(2,null);
  }
  SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getActivity());
  publishProgress(4,prefs.getBoolean(Preferences.OUTDATED_NOTIFICATION,true));
  if (mDevice == null)   mDevice=new Device(getActivity());
  mDevice.analyzeSu();
  boolean supported=mDevice.mFileSystem == FileSystem.EXTFS;
  if (!supported) {
    publishProgress(5,null);
  }
 else {
    publishProgress(5,mDevice.isRooted,mDevice.isSuProtected);
  }
  return null;
}
 

Example 72

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: Utils.java

  29 
vote

/** 
 * Converts an InputStream to a String.
 * @param is InputStream to convert
 * @return String version of the InputStream
 */
public static String convertStreamToString(InputStream is){
  String contentOfMyInputStream="";
  try {
    BufferedReader rd=new BufferedReader(new InputStreamReader(is),4096);
    String line;
    StringBuilder sb=new StringBuilder();
    while ((line=rd.readLine()) != null) {
      sb.append(line);
    }
    rd.close();
    contentOfMyInputStream=sb.toString();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return contentOfMyInputStream;
}
 

Example 73

From project ANNIS, under directory /annis-service/src/main/java/annis/administration/.

Source file: AnnisAdminRunner.java

  29 
vote

private void usage(String error){
  Resource resource=new ClassPathResource("annis/administration/usage.txt");
  BufferedReader reader=null;
  try {
    reader=new BufferedReader(new InputStreamReader(resource.getInputStream(),"UTF-8"));
    for (String line=reader.readLine(); line != null; line=reader.readLine()) {
      System.out.println(line);
    }
  }
 catch (  IOException e) {
    log.warn("could not read usage information: " + e.getMessage());
  }
 finally {
    if (reader != null) {
      try {
        reader.close();
      }
 catch (      IOException ex) {
        log.error(null,ex);
      }
    }
  }
  if (error != null) {
    error(error);
  }
}
 

Example 74

From project Apertiurm-Androind-app-devlopment, under directory /ApertiumAndroid/src/org/apertium/android/Internet/.

Source file: InternetManifest.java

  29 
vote

public InternetManifest(String ManifestFile) throws IOException {
  manifestRowList=new ArrayList<ManifestRow>();
  InputStream is=new FileInputStream(AppPreference.TEMP_DIR + "/" + AppPreference.MANIFEST_FILE);
  BufferedReader reader=new BufferedReader(new InputStreamReader(is));
  String input="";
  if (is != null) {
    while ((input=reader.readLine()) != null) {
      String[] Row=input.split("\t");
      if (Row.length > 2) {
        manifestRowList.add(new ManifestRow(Row[0],Row[1],Row[2],Row[3]));
      }
    }
  }
}
 

Example 75

From project apollo, under directory /injector/src/main/java/com/bskyb/cg/environments/server/.

Source file: LogServer.java

  29 
vote

public void run(){
  try {
    InputStream input=clientSocket.getInputStream();
    OutputStream output=clientSocket.getOutputStream();
    BufferedReader is=new BufferedReader(new InputStreamReader(input));
    String line;
    line=is.readLine();
    messageHandler.processMessage(line.getBytes());
    output.close();
    input.close();
  }
 catch (  IOException e) {
    logger.error("Exception in LogServer",e);
  }
}