Java Code Examples for java.io.FileReader

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 aranea, under directory /server/src/main/java/no/dusken/aranea/util/.

Source file: BaseTool.java

  33 
vote

public BaseTool() throws IOException {
  Properties p=new Properties();
  FileReader fileReader=null;
  try {
    fileReader=new FileReader(fileWrapper.getFile());
    p.load(fileReader);
  }
  finally {
    if (fileReader != null)     fileReader.close();
  }
  basestring=p.getProperty("baseurl",null);
  basesecure=p.getProperty("baseurlsecure",null);
  baseadminstring=p.getProperty("baseadminurl",null);
}
 

Example 2

From project Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/.

Source file: AndroidFlashcards.java

  32 
vote

static protected Lesson parseXML(File file,String default_name) throws Exception {
  XMLReader xr=XMLReaderFactory.createXMLReader();
  FCParser fcp=new FCParser();
  xr.setContentHandler(fcp);
  xr.setErrorHandler(fcp);
  FileReader r=new FileReader(file);
  xr.parse(new InputSource(r));
  String name=fcp.getName();
  if (name == "")   name=default_name;
  String description=fcp.getDesc();
  return new Lesson(fcp.getCards(),name,description);
}
 

Example 3

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

Source file: Wakelocks.java

  32 
vote

private static ArrayList<String[]> parseDelimitedFile(String filePath,String delimiter){
  ArrayList<String[]> rows=new ArrayList<String[]>();
  try {
    FileReader fr=new FileReader(filePath);
    BufferedReader br=new BufferedReader(fr);
    String currentRecord;
    while ((currentRecord=br.readLine()) != null)     rows.add(currentRecord.split(delimiter));
    br.close();
  }
 catch (  Exception e) {
  }
  return rows;
}
 

Example 4

From project bioclipse.speclipse, under directory /plugins/net.bioclipse.spectrum/src/spok/parser/.

Source file: JcampParser.java

  32 
vote

/** 
 * Reads the content of file (filename) into a string
 * @param filename name and path of the file to load
 * @return content of file in one string
 */
public String readFile(File filename) throws IOException {
  StringBuffer buffer=new StringBuffer();
  FileReader fileReader=new FileReader(filename);
  BufferedReader input=new BufferedReader(fileReader);
  int character;
  while ((character=input.read()) != -1) {
    buffer.append((char)character);
  }
  input.close();
  return buffer.toString();
}
 

Example 5

From project book, under directory /src/main/java/com/tamingtext/tagrecommender/.

Source file: TagRecommenderClient.java

  32 
vote

/** 
 * Simple utility to read a file to a string 
 */
public static String readFile(String file) throws IOException {
  StringBuilder buffer=new StringBuilder();
  char[] c=new char[1024];
  int read;
  FileReader fr=new FileReader(file);
  while ((read=fr.read(c)) > 0) {
    buffer.append(c,0,read);
  }
  fr.close();
  return buffer.toString();
}
 

Example 6

From project Bukkit-Plugin-Utilties, under directory /src/main/java/de/xzise/.

Source file: MinecraftUtil.java

  32 
vote

public static void copyFile(File source,File destination) throws IOException {
  FileReader in=new FileReader(source);
  if (!destination.exists()) {
    destination.createNewFile();
  }
  FileWriter out=new FileWriter(destination);
  int c;
  while ((c=in.read()) != -1)   out.write(c);
  in.close();
  out.close();
}
 

Example 7

From project caustic, under directory /core/src/net/caustic/file/.

Source file: JavaIOFileLoader.java

  32 
vote

public String load(String path) throws IOException {
  File file=new File(path);
  FileReader fileReader=new FileReader(file);
  char[] buffer=new char[(int)file.length()];
  fileReader.read(buffer);
  fileReader.close();
  return new String(buffer);
}
 

Example 8

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

Source file: ReportDownloader.java

  31 
vote

private void serveTemplate(HttpServletRequest request,HttpServletResponse response,BaseReportInfo report,String templateName) throws ServletException {
  String rinsedTemplateName=templateName.replaceAll("\\..*$","").replaceAll("\\W","") + ".vm";
  try {
    AuthManagerInfo authManager=this.databaseDefn.getAuthManager();
    if (!authManager.getAuthenticator().loggedInUserAllowedTo(request,PrivilegeType.MANAGE_TABLE,report.getParentTable())) {
      throw new DisallowedException(authManager.getLoggedInUser(request),PrivilegeType.MANAGE_TABLE,report.getParentTable());
    }
    CompanyInfo company=this.databaseDefn.getAuthManager().getCompanyForLoggedInUser(request);
    String pathString=this.databaseDefn.getDataManagement().getWebAppRoot() + "WEB-INF/templates/uploads/" + company.getInternalCompanyName()+ "/"+ report.getInternalReportName()+ "/"+ rinsedTemplateName;
    FileReader fr=new FileReader(pathString);
    BufferedReader br=new BufferedReader(fr);
    List<String> lines=new LinkedList<String>();
    String s;
    while ((s=br.readLine()) != null) {
      lines.add(s);
    }
    fr.close();
    response.setHeader("Content-disposition","attachment; filename=" + rinsedTemplateName);
    response.setHeader("Cache-Control","no-cache");
    response.setContentType("text/html");
    ServletOutputStream sos=response.getOutputStream();
    for (    String line : lines) {
      sos.println(line);
    }
    sos.flush();
  }
 catch (  AgileBaseException abex) {
    logger.error("Problem serving template: " + abex);
    throw new ServletException("Problem serving template: " + abex);
  }
catch (  IOException ioex) {
    logger.error("Problem serving template: " + ioex);
    throw new ServletException("Problem serving template: " + ioex);
  }
}
 

Example 9

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

Source file: Util.java

  31 
vote

public static List<String> readLines(File file){
  List list=new ArrayList<String>();
  FileReader f=null;
  BufferedReader s=null;
  try {
    f=new FileReader(file);
    s=new BufferedReader(f);
    String l=s.readLine();
    while (l != null) {
      list.add(l);
      l=s.readLine();
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(file.getAbsolutePath(),e);
  }
 finally {
    Closer.Close(f);
    Closer.Close(s);
  }
  return list;
}
 

Example 10

From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/dataholders/loadingutils/.

Source file: XmlMerger.java

  31 
vote

private Properties restoreFileModifications(File file){
  if (!file.exists() || !file.isFile())   return null;
  FileReader reader=null;
  try {
    Properties props=new Properties();
    reader=new FileReader(file);
    props.load(reader);
    return props;
  }
 catch (  IOException e) {
    logger.debug("File modfications restoring error. ",e);
    return null;
  }
 finally {
    IOUtils.closeQuietly(reader);
  }
}
 

Example 11

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

Source file: ConfigurationLoader.java

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

From project Android-DB-Editor, under directory /src/com/troido/dbeditor/.

Source file: TreeMouseListener.java

  31 
vote

public TreeMouseListener(){
  if (sqlitepath == null) {
    try {
      Properties props=new Properties();
      String iniPath=new File(TreeMouseListener.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent() + "/settings.ini";
      props.load(new FileReader(iniPath));
      sqlitepath=props.getProperty("sqliteeditorpath");
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
  }
}
 

Example 13

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

Source file: MicrodataExtractorTest.java

  31 
vote

private List<Statement> loadResultStatement(String resultFilePath) throws RDFHandlerException, IOException, RDFParseException {
  RDFParser nQuadsParser=Rio.createParser(RDFFormat.NQUADS);
  TestRDFHandler rdfHandler=new TestRDFHandler();
  nQuadsParser.setRDFHandler(rdfHandler);
  File file=copyResourceToTempFile(resultFilePath);
  nQuadsParser.parse(new FileReader(file),baseURI.toString());
  return rdfHandler.getStatements();
}
 

Example 14

From project ATHENA, under directory /src/main/java/com/synaptik/athena/.

Source file: AthenaTestSuite.java

  31 
vote

public void populateTests(File classFile) throws IOException {
  FileReader fr=null;
  BufferedReader br=null;
  try {
    fr=new FileReader(classFile);
    br=new BufferedReader(fr);
    String line=br.readLine();
    while (line != null) {
      if (line.contains("void test")) {
        String testName=getTestName(line);
        AthenaTest test=new AthenaTest();
        test.name=testName;
        tests.add(test);
      }
      line=br.readLine();
    }
  }
  finally {
    if (br != null) {
      br.close();
    }
  }
}
 

Example 15

From project avro, under directory /lang/java/tools/src/main/java/org/apache/avro/tool/.

Source file: DataFileWriteTool.java

  31 
vote

public static String readSchemaFromFile(String schemafile) throws IOException {
  String schemastr;
  StringBuilder b=new StringBuilder();
  FileReader r=new FileReader(schemafile);
  try {
    char[] buf=new char[64 * 1024];
    for (; ; ) {
      int read=r.read(buf);
      if (read == -1)       break;
      b.append(buf,0,read);
    }
    schemastr=b.toString();
  }
  finally {
    r.close();
  }
  return schemastr;
}
 

Example 16

From project bamboo-sonar-integration, under directory /bamboo-sonar-tasks/src/main/java/com/marvelution/bamboo/plugins/sonar/tasks/.

Source file: AbstractSonarMavenBuildTask.java

  31 
vote

/** 
 * Get the Apache Maven  {@link Model} for a given project {@link File}
 * @param projectFile the project {@link File} to get the {@link Model} from
 * @return the {@link Model} read from the project {@link File}, can be <code>null</code> if exceptions occur
 */
private Model getProjectObjectModel(File projectFile){
  MavenXpp3Reader reader=new MavenXpp3Reader();
  try {
    return reader.read(new FileReader(projectFile));
  }
 catch (  Exception e) {
    getLogger().warn("Failed to read the Maven Model from file: " + projectFile.getAbsolutePath(),e);
    return null;
  }
}
 

Example 17

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

Source file: CoeffW.java

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

From project BeeQueue, under directory /src/org/beequeue/launcher/.

Source file: BeeQueueJvmHelpeer.java

  31 
vote

public BeeQueueJvmHelpeer(int port){
  FileReader r=null;
  BufferedReader br=null;
  try {
    r=new FileReader(BeeQueueHome.instance.jvmCsv(port));
    br=new BufferedReader(r);
    BeeQueueJvmInfo v;
    while (null != (v=BeeQueueJvmInfo.valueOf(br.readLine()))) {
      if (v.isMe()) {
        me=v;
      }
      if (v.status == BeeQueueJvmStatus.STARTING) {
        starting=v;
      }
      list.add(v);
    }
  }
 catch (  Exception e) {
  }
 finally {
    try {
      r.close();
    }
 catch (    Exception ignore) {
    }
    try {
      br.close();
    }
 catch (    Exception ignore) {
    }
  }
}
 

Example 19

From project BetterShop_1, under directory /src/me/jascotty2/bettershop/.

Source file: Updater.java

  31 
vote

static long readUpdatedFile(){
  File versionFile=new File(BSConfig.pluginFolder,"lastUpdate");
  long t=0;
  if (versionFile.exists() && versionFile.canRead()) {
    FileReader fstream=null;
    BufferedReader in=null;
    try {
      fstream=new FileReader(versionFile.getAbsolutePath());
      in=new BufferedReader(fstream);
      t=CheckInput.GetLong(in.readLine(),0);
    }
 catch (    Exception ex) {
      BetterShopLogger.Log(Level.SEVERE,"Error reading update save file",ex);
    }
 finally {
      if (in != null) {
        try {
          in.close();
          fstream.close();
        }
 catch (        IOException ex) {
        }
      }
    }
  }
 else {
    setUpdatedFile();
  }
  return t;
}
 

Example 20

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

Source file: BioPEPACommandLine.java

  31 
vote

private static void performImportSpread(String[] args) throws WrongArgumentsException {
  String filename=args[0];
  try {
    FileReader reader=new FileReader(filename);
    NetworKinImport nimport=new NetworKinImport();
    int kinase=getKinaseColumn(args);
    int protein=getProteinColumn(args);
    int residue=getResidueColumn(args);
    nimport.importWithReader(reader,kinase,protein,residue);
    List<NetworKinLine> nlines=nimport.getNetworKinLines();
    StringConsumer outWriter=getOutStringConsumer(args);
    if (commandHasFlag("show-narrative",args)) {
      for (      NetworKinLine line : nlines) {
        outWriter.appendLine(line.toNarrative());
      }
      outWriter.endLine();
    }
    NetworKinTranslate ntranslate=new NetworKinTranslate(nlines);
    ntranslate.translate();
    if (commandHasFlag("show-reactions",args)) {
      outWriter.appendLine(ntranslate.reactionsString());
      outWriter.endLine();
    }
    outWriter.append(ntranslate.getBioPepaString());
    outWriter.closeStringConsumer();
  }
 catch (  IOException e) {
    printUserError("There was a problem reading the file: " + filename);
    e.printStackTrace();
    System.exit(1);
  }
}
 

Example 21

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

Source file: WordNetCorpusReader.java

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

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

Source file: LauncherUtils.java

  31 
vote

public static boolean isScriptFile(File aFile){
  final char firstTwoChars[]=new char[2];
  final FileReader reader;
  int charsRead;
  try {
    reader=new FileReader(aFile);
    charsRead=reader.read(firstTwoChars);
    if (2 != charsRead) {
      return false;
    }
    return (firstTwoChars[0] == '#' && firstTwoChars[1] == '!');
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 23

From project CDKHashFingerPrint, under directory /test/fingerprints/.

Source file: HashedBloomFingerprinterTest.java

  31 
vote

@Test public void testGenerateFingerprintIsNotASubset2() throws InvalidSmilesException, Exception {
  FileReader smilesQ=new FileReader("test/data/mol/C00137.mol");
  FileReader smilesT=new FileReader("test/data/mol/C00257.mol");
  MDLV2000Reader readerQ=new MDLV2000Reader(smilesQ);
  MDLV2000Reader readerT=new MDLV2000Reader(smilesT);
  IAtomContainer moleculeQ=(IAtomContainer)readerQ.read(new AtomContainer());
  IAtomContainer moleculeT=(IAtomContainer)readerT.read(new AtomContainer());
  moleculeQ.setID((smilesQ.toString().split(".mol"))[0]);
  moleculeT.setID((smilesT.toString().split(".mol"))[0]);
  System.out.println("Atom count Q:" + moleculeQ.getAtomCount());
  System.out.println("Atom count T:" + moleculeT.getAtomCount());
  IFingerprinter fingerprint=new HashedBloomFingerprinter(1024);
  fingerprint.setRespectRingMatches(true);
  BitSet fingerprintQ;
  BitSet fingerprintT;
  fingerprintQ=fingerprint.getBitFingerprint(moleculeQ).asBitSet();
  fingerprintT=fingerprint.getBitFingerprint(moleculeT).asBitSet();
  System.out.println("fpQ " + fingerprintQ.toString());
  System.out.println("fpT " + fingerprintT.toString());
  System.out.println("isSubset: " + FingerprinterTool.isSubset(fingerprintT,fingerprintQ));
  Assert.assertFalse(FingerprinterTool.isSubset(fingerprintT,fingerprintQ));
}
 

Example 24

From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/util/.

Source file: Skins.java

  30 
vote

/** 
 * Fills the specified data model with the current skink's language  configurations.
 * @param localeString the specified locale string
 * @param currentSkinDirName the specified current skin directory name
 * @param dataModel the specified data model
 * @throws ServiceException service exception 
 */
public static void fillSkinLangs(final String localeString,final String currentSkinDirName,final Map<String,Object> dataModel) throws ServiceException {
  Stopwatchs.start("Fill Skin Langs");
  try {
    final String langName=currentSkinDirName + "." + localeString;
    Map<String,String> langs=LANG_MAP.get(langName);
    if (null == langs) {
      LANG_MAP.clear();
      LOGGER.log(Level.INFO,"Loading skin[dirName={0}, locale={1}]",new Object[]{currentSkinDirName,localeString});
      langs=new HashMap<String,String>();
      final String webRootPath=SoloServletListener.getWebRoot();
      final String language=Locales.getLanguage(localeString);
      final String country=Locales.getCountry(localeString);
      final Properties props=new Properties();
      props.load(new FileReader(webRootPath + "skins" + File.separator+ currentSkinDirName+ File.separator+ Keys.LANGUAGE+ File.separator+ Keys.LANGUAGE+ '_'+ language+ '_'+ country+ ".properties"));
      final Set<Object> keys=props.keySet();
      for (      final Object key : keys) {
        langs.put((String)key,props.getProperty((String)key));
      }
      LANG_MAP.put(langName,langs);
      LOGGER.log(Level.INFO,"Loaded skin[dirName={0}, locale={1}, keyCount={2}]",new Object[]{currentSkinDirName,localeString,langs.size()});
    }
    dataModel.putAll(langs);
  }
 catch (  final IOException e) {
    LOGGER.log(Level.SEVERE,"Fills skin langs failed",e);
    throw new ServiceException(e);
  }
 finally {
    Stopwatchs.end();
  }
}
 

Example 25

From project bel-editor, under directory /org.openbel.editor.ui/src/org/openbel/editor/ui/.

Source file: ResourceLoader.java

  30 
vote

/** 
 * Reads the  {@link ResourceIndex resource index} from the BEL FrameworkHome configured in  {@link Activator#getBELFrameworkHome()}.
 * @return ResourceIndex the resource index or {@code null} if an erroroccurred.
 */
private ResourceIndex readResourceIndex(){
  final String belFrameworkHome=getDefault().getBELFrameworkHome();
  final StringBuilder b=new StringBuilder(belFrameworkHome).append(File.separator).append("config").append(File.separator).append(SYSCONFIG_FILENAME);
  final File configFile=new File(b.toString());
  if (!readable(configFile)) {
    logError(configFile + " not readable");
    return null;
  }
  try {
    final Properties scprops=new Properties();
    scprops.load(new FileReader(configFile));
    final String rurl=scprops.getProperty("resource_index_url");
    final URL url=new URL(rurl);
    ResourceIndex resourceIndex=Parser.getInstance().parse(url);
    return resourceIndex;
  }
 catch (  Exception e) {
    e.printStackTrace();
    logError(e);
    return null;
  }
}
 

Example 26

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

Source file: EncryptionUtils.java

  30 
vote

public boolean accept(final File file){
  Reader in=null;
  try {
    in=new FileReader(file);
    if (in.read(buf) == -1)     return false;
    final String str=new String(buf);
    if (!str.toString().equals(OPENSSL_MAGIC_TEXT))     return false;
    return true;
  }
 catch (  final IOException x) {
    return false;
  }
 finally {
    if (in != null) {
      try {
        in.close();
      }
 catch (      final IOException x2) {
      }
    }
  }
}
 

Example 27

From project BMach, under directory /src/bmach/logic/machine/.

Source file: Machine.java

  30 
vote

public static void main(String[] args){
  IMachine machine=new Machine();
  IProcessor p=machine.getProcessor();
  p.addObserver(new IObserver(){
    public void notifyObserver(    Object notificationData){
      if (notificationData instanceof ProcessorNotificationData) {
        Object data=((ProcessorNotificationData)notificationData).getData();
        if (data instanceof IBitPattern) {
          try {
            IBitPattern inst=new BitPattern(16,((IBitPattern)data).toBinaryString().substring(8));
            System.out.println("Command executed: " + ProcessorUtils.instructionToString(inst));
          }
 catch (          MalformedProcessorInstructionException mpie) {
          }
        }
      }
    }
  }
);
  try {
    machine.loadInstructions(new FileReader("/home/cyberpython/Desktop/test2.bma"));
    Thread t=new Thread(machine);
    t.start();
    try {
      t.join();
    }
 catch (    InterruptedException ie) {
    }
    System.out.println();
    p.printRegistersHex(System.out);
    System.out.println();
    machine.getMemory().printHex(System.out);
  }
 catch (  FileNotFoundException fnfe) {
    fnfe.printStackTrace();
  }
catch (  MalformedInstructionException mie) {
    mie.printStackTrace();
  }
}
 

Example 28

From project botula, under directory /src/main/java/com/vanaltj/botula/.

Source file: Configurations.java

  30 
vote

private static Properties getConfigProperties() throws IOException, MadeNewPropertiesException {
  Properties properties=new Properties();
  String home=System.getenv(ENV_BOTULA_HOME);
  if (home == null) {
    home=getUserBotulaHome();
  }
  File botHome=new File(home);
  if (!botHome.exists()) {
    botHome.mkdirs();
  }
  File propsFile=new File(botHome,CONFIG_FILE);
  try {
    properties.load(new FileReader(propsFile));
  }
 catch (  FileNotFoundException fnf) {
    createPropertiesFromDefault(properties,propsFile);
    throw new MadeNewPropertiesException("Just Because.");
  }
  return properties;
}
 

Example 29

From project bundlemaker, under directory /main/org.bundlemaker.core.osgi/src/org/bundlemaker/core/osgi/utils/.

Source file: ManifestUtils.java

  30 
vote

/** 
 * <p> </p>
 * @param file
 * @return
 */
public static ManifestContents readManifestContents(File file){
  Assert.isNotNull(file);
  if (!file.exists()) {
    return null;
  }
  try {
    ManifestContents result=new RecoveringManifestParser().parse(new FileReader(file));
    return result;
  }
 catch (  Exception e) {
    System.out.println("Exception while reading " + file.getAbsolutePath());
    e.printStackTrace();
    throw new RuntimeException(e.getMessage(),e);
  }
}
 

Example 30

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

Source file: Importer.java

  30 
vote

public void importRules(File[] rulesFiles,File metadata) throws IOException {
  Meta m=mapper.readValue(metadata,Meta.class);
  if (VersionUtil.getRulesVersionCompatibility(m.getVersion())) {
    Reader reader=null;
    try {
      reader=new FileReader(rulesFiles[0]);
      rulesImporter.importObject(reader);
    }
  finally {
      if (reader != null) {
        reader.close();
      }
    }
  }
 else {
    log.warn(i18n.tr("Incompatible rules: import version {0} older than our version {1}.",m.getVersion(),VersionUtil.getVersionString()));
    log.warn(i18n.tr("Manifest data will be imported without rules import."));
  }
}
 

Example 31

From project cargo-maven2-plugin-db, under directory /src/main/java/org/codehaus/cargo/maven2/.

Source file: DependencyCalculator.java

  30 
vote

void fixupProjectArtifact() throws FileNotFoundException, IOException, XmlPullParserException, ArtifactResolutionException, ArtifactNotFoundException, InvalidDependencyVersionException, ProjectBuildingException, ArtifactInstallationException {
  MavenProject mp2=new MavenProject(mavenProject);
  for (Iterator i=mp2.createArtifacts(artifactFactory,null,null).iterator(); i.hasNext(); ) {
    Artifact art=(Artifact)i.next();
    if (art.getType().equals("war")) {
      Artifact art2=artifactFactory.createArtifactWithClassifier(art.getGroupId(),art.getArtifactId(),art.getVersion(),"pom",null);
      fixupRepositoryArtifact(art2);
    }
  }
  Model pomFile=mp2.getModel();
  File outFile=File.createTempFile("pom",".xml");
  MavenXpp3Writer pomWriter=new MavenXpp3Writer();
  pomWriter.write(new FileWriter(outFile),pomFile);
  MavenXpp3Reader pomReader=new MavenXpp3Reader();
  pomFile=pomReader.read(new FileReader(outFile));
  Artifact art=mp2.getArtifact();
  fixModelAndSaveInRepository(art,pomFile);
  outFile.delete();
}
 

Example 32

From project Carolina-Digital-Repository, under directory /services/src/test/java/edu/unc/lib/dl/cdr/services/imaging/.

Source file: ImageEnhancementServiceITCase.java

  30 
vote

private EnhancementMessage ingestSample(String filename,String dataFilename,String mimetype) throws Exception {
  File file=new File("src/test/resources",filename);
  Document doc=new SAXBuilder().build(new FileReader(file));
  PID pid=this.getManagementClient().ingest(doc,Format.FOXML_1_1,"ingesting test object");
  if (dataFilename != null) {
    File dataFile=new File("src/test/resources",dataFilename);
    String uploadURI=this.getManagementClient().upload(dataFile);
    this.getManagementClient().addManagedDatastream(pid,"DATA_FILE",false,"Image Enhancement Test",Collections.<String>emptyList(),dataFilename,true,mimetype,uploadURI);
    PID dataFilePID=new PID(pid.getPid() + "/DATA_FILE");
    this.getManagementClient().addObjectRelationship(pid,ContentModelHelper.CDRProperty.sourceData.getURI().toString(),dataFilePID);
    this.getManagementClient().addLiteralStatement(pid,ContentModelHelper.CDRProperty.hasSourceMimeType.getURI().toString(),mimetype,null);
  }
  EnhancementMessage result=new EnhancementMessage(pid,JMSMessageUtil.servicesMessageNamespace,JMSMessageUtil.ServicesActions.APPLY_SERVICE_STACK.getName());
  samples.add(pid);
  return result;
}
 

Example 33

From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Commands/.

Source file: cmdSlots.java

  29 
vote

private void setSlots(String[] args,CommandSender sender){
  try {
    Integer maxPlayer=Integer.valueOf(args[0]);
    CraftServer server=(CraftServer)Bukkit.getServer();
    server.getHandle().maxPlayers=maxPlayer;
    ChatUtils.writeSuccess(sender,"MaxPlayers set to " + maxPlayer + " !");
    Properties p=new Properties();
    BufferedReader bReader=new BufferedReader(new FileReader("server.properties"));
    p.load(bReader);
    bReader.close();
    p.setProperty("max-players",maxPlayer.toString());
    BufferedWriter bWriter=new BufferedWriter(new FileWriter("server.properties"));
    p.store(bWriter,"");
    bWriter.close();
  }
 catch (  IOException IOE) {
    ConsoleUtils.printException(IOE,"Can't update server.properties!");
  }
catch (  NumberFormatException e) {
    ChatUtils.writeError(sender,args[0] + " is not a number!");
  }
}
 

Example 34

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

Source file: Model.java

  29 
vote

public boolean loadModel(String file) throws IOException {
  File f=new File(file);
  if (f.exists()) {
    relations.clear();
    BufferedReader r=new BufferedReader(new FileReader(f));
    readFromStream(r);
    r.close();
    return true;
  }
 else {
    System.err.println("File not found: " + file);
    return false;
  }
}
 

Example 35

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/aceeditor/.

Source file: LexiconHandler.java

  29 
vote

/** 
 * Creates a new lexicon handler object and loads the given lexicon file.
 * @param lexiconFile The lexicon file to be loaded.
 */
public LexiconHandler(String lexiconFile){
  if (lexiconFile == null || lexiconFile.equals("")) {
    return;
  }
  try {
    BufferedReader in=new BufferedReader(new FileReader(lexiconFile));
    String line=in.readLine();
    while (line != null) {
      addWord(line);
      line=in.readLine();
    }
    in.close();
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
}
 

Example 36

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

Source file: FileManager.java

  29 
vote

public HashMap<String,MaterialContainer> getAlias(){
  final HashMap<String,MaterialContainer> result=new HashMap<String,MaterialContainer>();
  final ExtendedConfiguration conf=getYml("Alias");
  final List<String> aliasList=conf.getStringList("alias",new ArrayList<String>());
  final List<String> idList=conf.getStringList("ids",new ArrayList<String>());
  int i=0;
  try {
    final CSVReader csv=new CSVReader(new FileReader(getInnerFile("items.csv",null,true)));
    String[] alias;
    while ((alias=csv.readNext()) != null) {
      try {
        result.put(alias[0],new MaterialContainer(alias[1],alias[2]));
      }
 catch (      final ArrayIndexOutOfBoundsException e) {
        try {
          result.put(alias[0],new MaterialContainer(alias[1]));
        }
 catch (        final ArrayIndexOutOfBoundsException e2) {
        }
      }
    }
  }
 catch (  final FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  final IOException e) {
    e.printStackTrace();
  }
  for (  final String alias : aliasList) {
    result.put(alias,new MaterialContainer(idList.get(i)));
    i++;
  }
  return result;
}
 

Example 37

From project AdServing, under directory /modules/services/geo/src/main/java/net/mad/ads/services/geo/lucene/.

Source file: GeoIpIndex.java

  29 
vote

private Map<String,Map<String,String>> getLocations(String path) throws IOException {
  if (!path.endsWith("/")) {
    path+="/";
  }
  String filename=path + "GeoLiteCity-Location.csv";
  Map<String,Map<String,String>> result=new HashMap<String,Map<String,String>>();
  BufferedReader br=new BufferedReader(new FileReader(filename));
  CSVReader reader=new CSVReader(br,',','\"',2);
  String[] values;
  while ((values=reader.readNext()) != null) {
    Map<String,String> loc=new HashMap<String,String>();
    loc.put("locid",values[0]);
    loc.put("country",values[1]);
    loc.put("region",values[2]);
    loc.put("city",values[3]);
    loc.put("postalcode",values[4]);
    loc.put("latitude",values[5]);
    loc.put("longitude",values[6]);
    result.put(values[0],loc);
  }
  return result;
}
 

Example 38

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

Source file: NDKDiscoveredPathInfo.java

  29 
vote

private void load(){
  try {
    File infoFile=getInfoFile();
    if (!infoFile.exists())     return;
    long timestamp=IFile.NULL_STAMP;
    List<IPath> includes=new ArrayList<IPath>();
    Map<String,String> defines=new HashMap<String,String>();
    BufferedReader reader=new BufferedReader(new FileReader(infoFile));
    for (String line=reader.readLine(); line != null; line=reader.readLine()) {
switch (line.charAt(0)) {
case 't':
        timestamp=Long.valueOf(line.substring(2));
      break;
case 'i':
    includes.add(Path.fromPortableString(line.substring(2)));
  break;
case 'd':
int n=line.indexOf(',',2);
if (n == -1) defines.put(line.substring(2),"");
 else defines.put(line.substring(2,n),line.substring(n + 1));
break;
}
}
reader.close();
lastUpdate=timestamp;
includePaths=includes.toArray(new IPath[includes.size()]);
symbols=defines;
}
 catch (IOException e) {
Activator.log(e);
}
}
 

Example 39

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

Source file: NotamFragmentBase.java

  29 
vote

private HashMap<String,ArrayList<String>> parseNotams(File notamFile){
  HashMap<String,ArrayList<String>> notams=new HashMap<String,ArrayList<String>>();
  BufferedReader in=null;
  try {
    Set<String> notamIDs=new HashSet<String>();
    in=new BufferedReader(new FileReader(notamFile));
    String notam;
    while ((notam=in.readLine()) != null) {
      String parts[]=notam.split(" ",5);
      String notamID=parts[1];
      if (!notamIDs.contains(notamID)) {
        String keyword=parts[0].equals("!FDC") ? "FDC" : parts[3];
        String subject=DataUtils.getNotamSubjectFromKeyword(keyword);
        ArrayList<String> list=notams.get(subject);
        if (list == null) {
          list=new ArrayList<String>();
        }
        list.add(notam);
        notams.put(subject,list);
        notamIDs.add(notamID);
      }
    }
  }
 catch (  IOException e) {
  }
 finally {
    try {
      if (in != null) {
        in.close();
      }
    }
 catch (    IOException e) {
    }
  }
  return notams;
}
 

Example 40

From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/io/file/.

Source file: FileUtils.java

  29 
vote

/** 
 * Reads a file and returns the lines of it as a list of strings. Handles opening a closing the file. If there are any errors other than that the file does not exist, will return an empty or partial list. Will ignore any line that starts with "#".
 * @param fileName The name of the file to load, required.
 * @return List of lines in the file.
 * @throws FileNotFoundException If the file does not exist.
 */
public static List<String> readFileAsLines(final String fileName) throws FileNotFoundException {
  if (fileName == null || fileName.length() < 1) {
    throw new IllegalArgumentException("Filename may not be null or empty");
  }
  final File file=new File(fileName);
  if (!file.exists()) {
    throw new FileNotFoundException(file.getAbsolutePath());
  }
  final List<String> data=new ArrayList<>();
  BufferedReader in=null;
  try {
    in=new BufferedReader(new FileReader(file));
    while (in.ready()) {
      final String line=in.readLine();
      if (line != null && !line.startsWith("#") && line.length() > 0) {
        data.add(line);
      }
    }
  }
 catch (  final IOException e) {
    log.log(Level.SEVERE,e.getMessage(),e);
  }
 finally {
    if (in != null) {
      try {
        in.close();
      }
 catch (      final IOException e) {
        log.log(Level.SEVERE,e.getMessage(),e);
      }
    }
  }
  log.log(Level.FINER,data.size() + " elements loaded.");
  return data;
}
 

Example 41

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

Source file: ReadXMLObject.java

  29 
vote

/** 
 * Unmarshal the object.
 * @param XML file 
 * @return the Object
 * @throws IOException Signals that an I/O exception has occurred.
 */
public Object getObject(String XMLfile) throws IOException {
  URL url=this.getClass().getClassLoader().getResource(XMLfile);
  File file;
  if (url == null)   file=new File(XMLfile);
 else   file=new File(url.getPath());
  if (file.exists()) {
    char[] buffer=null;
    BufferedReader bufferedReader=new BufferedReader(new FileReader(file));
    buffer=new char[(int)file.length()];
    int i=0;
    int c=bufferedReader.read();
    while (c != -1) {
      buffer[i++]=(char)c;
      c=bufferedReader.read();
    }
    bufferedReader.close();
    return xstream.fromXML(new String(buffer));
  }
 else   throw new IOException("Can not find file - " + XMLfile);
}
 

Example 42

From project android-thaiime, under directory /latinime/src/com/sugree/inputmethod/latin/.

Source file: Utils.java

  29 
vote

private BufferedReader getBufferedReader(){
  createLogFileIfNotExist();
  try {
    return new BufferedReader(new FileReader(mFile));
  }
 catch (  FileNotFoundException e) {
    return null;
  }
}
 

Example 43

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

Source file: MacAddressResolver.java

  29 
vote

private String arpResolve(String host){
  System.out.println("ARPRESOLVE HOST: " + host);
  try {
    InetAddress inet=InetAddress.getByName(host);
    inet.isReachable(500);
    String ipString=inet.getHostAddress();
    BufferedReader br=new BufferedReader(new FileReader("/proc/net/arp"));
    String line="";
    while (true) {
      line=br.readLine();
      if (line == null)       break;
      if (line.startsWith(ipString)) {
        br.close();
        System.out.println("ARPRESOLVE MAC:\n" + line);
        return line.split("\\s+")[3];
      }
    }
    br.close();
    return "";
  }
 catch (  Exception e) {
    return "";
  }
}
 

Example 44

From project AndroidSensorLogger, under directory /libraries/opencsv-2.3-src-with-libs/opencsv-2.3/examples/.

Source file: AddressExample.java

  29 
vote

public static void main(String[] args) throws IOException {
  CSVReader reader=new CSVReader(new FileReader(ADDRESS_FILE));
  String[] nextLine;
  while ((nextLine=reader.readNext()) != null) {
    System.out.println("Name: [" + nextLine[0] + "]\nAddress: ["+ nextLine[1]+ "]\nEmail: ["+ nextLine[2]+ "]");
  }
  CSVReader reader2=new CSVReader(new FileReader(ADDRESS_FILE));
  List<String[]> allElements=reader2.readAll();
  StringWriter sw=new StringWriter();
  CSVWriter writer=new CSVWriter(sw);
  writer.writeAll(allElements);
  System.out.println("\n\nGenerated CSV File:\n\n");
  System.out.println(sw.toString());
}
 

Example 45

From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/.

Source file: DeviceInfoSettings.java

  29 
vote

private String getFormattedKernelVersion(){
  String procVersionStr;
  try {
    BufferedReader reader=new BufferedReader(new FileReader("/proc/version"),256);
    try {
      procVersionStr=reader.readLine();
    }
  finally {
      reader.close();
    }
    final String PROC_VERSION_REGEX="\\w+\\s+" + "\\w+\\s+" + "([^\\s]+)\\s+"+ "\\(([^\\s@]+(?:@[^\\s.]+)?)[^)]*\\)\\s+"+ "\\((?:[^(]*\\([^)]*\\))?[^)]*\\)\\s+"+ "([^\\s]+)\\s+"+ "(?:PREEMPT\\s+)?"+ "(.+)";
    Pattern p=Pattern.compile(PROC_VERSION_REGEX);
    Matcher m=p.matcher(procVersionStr);
    if (!m.matches()) {
      Log.e(TAG,"Regex did not match on /proc/version: " + procVersionStr);
      return "Unavailable";
    }
 else     if (m.groupCount() < 4) {
      Log.e(TAG,"Regex match on /proc/version only returned " + m.groupCount() + " groups");
      return "Unavailable";
    }
 else {
      return (new StringBuilder(m.group(1)).append("\n").append(m.group(2)).append(" ").append(m.group(3)).append("\n").append(m.group(4))).toString();
    }
  }
 catch (  IOException e) {
    Log.e(TAG,"IO Exception when getting kernel version for Device Info screen",e);
    return "Unavailable";
  }
}
 

Example 46

From project android_packages_apps_cmparts, under directory /src/com/cyanogenmod/cmparts/activities/.

Source file: CPUActivity.java

  29 
vote

public static String readOneLine(String fname){
  BufferedReader br;
  String line=null;
  try {
    br=new BufferedReader(new FileReader(fname),512);
    try {
      line=br.readLine();
    }
  finally {
      br.close();
    }
  }
 catch (  Exception e) {
    Log.e(TAG,"IO Exception when reading /sys/ file",e);
  }
  return line;
}
 

Example 47

From project android_packages_apps_SalvageParts, under directory /src/com/salvagemod/salvageparts/activities/.

Source file: PerformanceActivity.java

  29 
vote

public static String readOneLine(String fname){
  BufferedReader br;
  String line=null;
  try {
    br=new BufferedReader(new FileReader(fname),512);
    try {
      line=br.readLine();
    }
  finally {
      br.close();
    }
  }
 catch (  Exception e) {
    Log.e(TAG,"IO Exception when reading /sys/ file",e);
  }
  return line;
}
 

Example 48

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

Source file: Device.java

  29 
vote

private void detectSystemFs(){
  try {
    BufferedReader in=new BufferedReader(new FileReader("/proc/mounts"),8192);
    String line;
    String parsedFs;
    while ((line=in.readLine()) != null) {
      if (line.matches(".*system.*")) {
        Log.i(TAG,"/system mount point: " + line);
        parsedFs=line.split(" ")[2].trim();
        if (parsedFs.equals("ext2") || parsedFs.equals("ext3") || parsedFs.equals("ext4")) {
          Log.i(TAG,"/system filesystem support extended attributes");
          mFileSystem=FileSystem.EXTFS;
          return;
        }
      }
    }
    in.close();
  }
 catch (  Exception e) {
    Log.e(TAG,"Impossible to parse /proc/mounts");
    e.printStackTrace();
  }
  Log.i(TAG,"/system filesystem doesn't support extended attributes");
  mFileSystem=FileSystem.UNSUPPORTED;
}
 

Example 49

From project android_packages_apps_VoiceDialer_2, under directory /src/com/android/voicedialer/.

Source file: VoiceContact.java

  29 
vote

/** 
 * @param contactsFile File containing a list of names,one per line.
 * @return a List of {@link VoiceContact} in a File.
 */
public static List<VoiceContact> getVoiceContactsFromFile(File contactsFile){
  if (false)   Log.d(TAG,"getVoiceContactsFromFile " + contactsFile);
  List<VoiceContact> contacts=new ArrayList<VoiceContact>();
  BufferedReader br=null;
  try {
    br=new BufferedReader(new FileReader(contactsFile),8192);
    String name;
    for (int id=1; (name=br.readLine()) != null; id++) {
      contacts.add(new VoiceContact(name,id,ID_UNDEFINED,ID_UNDEFINED,ID_UNDEFINED,ID_UNDEFINED,ID_UNDEFINED));
    }
  }
 catch (  IOException e) {
    if (false)     Log.d(TAG,"getVoiceContactsFromFile failed " + e);
  }
 finally {
    try {
      br.close();
    }
 catch (    IOException e) {
      if (false)       Log.d(TAG,"getVoiceContactsFromFile failed during close " + e);
    }
  }
  if (false)   Log.d(TAG,"getVoiceContactsFromFile " + contacts.size());
  return contacts;
}
 

Example 50

From project android_packages_inputmethods_LatinIME, under directory /java/src/com/android/inputmethod/latin/.

Source file: Utils.java

  29 
vote

private BufferedReader getBufferedReader(){
  createLogFileIfNotExist();
  try {
    return new BufferedReader(new FileReader(mFile));
  }
 catch (  FileNotFoundException e) {
    return null;
  }
}
 

Example 51

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

Source file: Connection.java

  29 
vote

private Payload doInBackgroundSyncDeckFromPayload(Payload data){
  Log.i(AnkiDroidApp.TAG,"SyncDeckFromPayload");
  Deck deck=(Deck)data.data[0];
  SyncClient client=new SyncClient(deck);
  BufferedReader bufPython;
  try {
    bufPython=new BufferedReader(new FileReader("/sdcard/jsonObjectPython.txt"));
    JSONObject payloadReply=new JSONObject(bufPython.readLine());
    client.applyPayloadReply(payloadReply);
    deck.setLastLoaded(deck.getModified());
    deck.commitToDB();
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
catch (  JSONException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  Log.i(AnkiDroidApp.TAG,"Synchronization from payload finished!");
  return data;
}
 

Example 52

From project ant4eclipse, under directory /org.ant4eclipse.lib.pde.test/src-framework/org/ant4eclipse/testframework/.

Source file: EchoLogfile.java

  29 
vote

public EchoLogfile(String echoLogfileName) throws FileNotFoundException {
  Assert.assertNotNull(echoLogfileName);
  this._echoLogfileName=echoLogfileName;
  File echoLogfile=new File(echoLogfileName);
  Assert.assertTrue(echoLogfile.exists());
  this._reader=new BufferedReader(new FileReader(echoLogfile));
}
 

Example 53

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

Source file: CoverageBuilder.java

  29 
vote

private EnumMap<CoverageReport.Column,Integer> loadCoverageInfo(CoverageReport report){
  BufferedReader reader=null;
  try {
    reader=new BufferedReader(new FileReader(report.getOutputFile(outputDir)));
    String line=null;
    for (int i=0; i < 6 && (line=reader.readLine()) != null; i++) {
      ;
    }
    EnumMap<CoverageReport.Column,Integer> info=new EnumMap<CoverageReport.Column,Integer>(CoverageReport.Column.class);
    if (line != null) {
      for (      CoverageReport.Column o : report.getColumns()) {
        int p=line.indexOf('%');
        if (p != -1) {
          int val=Integer.parseInt(line.substring(0,p).trim());
          info.put(o,val);
          p=line.indexOf(')');
          line=line.substring(p + 2);
        }
      }
    }
    return info;
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
 finally {
    StreamUtils.close(reader);
  }
}
 

Example 54

From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/oneoff/.

Source file: XmlWriter.java

  29 
vote

private void createHtmlFile(File newDir,ComparisonResult cr) throws IOException {
  String templateName=cr.isEqualsImages() ? "template_same_images.html" : "template_different_images.html";
  BufferedWriter writer=new BufferedWriter(new FileWriter(new File(newDir,"result.html")));
  BufferedReader template=new BufferedReader(new FileReader(templateName));
  String line;
  while ((line=template.readLine()) != null) {
    writer.write(replacePlaceholders(cr,newDir,line));
  }
  template.close();
  writer.close();
}
 

Example 55

From project artimate, under directory /artimate-demo/src/main/java/com/jdotsoft/jarloader/.

Source file: JarClassLoader.java

  29 
vote

/** 
 * Deletes temporary files listed in the file. The method is called on shutdown().
 * @param fileCfg file with temporary files list.
 */
private void deleteOldTemp(File fileCfg){
  BufferedReader reader=null;
  try {
    int count=0;
    reader=new BufferedReader(new FileReader(fileCfg));
    String sLine;
    while ((sLine=reader.readLine()) != null) {
      File file=new File(sLine);
      if (!file.exists()) {
        continue;
      }
      if (file.delete()) {
        count++;
      }
 else {
        hsDeleteOnExit.add(file);
      }
    }
    logDebug(LogArea.CONFIG,"Deleted %d old temp files listed in %s",count,fileCfg.getAbsolutePath());
  }
 catch (  IOException e) {
  }
 finally {
    if (reader != null) {
      try {
        reader.close();
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 56

From project asterisk-java, under directory /src/main/java/org/asteriskjava/config/.

Source file: ConfigFileReader.java

  29 
vote

public ConfigFile readFile(String configfile) throws IOException, ConfigParseException {
  final ConfigFile result;
  final BufferedReader reader;
  reader=new BufferedReader(new FileReader(configfile));
  try {
    readFile(configfile,reader);
  }
  finally {
    try {
      reader.close();
    }
 catch (    Exception e) {
    }
  }
  result=new ConfigFileImpl(configfile,new TreeMap<String,Category>(categories));
  return result;
}
 

Example 57

From project authme-2.0, under directory /src/uk/org/whoami/authme/datasource/.

Source file: FileDataSource.java

  29 
vote

@Override public synchronized boolean isAuthAvailable(String user){
  BufferedReader br=null;
  try {
    br=new BufferedReader(new FileReader(source));
    String line;
    while ((line=br.readLine()) != null) {
      String[] args=line.split(":");
      if (args.length > 1 && args[0].equals(user)) {
        return true;
      }
    }
  }
 catch (  FileNotFoundException ex) {
    ConsoleLogger.showError(ex.getMessage());
    return false;
  }
catch (  IOException ex) {
    ConsoleLogger.showError(ex.getMessage());
    return false;
  }
 finally {
    if (br != null) {
      try {
        br.close();
      }
 catch (      IOException ex) {
      }
    }
  }
  return false;
}
 

Example 58

From project AuthMe-Reloaded, under directory /src/main/java/uk/org/whoami/authme/datasource/.

Source file: FileDataSource.java

  29 
vote

@Override public synchronized boolean isAuthAvailable(String user){
  BufferedReader br=null;
  try {
    br=new BufferedReader(new FileReader(source));
    String line;
    while ((line=br.readLine()) != null) {
      String[] args=line.split(":");
      if (args.length > 1 && args[0].equals(user)) {
        return true;
      }
    }
  }
 catch (  FileNotFoundException ex) {
    ConsoleLogger.showError(ex.getMessage());
    return false;
  }
catch (  IOException ex) {
    ConsoleLogger.showError(ex.getMessage());
    return false;
  }
 finally {
    if (br != null) {
      try {
        br.close();
      }
 catch (      IOException ex) {
      }
    }
  }
  return false;
}
 

Example 59

From project AuthMe-Reloaded-Charge-fix, under directory /src/uk/org/whoami/authme/datasource/.

Source file: FileDataSource.java

  29 
vote

@Override public synchronized boolean isAuthAvailable(String user){
  BufferedReader br=null;
  try {
    br=new BufferedReader(new FileReader(source));
    String line;
    while ((line=br.readLine()) != null) {
      String[] args=line.split(":");
      if (args.length > 1 && args[0].equals(user)) {
        return true;
      }
    }
  }
 catch (  FileNotFoundException ex) {
    ConsoleLogger.showError(ex.getMessage());
    return false;
  }
catch (  IOException ex) {
    ConsoleLogger.showError(ex.getMessage());
    return false;
  }
 finally {
    if (br != null) {
      try {
        br.close();
      }
 catch (      IOException ex) {
      }
    }
  }
  return false;
}
 

Example 60

From project aws-tasks, under directory /src/test/java/datameer/awstasks/ssh/.

Source file: JschRunnerTest.java

  29 
vote

@Test public void testCreate() throws Exception {
  File file=_tempFolder.newFile("remoteFile");
  file.delete();
  String message="hello world";
  JschRunner jschRunner=createJschRunner();
  OutputStream outputStream=jschRunner.createFile(file.getAbsolutePath(),message.getBytes().length);
  outputStream.write(message.getBytes());
  outputStream.close();
  BufferedReader reader=new BufferedReader(new FileReader(file));
  String line=reader.readLine();
  assertEquals(message,line);
  assertNull(reader.readLine());
  reader.close();
}
 

Example 61

From project azkaban, under directory /azkaban/src/java/azkaban/scheduler/.

Source file: LocalFileScheduleLoader.java

  29 
vote

@SuppressWarnings("unchecked") private List<ScheduledJob> loadFromFile(File schedulefile){
  BufferedReader reader=null;
  try {
    reader=new BufferedReader(new FileReader(schedulefile));
  }
 catch (  FileNotFoundException e) {
    logger.error("Error loading schedule file ",e);
  }
  List<ScheduledJob> scheduleList=new ArrayList<ScheduledJob>();
  HashMap<String,Object> schedule;
  try {
    schedule=(HashMap<String,Object>)JSONUtils.fromJSONStream(reader);
  }
 catch (  Exception e) {
    schedule=loadLegacyFile(schedulefile);
  }
 finally {
    try {
      reader.close();
    }
 catch (    IOException e) {
    }
  }
  ArrayList<Object> array=(ArrayList<Object>)schedule.get("schedule");
  for (int i=0; i < array.size(); ++i) {
    HashMap<String,Object> schedItem=(HashMap<String,Object>)array.get(i);
    ScheduledJob sched=createScheduledJob(schedItem);
    if (sched != null) {
      scheduleList.add(sched);
    }
  }
  return scheduleList;
}
 

Example 62

From project babel, under directory /src/babel/prep/langidtime/.

Source file: URLAndContentsLangTimeExtractor.java

  29 
vote

private static String readFileAsString(String path) throws Exception {
  StringBuilder fileData=new StringBuilder();
  BufferedReader reader=new BufferedReader(new FileReader(path));
  char[] buf=new char[1024];
  int numRead=0;
  while ((numRead=reader.read(buf)) != -1) {
    String readData=String.valueOf(buf,0,numRead);
    fileData.append(readData);
  }
  reader.close();
  return fileData.toString();
}
 

Example 63

From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.

Source file: Signer.java

  29 
vote

/** 
 * Generates a canonicalized JSON format of the given object, and put the signature in it. Because it mutates the signed object itself, validating the signature needs a bit of work, but this enables a signature to be added transparently.
 * @return The same value passed as the argument so that the method can be used like a filter.
 */
public JSONObject sign(JSONObject o) throws GeneralSecurityException, IOException, CmdLineException {
  if (!isConfigured())   return o;
  JSONObject sign=new JSONObject();
  List<X509Certificate> certs=getCertificateChain();
  X509Certificate signer=certs.get(0);
  PrivateKey key=((KeyPair)new PEMReader(new FileReader(privateKey)).readObject()).getPrivate();
  SignatureGenerator sg=new SignatureGenerator(signer,key);
  o.writeCanonical(new OutputStreamWriter(sg.getOut(),"UTF-8"));
  sg.addRecord(sign,"");
  OutputStream raw=new NullOutputStream();
  if (canonical != null) {
    raw=new FileOutputStream(canonical);
  }
  sg=new SignatureGenerator(signer,key);
  o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(sg.getOut(),raw),"UTF-8")).close();
  sg.addRecord(sign,"correct_");
  JSONArray a=new JSONArray();
  for (  X509Certificate cert : certs)   a.add(new String(Base64.encodeBase64(cert.getEncoded())));
  sign.put("certificates",a);
  o.put("signature",sign);
  return o;
}
 

Example 64

From project Battlepath, under directory /src/interaction/.

Source file: OpenGLRenderer.java

  29 
vote

private void setupShaders(GL2 gl){
  int f=gl.glCreateShader(GL2.GL_FRAGMENT_SHADER);
  BufferedReader brf=null;
  try {
    brf=new BufferedReader(new FileReader("src/shader/shockwave.glsl"));
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
    return;
  }
  String[] fsrc={""};
  String line;
  try {
    while ((line=brf.readLine()) != null) {
      fsrc[0]+=line + "\n";
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
    return;
  }
  int len[]=new int[1];
  len[0]=fsrc[0].length();
  gl.glShaderSource(f,1,fsrc,len,0);
  gl.glCompileShader(f);
  checkLogInfo(gl,f);
  int shaderprogram=gl.glCreateProgram();
  gl.glAttachShader(shaderprogram,f);
  gl.glLinkProgram(shaderprogram);
  gl.glValidateProgram(shaderprogram);
  gl.glUseProgram(shaderprogram);
  radiusUniform=gl.glGetUniformLocation(shaderprogram,"radius");
  posUniform=gl.glGetUniformLocation(shaderprogram,"pos");
  numberUniform=gl.glGetUniformLocation(shaderprogram,"number");
}
 

Example 65

From project BazaarUtils, under directory /src/org/alexd/jsonrpc/.

Source file: JSONRPCHttpClient.java

  29 
vote

protected JSONObject getCachedResult(String paramHash,Context c,int cacheTime) throws JSONException {
  File vCache=CacheUtils.getCacheFile(paramHash + ".json",c,cacheTime);
  if (vCache != null) {
    try {
      StringBuffer sb=new StringBuffer();
      BufferedReader reader=new BufferedReader(new FileReader(vCache));
      String line=null;
      while ((line=reader.readLine()) != null) {
        sb.append(line);
      }
      return new JSONObject(sb.toString());
    }
 catch (    IOException e) {
      Log.w(TAG,"BazaarUtils :: getCachedResult",e);
    }
  }
  return null;
}
 

Example 66

From project BG7, under directory /src/com/era7/bioinfo/annotation/.

Source file: FixFastaHeaders.java

  29 
vote

public static void main(String[] args){
  if (args.length != 3) {
    System.out.println("This program expects three parameters: \n" + "1. Input FASTA file \n" + "2. Output FASTA file\n"+ "3. Project prefix\n");
  }
 else {
    String inFileString=args[0];
    String outFileString=args[1];
    String projectPrefix=args[2];
    File inFile=new File(inFileString);
    File outFile=new File(outFileString);
    try {
      BufferedWriter outBuff=new BufferedWriter(new FileWriter(outFile));
      BufferedReader reader=new BufferedReader(new FileReader(inFile));
      String line;
      int idCounter=1;
      while ((line=reader.readLine()) != null) {
        if (line.startsWith(">")) {
          outBuff.write(">" + projectPrefix + addUglyZeros(idCounter)+ " |"+ line.substring(1)+ "\n");
          idCounter++;
        }
 else {
          outBuff.write(line + "\n");
        }
      }
      reader.close();
      outBuff.close();
      System.out.println("Output fasta file created successfully! :D");
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
  }
}
 

Example 67

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

Source file: JobEntryPigScriptExecutorTest.java

  29 
vote

@Test public void testRegressionTutorialLocal() throws Exception {
  HadoopConfigurationProvider provider=new HadoopConfigurationProvider(){
    HadoopConfiguration config=new HadoopConfiguration(VFS.getManager().resolveFile("ram:///"),"test","test",new CommonHadoopShim(),new CommonSqoopShim(),new CommonPigShim());
    @Override public boolean hasConfiguration(    String id){
      return true;
    }
    @Override public List<? extends HadoopConfiguration> getConfigurations(){
      return Arrays.asList(config);
    }
    @Override public HadoopConfiguration getConfiguration(    String id) throws ConfigurationException {
      return config;
    }
    @Override public HadoopConfiguration getActiveConfiguration() throws ConfigurationException {
      return config;
    }
  }
;
  Field providerField=HadoopConfigurationBootstrap.class.getDeclaredField("provider");
  providerField.setAccessible(true);
  providerField.set(null,provider);
  System.setProperty("KETTLE_PLUGIN_CLASSES","org.pentaho.di.job.entries.pig.JobEntryPigScriptExecutor");
  KettleEnvironment.init();
  JobMeta meta=new JobMeta("test-res/pig/pigTest.kjb",null);
  Job job=new Job(null,meta);
  job.start();
  job.waitUntilFinished();
  BufferedReader br=new BufferedReader(new FileReader("bin/test/pig/script1-local-results.txt/part-r-00000"));
  StringBuffer pigOutput=readResource(br);
  assertEquals(m_reference.toString(),pigOutput.toString());
}
 

Example 68

From project Bit4Tat, under directory /Bit4Tat/src/com/Bit4Tat/.

Source file: WalletFileIO.java

  29 
vote

/** 
 * Opens the filename passed to the constructor for reading.
 */
public void openReader(){
  try {
    if (filename != null) {
      in=new BufferedReader(new FileReader(filename));
      reader=true;
    }
  }
 catch (  IOException e) {
    System.err.println("There was a problem opening the requested file " + filename + ".");
    System.err.println("Error: " + e);
    System.exit(1);
  }
}
 

Example 69

From project BlameSubversion-plugin, under directory /src/main/java/hudson/scm/.

Source file: BlameSubversionSCM.java

  29 
vote

/** 
 * Reads the revision file of the specified build (or the closest, if the flag is so specified.)
 * @param findClosest If true, this method will go back the build history until it finds a revision file. A build may not have a revision file for any number of reasons (such as failure, interruption, etc.)
 * @return map from {@link SvnInfo#url Subversion URL} to its revision.
 */
static Map<String,Long> parseRevisionFile(AbstractBuild<?,?> build,boolean findClosest) throws IOException {
  Map<String,Long> revisions=new HashMap<String,Long>();
  if (findClosest) {
    for (AbstractBuild<?,?> b=build; b != null; b=b.getPreviousBuild()) {
      if (getRevisionFile(b).exists()) {
        build=b;
        break;
      }
    }
  }
{
    File file=getRevisionFile(build);
    if (!file.exists())     return revisions;
    BufferedReader br=new BufferedReader(new FileReader(file));
    try {
      String line;
      while ((line=br.readLine()) != null) {
        int index=line.lastIndexOf('/');
        if (index < 0) {
          continue;
        }
        try {
          revisions.put(line.substring(0,index),Long.parseLong(line.substring(index + 1)));
        }
 catch (        NumberFormatException e) {
        }
      }
    }
  finally {
      br.close();
    }
  }
  return revisions;
}
 

Example 70

From project blur_1, under directory /src/com/northps/blur/impl/.

Source file: ITrieNode.java

  29 
vote

public void loadDictionary(File dictionary) throws Exception {
  try {
    BufferedReader is=null;
    try {
      is=new BufferedReader(new FileReader(dictionary));
      String line=null;
      while ((line=is.readLine()) != null) {
        this.attach(line);
      }
    }
  finally {
      is.close();
    }
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
    throw e;
  }
catch (  IOException e) {
    e.printStackTrace();
    throw e;
  }
}
 

Example 71

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

Source file: FileWriterSourceTests.java

  29 
vote

@Test public void testNoResource() throws IOException {
  File outputFile=File.createTempFile("ItemWriterTest-",".csv");
  outputFile.deleteOnExit();
  String outputFileName=outputFile.getAbsolutePath();
  FileWriterSource source=new FileWriterSource();
  JobParameters params=mock(JobParameters.class);
  when(params.getString("output.file")).thenReturn(outputFileName);
  StepExecution execution=mock(StepExecution.class);
  when(execution.getJobParameters()).thenReturn(params);
  source.initialise(execution);
  final String testString="testDefaultResource";
  source.getWriter().write(testString);
  source.close();
  BufferedReader reader=new BufferedReader(new FileReader(outputFile));
  assertThat(reader.readLine(),is(testString));
  reader.close();
}
 

Example 72

From project Calendar-Application, under directory /calendar/.

Source file: Data.java

  29 
vote

/** 
 * Initialise the contacts collection, This loads contacts from the CSV file and saves them into the collection. 
 * @throws Exception in an error occurs, eg while reading the file
 */
private static boolean initContacts() throws Exception {
  try {
    File contacts_file=new File("data/contacts.csv");
    if (!contacts_file.exists())     contacts_file.createNewFile();
    CSVReader reader=new CSVReader(new FileReader(contacts_file));
    String[] nextLine;
    int line=0;
    while ((nextLine=reader.readNext()) != null) {
      line++;
      if (nextLine.length != Contact.NO_FIELDS) {
        throw new Exception("Wrong format for csv file " + "contacts.csv at line " + line);
      }
 else {
        m_contacts.Add(new Contact(Data.ParseInt(nextLine[Contact.IDX_ID]),nextLine[Contact.IDX_NAME],Data.ParseDate(nextLine[Contact.IDX_DOB]),nextLine[Contact.IDX_LANDPHONE],nextLine[Contact.IDX_MOBILEPHONE],nextLine[Contact.IDX_WORKPHONE],nextLine[Contact.IDX_EMAIL],nextLine[Contact.IDX_WORKEMAIL],nextLine[Contact.IDX_WEBSITE]));
        int id=Data.ParseInt(nextLine[Contact.IDX_ID]);
        if (id > m_max_contact_id)         m_max_contact_id=id;
      }
    }
  }
 catch (  IOException e) {
    throw new Exception("Something wrong with file reading... Please " + "contact an administrator");
  }
  return true;
}
 

Example 73

From project callmeter, under directory /src/de/ub0r/android/callmeter/data/.

Source file: Device.java

  29 
vote

/** 
 * Read a  {@link File} an return its name+its first line.
 * @param f filename
 * @return name + \n + 1st line
 */
private static String readFile(final String f){
  StringBuilder sb=new StringBuilder();
  try {
    BufferedReader r=new BufferedReader(new FileReader(f),BUFSIZE);
    sb.append("read: " + f);
    sb.append("\t");
    sb.append(r.readLine());
    r.close();
  }
 catch (  IOException e) {
    Log.e(TAG,"error reading file: " + f,e);
  }
  return sb.toString();
}
 

Example 74

From project capedwarf-blue, under directory /testsuite/src/test/java/org/jboss/test/capedwarf/testsuite/cache/test/.

Source file: PersistingTest.java

  29 
vote

protected Long readMarker() throws Exception {
  final File marker=getMarker();
  if (marker.exists() == false)   return null;
  long id;
  try {
    BufferedReader reader=new BufferedReader(new FileReader(marker));
    try {
      id=Long.parseLong(reader.readLine());
    }
  finally {
      reader.close();
    }
  }
  finally {
    Assert.assertTrue(marker.delete());
  }
  return id;
}
 

Example 75

From project Carnivore, under directory /net/sourceforge/jpcap/util/.

Source file: FileUtility.java

  29 
vote

public static String readFile(String filename) throws IOException {
  String readString="";
  String tmp;
  File f=new File(filename);
  char[] readIn=new char[(new Long(f.length())).intValue()];
  BufferedReader in=new BufferedReader(new FileReader(f));
  in.read(readIn);
  readString=new String(readIn);
  in.close();
  return readString;
}
 

Example 76

From project CCR-Validator, under directory /src/main/java/org/openhealthdata/validation/.

Source file: CCRV1SchemaValidator.java

  29 
vote

private void validate(File src){
  ccr=null;
  try {
    SAXSource source=new SAXSource(new InputSource(new FileReader(src)));
    validator.validate(source);
    Document xml=parseFile(src,false);
    if (xml != null) {
      JAXBContext jc=JAXBContext.newInstance("org.astm.ccr");
      Unmarshaller um=jc.createUnmarshaller();
      ccr=(ContinuityOfCareRecord)um.unmarshal(xml);
    }
  }
 catch (  SAXException e) {
    logger.log(Level.SEVERE,"Not Valid CCR XML: " + e.getMessage());
  }
catch (  IOException e) {
    logger.log(Level.SEVERE,"Exception during validating",e);
    e.printStackTrace();
  }
catch (  JAXBException e) {
    logger.log(Level.SEVERE,"Exception during unmarshalling XML DOM",e);
    e.printStackTrace();
  }
}
 

Example 77

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

Source file: Tools.java

  29 
vote

public static AffineTransform loadWorldFile(String filename) throws IOException {
  BufferedReader reader=new BufferedReader(new FileReader(filename));
  try {
    double[] flatMatrix=new double[6];
    new AffineTransform().getMatrix(flatMatrix);
    for (int i=0; i < flatMatrix.length; i++) {
      final String parameter=reader.readLine();
      if (parameter == null) {
        throw new IOException("Could not read world file: Missing a parameter.");
      }
      try {
        flatMatrix[i]=Double.valueOf(parameter);
      }
 catch (      NumberFormatException e) {
        IOException ioException=new IOException("Could not read world file. " + e.getMessage());
        ioException.initCause(e);
        throw ioException;
      }
    }
    return new AffineTransform(flatMatrix);
  }
  finally {
    reader.close();
  }
}