Java Code Examples for java.io.Reader

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 AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/sensor/external/.

Source file: LineDataReader.java

  34 
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 2

From project Aardvark, under directory /aardvark-core/src/main/java/gw/vark/.

Source file: Aardvark.java

  32 
vote

public static String getVersion(){
  URL versionResource=Aardvark.class.getResource("/gw/vark/version.txt");
  try {
    Reader reader=StreamUtil.getInputStreamReader(versionResource.openStream());
    String version=StreamUtil.getContent(reader).trim();
    return "Aardvark version " + version;
  }
 catch (  IOException e) {
    throw GosuExceptionUtil.forceThrow(e);
  }
}
 

Example 3

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

Source file: Convert.java

  32 
vote

private static String clobToString(Clob clob){
  try {
    Reader r=clob.getCharacterStream();
    StringWriter sw=new StringWriter();
    copyStream(r,sw);
    return sw.toString();
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 4

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

Source file: DefaultServlet.java

  32 
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 5

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

Source file: ConfigurationLoader.java

  32 
vote

/** 
 * Loads properties from the given file
 * @param path file path
 * @return properties
 * @throws IOException errors
 */
public Map<String,String> loadPropertiesFrom(String path) throws IOException {
  Reader reader=new FileReader(new File(path));
  Properties properties=new Properties();
  try {
    properties.load(reader);
  }
  finally {
    reader.close();
  }
  return toMap(properties);
}
 

Example 6

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

Source file: ALPJSONValidator.java

  32 
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 7

From project anadix, under directory /anadix-tests/src/test/java/org/anadix/factories/.

Source file: ClassPathSourceTest.java

  32 
vote

@Test(dependsOnGroups="constructor") public void testGetReader() throws Exception {
  Source s=SourceFactory.newClassPathSource(resourcePath,false);
  Reader r=s.getReader();
  assertNotNull(r);
  String content=readReader(r);
  assertNotNull(content);
  assertEquals(content,sourceText);
}
 

Example 8

From project androidpn, under directory /androidpn-server-bin-tomcat/src/org/jivesoftware/openfire/net/.

Source file: MXParser.java

  32 
vote

public void resetInput(){
  Reader oldReader=reader;
  String oldEncoding=inputEncoding;
  reset();
  reader=oldReader;
  inputEncoding=oldEncoding;
}
 

Example 9

From project AndroidSensorLogger, under directory /libraries/opencsv-2.3-src-with-libs/opencsv-2.3/src/au/com/bytecode/opencsv/.

Source file: ResultSetHelperService.java

  32 
vote

private static String read(Clob c) throws SQLException, IOException {
  StringBuilder sb=new StringBuilder((int)c.length());
  Reader r=c.getCharacterStream();
  char[] cbuf=new char[CLOBBUFFERSIZE];
  int n;
  while ((n=r.read(cbuf,0,cbuf.length)) != -1) {
    sb.append(cbuf,0,n);
  }
  return sb.toString();
}
 

Example 10

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

Source file: JsonRequest.java

  32 
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 11

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

Source file: TemplateBasedBuilder.java

  32 
vote

public void writeInDirectory(String _targetDirectory) throws IOException, Exception {
  Reader srcText=new StringReader(getTargetContents());
  FileWriter out=new FileWriter(new File(_targetDirectory,targetFileName));
  int charsRead;
  while ((charsRead=srcText.read(data,0,BUFSIZE)) > 0) {
    out.write(data,0,charsRead);
  }
  out.close();
  srcText.close();
}
 

Example 12

From project archive-commons, under directory /ia-tools/src/main/java/org/archive/hadoop/io/.

Source file: MergeClusterRangesInputFormat.java

  32 
vote

public static void setSplitPath(Configuration conf,String path) throws IOException {
  conf.set(SPLIT_CONFIG_KEY,path);
  LOG.warning(String.format("Setting Split path: %s",path));
  SplitFile splitFile=new SplitFile();
  Reader r=getSplitReader(conf);
  splitFile.read(r);
  for (int i=0; i < splitFile.size(); i++) {
    PartitionName.setPartitionOutputName(conf,i,splitFile.getName(i));
  }
  r.close();
}
 

Example 13

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

Source file: InterpreterFactory.java

  32 
vote

public static Interpreter create(Class<?> clazz,String name){
  Reader reader=getValueAsStream(clazz,name);
  try {
    return create(reader);
  }
  finally {
    IoUtils.close(reader);
  }
}
 

Example 14

From project beam-meris-icol, under directory /src/main/java/org/esa/beam/meris/icol/.

Source file: CoeffW.java

  32 
vote

public CoeffW(File auxdataTargetDir,boolean reshapedConvolution,int correctionMode) throws IOException {
  this.correctionMode=correctionMode;
  this.auxdataTargetDir=auxdataTargetDir;
  File wFile=new File(auxdataTargetDir,FILENAME);
  Reader reader=new FileReader(wFile);
  loadCoefficient(reader);
}
 

Example 15

From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/server/.

Source file: Bf3ServerCall.java

  32 
vote

@Override public void onSimpleHttpCallSuccess(HttpResponse response){
  Reader reader=getJSONReader(response);
  JsonParser parser=new JsonParser();
  JsonObject jsonObject=parser.parse(reader).getAsJsonObject();
  callback.onBf3CallSuccess(overviewStatsObject(jsonObject));
}
 

Example 16

From project C-Cat, under directory /wordnet/src/main/java/gov/llnl/ontology/wordnet/.

Source file: WordNetCorpusReader.java

  32 
vote

/** 
 * Returns a  {@link BufferedReader} for the exact file name requested.
 */
private BufferedReader getReaderFromFullFilename(String filename) throws IOException {
  Reader reader;
  if (readFromJar)   reader=new InputStreamReader(StreamUtil.fromJar(this.getClass(),filename));
 else   reader=new FileReader(filename);
  return new BufferedReader(reader);
}
 

Example 17

From project Cafe, under directory /webapp/src/org/openqa/selenium/browserlaunchers/.

Source file: DoNotUseProxyPac.java

  32 
vote

private void appendSuperPac(Writer writer) throws IOException {
  if (deriveFrom == null) {
    return;
  }
  Reader reader=new InputStreamReader((InputStream)deriveFrom.toURL().getContent());
  StringBuilder content=new StringBuilder();
  for (int i=reader.read(); i != -1; i=reader.read()) {
    content.append((char)i);
  }
  writer.append(content.toString().replace("FindProxyForURL","originalFindProxyForURL"));
  writer.append("\n");
}
 

Example 18

From project Calendar-Application, under directory /au/com/bytecode/opencsv/.

Source file: ResultSetHelperService.java

  32 
vote

private static String read(Clob c) throws SQLException, IOException {
  StringBuilder sb=new StringBuilder((int)c.length());
  Reader r=c.getCharacterStream();
  char[] cbuf=new char[CLOBBUFFERSIZE];
  int n;
  while ((n=r.read(cbuf,0,cbuf.length)) != -1) {
    sb.append(cbuf,0,n);
  }
  return sb.toString();
}
 

Example 19

From project candlepin, under directory /src/test/java/org/candlepin/sync/.

Source file: ConsumerTypeImporterTest.java

  32 
vote

@Test public void testDeserialize() throws IOException {
  String consumerTypeString="{\"id\":15, \"label\":\"prosumer\"}";
  Reader reader=new StringReader(consumerTypeString);
  ConsumerType consumerType=new ConsumerTypeImporter(null).createObject(SyncUtils.getObjectMapper(new Config(new HashMap<String,String>())),reader);
  assertEquals("prosumer",consumerType.getLabel());
}
 

Example 20

From project caustic, under directory /console/src/au/com/bytecode/opencsv/.

Source file: ResultSetHelperService.java

  32 
vote

private static String read(Clob c) throws SQLException, IOException {
  StringBuilder sb=new StringBuilder((int)c.length());
  Reader r=c.getCharacterStream();
  char[] cbuf=new char[CLOBBUFFERSIZE];
  int n;
  while ((n=r.read(cbuf,0,cbuf.length)) != -1) {
    sb.append(cbuf,0,n);
  }
  return sb.toString();
}
 

Example 21

From project ceres, under directory /ceres-jai/src/main/java/com/bc/ceres/jai/.

Source file: JaiShell.java

  32 
vote

private static StringBuilder read(File file) throws IOException {
  Reader reader=new BufferedReader(new FileReader(file));
  try {
    return readAll(reader);
  }
  finally {
    reader.close();
  }
}
 

Example 22

From project cider, under directory /src/net/yacy/cider/util/.

Source file: FileUtils.java

  32 
vote

/** 
 * copies the input stream to all writers (byte per byte)
 * @param data
 * @param writer
 * @param charSet
 * @return
 * @throws IOException
 */
public static int copyToWriter(final BufferedInputStream data,final BufferedWriter writer,final Charset charSet) throws IOException {
  final Reader sourceReader=new InputStreamReader(data,charSet);
  int count=0;
  int b;
  while ((b=sourceReader.read()) != -1) {
    count++;
    writer.write(b);
  }
  writer.flush();
  return count;
}
 

Example 23

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/Files/Unicode/.

Source file: UnicodeUtil.java

  31 
vote

/** 
 * Save the content of an InputStream to a file in UTF8 with Signature
 * @param file file to save
 * @param stream InputStream to copy to the file
 * @param append append data
 * @throws IOException something goes wrong with the file
 */
public static void saveUTF8File(final File file,final InputStream stream,final boolean append) throws IOException {
  BufferedWriter bw=null;
  OutputStreamWriter osw=null;
  final FileOutputStream fos=new FileOutputStream(file,append);
  final Reader reader=new BufferedReader(new UnicodeReader(stream,"UTF-8"));
  try {
    if (file.length() < 1) {
      fos.write(UTF8_BOMS);
    }
    osw=new OutputStreamWriter(fos,"UTF-8");
    bw=new BufferedWriter(osw);
    if (reader != null) {
      for (int i=0; (i=reader.read()) > 0; ) {
        bw.write(i);
      }
    }
  }
  finally {
    try {
      bw.close();
      fos.close();
      reader.close();
    }
 catch (    final Exception ex) {
    }
  }
}
 

Example 24

From project agraph-java-client, under directory /src/test/.

Source file: AGRepositoryConnectionTests.java

  31 
vote

@Test public void testAddReaderNTriples() throws Exception {
  InputStream defaultGraphStream=new FileInputStream(TEST_DIR_PREFIX + "default-graph.nt");
  Reader defaultGraph=new InputStreamReader(defaultGraphStream,"UTF-8");
  testCon.add(defaultGraph,"",RDFFormat.NTRIPLES);
  defaultGraph.close();
  assertTrue("Repository should contain newly added statements",testCon.hasStatement(null,publisher,nameBob,false));
  assertTrue("Repository should contain newly added statements",testCon.hasStatement(null,publisher,nameAlice,false));
  InputStream graph1Stream=new FileInputStream(TEST_DIR_PREFIX + "graph1.nt");
  Reader graph1=new InputStreamReader(graph1Stream,"UTF-8");
  try {
    testCon.add(graph1,"",RDFFormat.NTRIPLES,context1);
  }
  finally {
    graph1.close();
  }
  InputStream graph2Stream=new FileInputStream(TEST_DIR_PREFIX + "graph2.nt");
  Reader graph2=new InputStreamReader(graph2Stream,"UTF-8");
  try {
    testCon.add(graph2,"",RDFFormat.NTRIPLES,context2);
  }
  finally {
    graph2.close();
  }
  assertTrue("alice should be known in the store",testCon.hasStatement(null,name,nameAlice,false));
  assertFalse("alice should not be known in context1",testCon.hasStatement(null,name,nameAlice,false,context1));
  assertTrue("alice should be known in context2",testCon.hasStatement(null,name,nameAlice,false,context2));
  assertTrue("bob should be known in the store",testCon.hasStatement(null,name,nameBob,false));
  assertFalse("bob should not be known in context2",testCon.hasStatement(null,name,nameBob,false,context2));
  assertTrue("bib should be known in context1",testCon.hasStatement(null,name,nameBob,false,context1));
}
 

Example 25

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

Source file: FileUtils.java

  31 
vote

public static String readFile(String path) throws IOException {
  FileInputStream is=new FileInputStream(path);
  try {
    StringBuilder sb=new StringBuilder();
    Reader reader=new BufferedReader(new InputStreamReader(is));
    char[] buffer=new char[8192];
    int read;
    while ((read=reader.read(buffer)) > 0) {
      sb.append(buffer,0,read);
    }
    return sb.toString();
  }
  finally {
    is.close();
  }
}
 

Example 26

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

Source file: OAuthUtils.java

  31 
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 27

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

Source file: EntityUtils.java

  31 
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 28

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

Source file: BaseJEP.java

  31 
vote

/** 
 * Parses the expression.  The root of the expression tree is returned by  {@link #getTopNode()} method
 * @throws com.meidusa.amoeba.sqljep.ParseException If there are errors in the expression then it fires the exception
 */
final public void parseExpression(Map<String,Integer> columnMapping,Map<String,Variable> variableMapping,final Map<String,PostfixCommand> funMap) throws ParseException {
  Reader reader=new StringReader(expression);
  Parser parser=new Parser(reader){
    @Override public boolean containsKey(    String key){
      return funMap.containsKey(key);
    }
    @Override public PostfixCommandI getFunction(    String name){
      return funMap.get(name);
    }
  }
;
  parser.setColumnMapping(columnMapping);
  parser.setVariableMapping(variableMapping);
  try {
    topNode=parser.parseStream(reader);
    errorList.clear();
    errorList.addAll(parser.getErrorList());
  }
 catch (  ParseException e) {
    topNode=null;
    errorList.add(e.getMessage());
  }
catch (  Throwable e) {
    throw new com.meidusa.amoeba.sqljep.ParseException(toString(),e);
  }
  if (hasError()) {
    throw new com.meidusa.amoeba.sqljep.ParseException(getErrorInfo());
  }
  if (debug) {
    ParserVisitor v=new ParserDumpVisitor();
    try {
      topNode.jjtAccept(v,null);
    }
 catch (    ParseException e) {
      errorList.add(e.getMessage());
      e.printStackTrace();
    }
  }
}
 

Example 29

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

Source file: ArticleViewActivity.java

  31 
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 30

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

Source file: OAuthMessage.java

  31 
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 31

From project Arecibo, under directory /aggregator/src/main/java/com/ning/arecibo/aggregator/stringtemplates/.

Source file: HtmlTemplateGroupLoader.java

  31 
vote

public static StringTemplateGroup load(String name,URL resourceUrl){
  Reader reader;
  try {
    reader=new InputStreamReader(resourceUrl.openStream());
  }
 catch (  IOException ex) {
    throw new RuntimeException(String.format("Error loading StringTemplate: %s",name),ex);
  }
  AtomicBoolean error=new AtomicBoolean(false);
  StringTemplateGroup result=new StringTemplateGroup(reader,DefaultTemplateLexer.class,new StringTemplateErrorListener(){
    public void error(    String msg,    Throwable e){
      log.error(msg,e);
    }
    public void warning(    String msg){
      log.warn(msg);
    }
    public void debug(    String msg){
      log.debug(msg);
    }
  }
);
  if (error.get()) {
    throw new RuntimeException(String.format("Error loading StringTemplate: %s",name));
  }
  return result;
}
 

Example 32

From project b3log-latke, under directory /maven-min-plugin/src/main/java/org/b3log/maven/plugin/min/.

Source file: CSSProcessor.java

  31 
vote

/** 
 * Minimizes CSS sources.
 */
@Override protected void minimize(){
  if (null == getSrcDir()) {
    getLogger().error("The source directory is null!");
    return;
  }
  try {
    final File srcDir=getSrcDir();
    final File[] srcFiles=srcDir.listFiles(new FileFilter(){
      @Override public boolean accept(      final File file){
        return !file.isDirectory() && !file.getName().endsWith(getSuffix() + ".css");
      }
    }
);
    for (int i=0; i < srcFiles.length; i++) {
      final File src=srcFiles[i];
      final String targetPath=getTargetDir() + File.separator + src.getName().substring(0,src.getName().length() - ".css".length())+ getSuffix()+ ".css";
      final File target=new File(targetPath);
      getLogger().info("Minimizing [srcPath=" + src.getPath() + ", targetPath="+ targetPath+ "]");
      final Reader reader=new InputStreamReader(new FileInputStream(src),"UTF-8");
      final FileOutputStream writerStream=new FileOutputStream(target);
      final Writer writer=new OutputStreamWriter(writerStream,"UTF-8");
      final CssCompressor compressor=new CssCompressor(reader);
      compressor.compress(writer,-1);
      reader.close();
      writer.close();
    }
  }
 catch (  final IOException e) {
    getLogger().error("Minimization error!",e);
  }
}
 

Example 33

From project Bifrost, under directory /src/main/java/com/craftfire/bifrost/scripts/forum/.

Source file: XenForo.java

  31 
vote

@Override public boolean authenticate(String username,String password){
  Blob hashBlob=this.getDataManager().getBlobField("user_authenticate","data","`user_id` = '" + getUserID(username) + "'");
  String hash="", salt="";
  if (hashBlob != null) {
    int offset=-1;
    int chunkSize=1024;
    StringBuilder stringBuffer=new StringBuilder();
    try {
      long blobLength=hashBlob.length();
      if (chunkSize > blobLength) {
        chunkSize=(int)blobLength;
      }
      char buffer[]=new char[chunkSize];
      Reader reader=new InputStreamReader(hashBlob.getBinaryStream());
      while ((offset=reader.read(buffer)) != -1) {
        stringBuffer.append(buffer,0,offset);
      }
    }
 catch (    IOException e) {
      this.getLoggingManager().stackTrace(e);
    }
catch (    SQLException e) {
      this.getLoggingManager().stackTrace(e);
    }
    String cache=stringBuffer.toString();
    hash=CraftCommons.forumCacheValue(cache,"hash");
    salt=CraftCommons.forumCacheValue(cache,"salt");
  }
  return hashPassword(salt,password).equals(hash);
}
 

Example 34

From project BioMAV, under directory /Behavior/src/nl/ru/ai/projects/parrot/tools/.

Source file: TwitterAccess.java

  31 
vote

/** 
 * Uploads an image
 * @param image The image to upload
 * @param tweet The text of the tweet that needs to be posted with the image
 */
public void uploadImage(byte[] image,String tweet){
  if (!enabled)   return;
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  RenderedImage img=getImageFromCamera(image);
  try {
    ImageIO.write(img,"jpg",baos);
    URL url=new URL("http://api.imgur.com/2/upload.json");
    String data=URLEncoder.encode("image","UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(baos.toByteArray()),"UTF-8");
    data+="&" + URLEncoder.encode("key","UTF-8") + "="+ URLEncoder.encode("f9c4861fc0aec595e4a64dd185751d28","UTF-8");
    URLConnection conn=url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr=new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
    StringBuffer buffer=new StringBuffer();
    InputStreamReader isr=new InputStreamReader(conn.getInputStream());
    Reader in=new BufferedReader(isr);
    int ch;
    while ((ch=in.read()) > -1)     buffer.append((char)ch);
    String imgURL=processJSON(buffer.toString());
    setStatus(tweet + " " + imgURL,100);
  }
 catch (  IOException e1) {
    e1.printStackTrace();
  }
}
 

Example 35

From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/.

Source file: DetermineFirstSeenThread.java

  31 
vote

@Override public void run(){
  try {
    final URLConnection connection=new URL(Constants.BLOCKEXPLORER_BASE_URL + "address/" + address).openConnection();
    connection.connect();
    final Reader is=new InputStreamReader(new BufferedInputStream(connection.getInputStream()));
    final StringBuilder content=new StringBuilder();
    IOUtils.copy(is,content);
    is.close();
    final Matcher m=P_FIRST_SEEN.matcher(content);
    if (m.find()) {
      succeed(Iso8601Format.parseDateTime(m.group(1)));
    }
 else {
      succeed(null);
    }
  }
 catch (  final IOException x) {
    failed(x);
  }
catch (  final ParseException x) {
    failed(x);
  }
}
 

Example 36

From project BMach, under directory /src/jsyntaxpane/actions/.

Source file: ScriptAction.java

  31 
vote

/** 
 * @param url
 */
public void getScriptFromURL(String url){
  InputStream is=JarServiceProvider.findResource(url,this.getClass().getClassLoader());
  if (is != null) {
    Reader reader=new InputStreamReader(is);
    try {
      engine.eval(reader);
    }
 catch (    ScriptException ex) {
      showScriptError(null,ex);
    }
  }
 else {
    JOptionPane.showMessageDialog(null,"No script is found in: " + url,"Error in Script",JOptionPane.WARNING_MESSAGE);
  }
}
 

Example 37

From project book, under directory /src/test/java/com/tamingtext/classifier/mlt/.

Source file: MoreLikeThisQueryTest.java

  31 
vote

@Test public void testMoreLikeThisQuery() throws Exception {
  Directory directory=FSDirectory.open(new File(modelPath));
  IndexReader indexReader=IndexReader.open(directory);
  IndexSearcher indexSearcher=new IndexSearcher(indexReader);
  Analyzer analyzer=new EnglishAnalyzer(Version.LUCENE_36);
  if (nGramSize > 1) {
    analyzer=new ShingleAnalyzerWrapper(analyzer,nGramSize,nGramSize);
  }
  MoreLikeThis moreLikeThis=new MoreLikeThis(indexReader);
  moreLikeThis.setAnalyzer(analyzer);
  moreLikeThis.setFieldNames(new String[]{"content"});
  moreLikeThis.setMinTermFreq(1);
  moreLikeThis.setMinDocFreq(1);
  Reader reader=new FileReader(inputPath);
  Query query=moreLikeThis.like(reader);
  TopDocs results=indexSearcher.search(query,maxResults);
  HashMap<String,CategoryHits> categoryHash=new HashMap<String,CategoryHits>();
  for (  ScoreDoc sd : results.scoreDocs) {
    Document d=indexReader.document(sd.doc);
    Fieldable f=d.getFieldable(categoryFieldName);
    String cat=f.stringValue();
    CategoryHits ch=categoryHash.get(cat);
    if (ch == null) {
      ch=new CategoryHits();
      ch.setLabel(cat);
      categoryHash.put(cat,ch);
    }
    ch.incrementScore(sd.score);
  }
  SortedSet<CategoryHits> sortedCats=new TreeSet<CategoryHits>(CategoryHits.byScoreComparator());
  sortedCats.addAll(categoryHash.values());
  for (  CategoryHits c : sortedCats) {
    System.out.println(c.getLabel() + "\t" + c.getScore());
  }
}
 

Example 38

From project bundlemaker, under directory /unittests/org.bundlemaker.core.testutils/src/org/bundlemaker/core/testutils/.

Source file: BundleMakerTestUtils.java

  31 
vote

/** 
 * <p> </p>
 * @param is
 * @return
 * @throws IOException
 */
public static String convertStreamToString(InputStream is){
  try {
    if (is != null) {
      Writer writer=new StringWriter();
      char[] buffer=new char[1024];
      try {
        Reader reader=new BufferedReader(new InputStreamReader(is,"UTF-8"));
        int n;
        while ((n=reader.read(buffer)) != -1) {
          writer.write(buffer,0,n);
        }
      }
  finally {
        is.close();
      }
      return writer.toString();
    }
 else {
      return "";
    }
  }
 catch (  Exception e) {
    throw new RuntimeException(e.getMessage(),e);
  }
}
 

Example 39

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/xmlconfig/.

Source file: JAXBBinding.java

  31 
vote

/** 
 * <p class="changed_added_4_0"> Close input source after parsing. </p>
 * @param source
 */
private void closeSource(Source source){
  if (source instanceof SAXSource) {
    SAXSource saxSource=(SAXSource)source;
    InputSource inputSource=saxSource.getInputSource();
    try {
      Reader stream=inputSource.getCharacterStream();
      if (null != stream) {
        stream.close();
      }
 else {
        InputStream byteStream=inputSource.getByteStream();
        if (null != byteStream) {
          byteStream.close();
        }
      }
    }
 catch (    IOException e) {
    }
  }
}
 

Example 40

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

Source file: Utils.java

  29 
vote

public static void copyStream(Reader in,OutputStream out,String charSet) throws IOException {
  char[] buf=new char[4096];
  int len;
  if (charSet == null)   while ((len=in.read(buf)) != -1) {
    out.write(new String(buf,0,len).getBytes());
  }
 else   while ((len=in.read(buf)) != -1)   out.write(new String(buf,0,len).getBytes(charSet));
}
 

Example 41

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

Source file: IniArtifactDataReader.java

  29 
vote

private ArtifactDescription parse(Reader reader) throws IOException {
  String line=null;
  State state=State.NONE;
  Map<State,List<String>> sections=new HashMap<State,List<String>>();
  BufferedReader in=new BufferedReader(reader);
  try {
    while ((line=in.readLine()) != null) {
      line=cutComment(line);
      if (isEmpty(line)) {
        continue;
      }
      if (line.startsWith("[")) {
        try {
          state=State.valueOf(line.substring(1,line.length() - 1).toUpperCase(Locale.ENGLISH));
          sections.put(state,new ArrayList<String>());
        }
 catch (        IllegalArgumentException e) {
          throw new IOException("unknown section: " + line);
        }
      }
 else {
        List<String> lines=sections.get(state);
        if (lines == null) {
          throw new IOException("missing section: " + line);
        }
        lines.add(line.trim());
      }
    }
  }
  finally {
    in.close();
  }
  List<Artifact> relocations=relocations(sections.get(State.RELOCATIONS));
  List<Dependency> dependencies=dependencies(sections.get(State.DEPENDENCIES));
  List<Dependency> managedDependencies=dependencies(sections.get(State.MANAGEDDEPENDENCIES));
  List<RemoteRepository> repositories=repositories(sections.get(State.REPOSITORIES));
  ArtifactDescription description=new ArtifactDescription(relocations,dependencies,managedDependencies,repositories);
  return description;
}
 

Example 42

From project and-bible, under directory /jsword-tweaks/src/main/java/jsword/org/crosswire/jsword/index/lucene/analysis/.

Source file: ConfigurableSnowballAnalyzer.java

  29 
vote

/** 
 * Filters  {@link LowerCaseTokenizer} with {@link StopFilter} if enabled and{@link SnowballFilter}.
 */
@Override public final TokenStream tokenStream(String fieldName,Reader reader){
  TokenStream result=new LowerCaseTokenizer(reader);
  if (doStopWords && stopSet != null) {
    result=new StopFilter(false,result,stopSet);
  }
  if (doStemming) {
    result=new SnowballFilter(result,stemmerName);
  }
  return result;
}
 

Example 43

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

Source file: InternalUtils.java

  29 
vote

/** 
 * Use a buffered reader to extract the contents of the given reader.
 * @param reader
 * @return The contents of this reader.
 */
static String toString(Reader reader) throws RuntimeException {
  try {
    reader=reader instanceof BufferedReader ? (BufferedReader)reader : new BufferedReader(reader);
    StringBuilder output=new StringBuilder();
    while (true) {
      int c=reader.read();
      if (c == -1) {
        break;
      }
      output.append((char)c);
    }
    return output.toString();
  }
 catch (  IOException ex) {
    throw new RuntimeException(ex);
  }
 finally {
    URLConnectionHttpClient.close(reader);
  }
}
 

Example 44

From project android_8, under directory /src/com/google/gson/.

Source file: Gson.java

  29 
vote

/** 
 * This method deserializes the Json read from the specified reader into an object of the specified class. It is not suitable to use if the specified class is a generic type since it will not have the generic type information because of the Type Erasure feature of Java. Therefore, this method should not be used if the desired type is a generic type. Note that this method works fine if the any of the fields of the specified object are generics, just the object itself should not be a generic type. For the cases when the object is of generic type, invoke  {@link #fromJson(Reader,Type)}. If you have the Json in a String form instead of a {@link Reader}, use  {@link #fromJson(String,Class)} instead.
 * @param < T > the type of the desired object
 * @param json the reader producing the Json from which the object is to be deserialized.
 * @param classOfT the class of T
 * @return an object of type T from the string
 * @throws JsonIOException if there was a problem reading from the Reader
 * @throws JsonSyntaxException if json is not a valid representation for an object of type
 * @since 1.2
 */
public <T>T fromJson(Reader json,Class<T> classOfT) throws JsonSyntaxException, JsonIOException {
  JsonReader jsonReader=new JsonReader(json);
  Object object=fromJson(jsonReader,classOfT);
  assertFullConsumption(object,jsonReader);
  return Primitives.wrap(classOfT).cast(object);
}
 

Example 45

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

Source file: CharStreams.java

  29 
vote

/** 
 * Joins multiple  {@link Reader} suppliers into a single supplier.Reader returned from the supplier will contain the concatenated data from the readers of the underlying suppliers. <p>Reading from the joined reader will throw a  {@link NullPointerException}if any of the suppliers are null or return null. <p>Only one underlying reader will be open at a time. Closing the joined reader will close the open underlying reader.
 * @param suppliers the suppliers to concatenate
 * @return a supplier that will return a reader containing the concatenateddata
 */
public static InputSupplier<Reader> join(final Iterable<? extends InputSupplier<? extends Reader>> suppliers){
  return new InputSupplier<Reader>(){
    public Reader getInput() throws IOException {
      return new MultiReader(suppliers.iterator());
    }
  }
;
}
 

Example 46

From project any23, under directory /core/src/main/java/org/apache/any23/util/.

Source file: ReaderInputStream.java

  29 
vote

/** 
 * Construct a <CODE>ReaderInputStream</CODE> for the specified <CODE>Reader</CODE>, with the specified encoding.
 * @param reader     non-null <CODE>Reader</CODE>.
 * @param encoding   non-null <CODE>String</CODE> encoding.
 */
public ReaderInputStream(Reader reader,String encoding){
  this(reader);
  if (encoding == null) {
    throw new IllegalArgumentException("encoding must not be null");
  }
 else {
    this.encoding=encoding;
  }
}
 

Example 47

From project arquillian-container-openshift, under directory /openshift-express/src/main/java/org/jboss/arquillian/container/openshift/express/util/.

Source file: IOUtils.java

  29 
vote

/** 
 * Unconditionally close an Reader. Equivalent to  {@link Reader#close()}, except any exceptions will be ignored. This is typically used in finally blocks.
 * @param input the Reader to close, may be null or already closed
 */
public static void closeQuietly(Reader input){
  try {
    if (input != null) {
      input.close();
    }
  }
 catch (  IOException ioe) {
  }
}
 

Example 48

From project as3-commons-jasblocks, under directory /src/main/java/org/as3commons/asblocks/impl/.

Source file: ASTASParser.java

  29 
vote

@Override public IASCompilationUnit parseIn(Reader in){
  AS3Parser parser=ASTUtils.parse(in);
  LinkedListTree cu;
  try {
    cu=AS3FragmentParser.tree(parser.compilationUnit());
  }
 catch (  RecognitionException e) {
    throw ASTUtils.buildSyntaxException(null,parser,e);
  }
  return new ASTASCompilationUnit(cu);
}
 

Example 49

From project azkaban, under directory /azkaban/src/java/azkaban/util/process/.

Source file: AzkabanProcess.java

  29 
vote

public LogGobbler(final Reader inputReader,final Logger logger,final Level level,final int bufferLines){
  this.inputReader=new BufferedReader(inputReader);
  this.logger=logger;
  this.loggingLevel=level;
  buffer=new CircularBuffer<String>(bufferLines);
}
 

Example 50

From project b1-pack, under directory /standard/src/main/java/org/b1/pack/standard/writer/.

Source file: CompressedFormatDetector.java

  29 
vote

private static void readResource(final URL url,ImmutableSet.Builder<String> builder) throws IOException {
  StringTokenizer tokenizer=new StringTokenizer(CharStreams.toString(new InputSupplier<Reader>(){
    @Override public Reader getInput() throws IOException {
      return new InputStreamReader(url.openStream(),Charsets.UTF_8);
    }
  }
));
  while (tokenizer.hasMoreTokens()) {
    builder.add(tokenizer.nextToken().toLowerCase());
  }
}
 

Example 51

From project beanstalker, under directory /simpledb-maven-plugin/src/main/java/br/com/ingenieux/mojo/simpledb/cmd/.

Source file: PutAttributesContext.java

  29 
vote

public PutAttributesContext(String domain,Reader source,boolean createDomainIfNeeded){
  super();
  this.domain=domain;
  this.source=source;
  this.createDomainIfNeeded=createDomainIfNeeded;
}
 

Example 52

From project BeeQueue, under directory /lib/src/hyperic-sigar-1.6.4/bindings/java/examples/.

Source file: Tail.java

  29 
vote

public static void main(String[] args) throws SigarException {
  Sigar sigar=new Sigar();
  FileWatcherThread watcherThread=FileWatcherThread.getInstance();
  watcherThread.doStart();
  watcherThread.setInterval(1000);
  FileTail watcher=new FileTail(sigar){
    public void tail(    FileInfo info,    Reader reader){
      String line;
      BufferedReader buffer=new BufferedReader(reader);
      if (getFiles().size() > 1) {
        System.out.println("==> " + info.getName() + " <==");
      }
      try {
        while ((line=buffer.readLine()) != null) {
          System.out.println(line);
        }
      }
 catch (      IOException e) {
        System.out.println(e);
      }
    }
  }
;
  for (int i=0; i < args.length; i++) {
    watcher.add(args[i]);
  }
  watcherThread.add(watcher);
  try {
    System.in.read();
  }
 catch (  IOException e) {
  }
  watcherThread.doStop();
}
 

Example 53

From project big-data-plugin, under directory /test-src/org/pentaho/di/job/entries/pig/.

Source file: JobEntryPigScriptExecutorTest.java

  29 
vote

private StringBuffer readResource(Reader r) throws IOException {
  StringBuffer ret=new StringBuffer();
  char[] buf=new char[5];
  for (int read=r.read(buf); read > 0; read=r.read(buf)) {
    ret.append(new String(buf,0,read));
  }
  r.close();
  return ret;
}
 

Example 54

From project Bio-PEPA, under directory /uk.ac.ed.inf.biopepa.core/src/uk/ac/ed/inf/biopepa/core/dom/internal/.

Source file: BioPEPALexer.java

  29 
vote

/** 
 * Resets the scanner to read from a new input stream. Does not close the old reader. All internal variables are reset, the old input stream  <b>cannot</b> be reused (internal buffer is discarded and lost). Lexical state is set to <tt>ZZ_INITIAL</tt>.
 * @param reader   the new input stream 
 */
public final void yyreset(java.io.Reader reader){
  zzReader=reader;
  zzAtBOL=true;
  zzAtEOF=false;
  zzEndRead=zzStartRead=0;
  zzCurrentPos=zzMarkedPos=zzPushbackPos=0;
  yyline=yychar=yycolumn=0;
  zzLexicalState=YYINITIAL;
}
 

Example 55

From project bndtools, under directory /bndtools.core/src/bndtools/utils/.

Source file: TextUtils.java

  29 
vote

public static void indentText(String initialIndent,String innerIndent,Reader input,StringBuffer result) throws IOException {
  BufferedReader reader=(input instanceof BufferedReader) ? (BufferedReader)input : new BufferedReader(input);
  String line=reader.readLine();
  while (line != null) {
    line=initialIndent + line.replaceAll("\t",innerIndent);
    result.append(line);
    line=reader.readLine();
    if (line != null)     result.append('\n');
  }
}
 

Example 56

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: CallableStatementHandle.java

  29 
vote

@Override public Reader getCharacterStream(int parameterIndex) throws SQLException {
  checkClosed();
  try {
    return this.internalCallableStatement.getCharacterStream(parameterIndex);
  }
 catch (  SQLException e) {
    throw this.connectionHandle.markPossiblyBroken(e);
  }
}
 

Example 57

From project bpelunit, under directory /net.bpelunit.framework.control.datasource.csv/src/main/java/net/bpelunit/framework/control/datasource/csv/.

Source file: CSVDataSource.java

  29 
vote

private void setSource(Reader reader) throws DataSourceException {
  try {
    this.lines=new ArrayList<String>();
    BufferedReader in=new BufferedReader(reader);
    readColumnHeadersIfNecessary(in);
    while (in.ready()) {
      String line=in.readLine();
      if (!line.trim().equals("")) {
        this.lines.add(line);
      }
    }
  }
 catch (  IOException e) {
    throw new DataSourceException("Invalid data source",e);
  }
 finally {
    try {
      reader.close();
    }
 catch (    IOException e) {
    }
  }
}
 

Example 58

From project BPMN2-Editor-for-Eclipse, under directory /org.eclipse.bpmn2.modeler.ui/src/org/eclipse/bpmn2/modeler/ui/.

Source file: BPMN2ContentDescriber.java

  29 
vote

private synchronized String doDescribe(Reader contents) throws IOException {
  try {
    InputSource source=new InputSource(contents);
    parser=new RootElementParser();
    parser.parse(source);
  }
 catch (  AcceptedException e) {
    return e.acceptedRootElement;
  }
catch (  RejectedException e) {
    return null;
  }
catch (  Exception e) {
    return null;
  }
 finally {
    parser=null;
  }
  return null;
}
 

Example 59

From project c24-spring, under directory /c24-spring-batch/src/main/java/biz/c24/io/spring/batch/reader/source/.

Source file: FileSource.java

  29 
vote

@Override public void discard(Reader reader) throws IOException {
  if (this.reader == reader) {
    reader.close();
    this.reader=null;
  }
}
 

Example 60

From project Carolina-Digital-Repository, under directory /admin/src/main/java/edu/unc/lib/dl/search/.

Source file: SearchProcessor.java

  29 
vote

private static void bufferedRead(Reader reader,Writer writer) throws IOException {
  char[] buffer=new char[1024];
  int count=0;
  while ((count=reader.read(buffer)) >= 0) {
    writer.write(buffer,0,count);
  }
  writer.flush();
}
 

Example 61

From project cb2java, under directory /src/main/java/net/sf/cb2java/copybook/.

Source file: CopybookParser.java

  29 
vote

/** 
 * Parses a copybook definition and returns a Copybook instance
 * @param name the name of the copybook.  For future use.
 * @param reader the copybook definition's source reader
 * @return a copybook instance containing the parse tree for the definition
 */
public static Copybook parse(String name,Reader reader){
  Copybook document=null;
  Lexer lexer=null;
  try {
    String preProcessed=CobolPreprocessor.preProcess(reader);
    StringReader sr=new StringReader(preProcessed);
    PushbackReader pbr=new PushbackReader(sr,1000);
    if (debug) {
      lexer=new DebugLexer(pbr);
    }
 else {
      lexer=new Lexer(pbr);
    }
    Parser parser=new Parser(lexer);
    Start ast=parser.parse();
    CopybookAnalyzer copyBookAnalyzer=new CopybookAnalyzer(name,parser);
    ast.apply(copyBookAnalyzer);
    document=copyBookAnalyzer.getDocument();
  }
 catch (  Exception e) {
    throw new RuntimeException("fatal parse error\n" + (lexer instanceof DebugLexer ? "=== buffer dump start ===\n" + ((DebugLexer)lexer).getBuffer() + "\n=== buffer dump end ===" : ""),e);
  }
  return document;
}
 

Example 62

From project ceylon-ide-eclipse, under directory /plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/editor/.

Source file: StreamUtils.java

  29 
vote

/** 
 * Reads the contents of the given reader into a string using the encoding associated with the reader. Returns null if an error occurred.
 */
public static String readReaderContents(Reader r){
  BufferedReader reader=null;
  try {
    StringBuffer buffer=new StringBuffer();
    char[] part=new char[2048];
    int read=0;
    reader=new BufferedReader(r);
    while ((read=reader.read(part)) != -1)     buffer.append(part,0,read);
    return buffer.toString();
  }
 catch (  IOException ex) {
    System.err.println("I/O Exception: " + ex.getMessage());
  }
 finally {
    if (reader != null) {
      try {
        reader.close();
      }
 catch (      IOException ex) {
      }
    }
  }
  return null;
}
 

Example 63

From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/admin/util/.

Source file: JSONTokener.java

  29 
vote

/** 
 * Construct a JSONTokener from a Reader.
 * @param reader     A reader.
 */
public JSONTokener(Reader reader){
  this.reader=reader.markSupported() ? reader : new BufferedReader(reader);
  this.eof=false;
  this.usePrevious=false;
  this.previous=0;
  this.index=0;
  this.character=1;
  this.line=1;
}