List of usage examples for java.io FileNotFoundException getCause
public synchronized Throwable getCause()
From source file:com.aliyun.odps.mapred.cli.Cli.java
public static void main(String[] args) { SessionState ss = SessionState.get(); OptionParser parser = new OptionParser(ss); try {// w w w . j a v a 2s .com parser.parse(args); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (ClassNotFoundException e) { System.err.println("Class not found:" + e.getMessage()); System.exit(-1); } catch (ParseException e) { System.err.println(e.getMessage()); parser.usage(); System.exit(-1); } catch (OdpsException e) { System.err.println(e.getMessage()); System.exit(-1); } try { Method main = parser.getMainClass().getMethod("main", String[].class); main.invoke(null, (Object) parser.getArguments()); } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t != null && t instanceof OdpsException) { OdpsException ex = (OdpsException) t; System.err.println(ex.getErrorCode() + ":" + ex.getMessage()); System.exit(-1); } else { throw new RuntimeException("Unknown error", e); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:de.tudarmstadt.ukp.dariah.pipeline.RunPipeline.java
public static void main(String[] args) { Date startDate = new Date(); PrintStream ps;/*from www.j a v a2s . c o m*/ try { ps = new PrintStream("error.log"); System.setErr(ps); } catch (FileNotFoundException e) { System.out.println("Errors cannot be redirected"); } try { if (!parseArgs(args)) { System.out.println("Usage: java -jar pipeline.jar -help"); System.out.println("Usage: java -jar pipeline.jar -input <Input File> -output <Output Folder>"); System.out.println( "Usage: java -jar pipeline.jar -config <Config File> -input <Input File> -output <Output Folder>"); return; } } catch (ParseException e) { e.printStackTrace(); System.out.println( "Error when parsing command line arguments. Use\njava -jar pipeline.jar -help\n to get further information"); System.out.println("See error.log for further details"); return; } LinkedList<String> configFiles = new LinkedList<>(); String configFolder = "configs/"; configFiles.add(configFolder + "default.properties"); //Language dependent properties file String path = configFolder + "default_" + optLanguage + ".properties"; File f = new File(path); if (f.exists()) { configFiles.add(path); } else { System.out.println("Language config file: " + path + " not found"); } String[] configFileArg = new String[0]; for (int i = 0; i < args.length - 1; i++) { if (args[i].equals("-config")) { configFileArg = args[i + 1].split("[,;]"); break; } } for (String configFile : configFileArg) { f = new File(configFile); if (f.exists()) { configFiles.add(configFile); } else { //Check in configs folder path = configFolder + configFile; f = new File(path); if (f.exists()) { configFiles.add(path); } else { System.out.println("Config file: " + configFile + " not found"); return; } } } for (String configFile : configFiles) { try { parseConfig(configFile); } catch (Exception e) { e.printStackTrace(); System.out.println("Exception when parsing config file: " + configFile); System.out.println("See error.log for further details"); } } printConfiguration(configFiles.toArray(new String[0])); try { // Read in the input files String defaultFileExtension = (optReader == ReaderType.XML) ? ".xml" : ".txt"; GlobalFileStorage.getInstance().readFilePaths(optInput, defaultFileExtension, optOutput, optResume); System.out.println("Process " + GlobalFileStorage.getInstance().size() + " files"); CollectionReaderDescription reader; if (optReader == ReaderType.XML) { reader = createReaderDescription(XmlReader.class, XmlReader.PARAM_LANGUAGE, optLanguage); } else { reader = createReaderDescription(TextReaderWithInfo.class, TextReaderWithInfo.PARAM_LANGUAGE, optLanguage); } AnalysisEngineDescription paragraph = createEngineDescription(ParagraphSplitter.class, ParagraphSplitter.PARAM_SPLIT_PATTERN, (optParagraphSingleLineBreak) ? ParagraphSplitter.SINGLE_LINE_BREAKS_PATTERN : ParagraphSplitter.DOUBLE_LINE_BREAKS_PATTERN); AnalysisEngineDescription seg = createEngineDescription(optSegmenterCls, optSegmenterArguments); AnalysisEngineDescription paragraphSentenceCorrector = createEngineDescription( ParagraphSentenceCorrector.class); AnalysisEngineDescription frenchQuotesSeg = createEngineDescription(PatternBasedTokenSegmenter.class, PatternBasedTokenSegmenter.PARAM_PATTERNS, "+|[]"); AnalysisEngineDescription quotesSeg = createEngineDescription(PatternBasedTokenSegmenter.class, PatternBasedTokenSegmenter.PARAM_PATTERNS, "+|[\"\"]"); AnalysisEngineDescription posTagger = createEngineDescription(optPOSTaggerCls, optPOSTaggerArguments); AnalysisEngineDescription lemma = createEngineDescription(optLemmatizerCls, optLemmatizerArguments); AnalysisEngineDescription chunker = createEngineDescription(optChunkerCls, optChunkerArguments); AnalysisEngineDescription morph = createEngineDescription(optMorphTaggerCls, optMorphTaggerArguments); AnalysisEngineDescription hyphenation = createEngineDescription(optHyphenationCls, optHyphenationArguments); AnalysisEngineDescription depParser = createEngineDescription(optDependencyParserCls, optDependencyParserArguments); AnalysisEngineDescription constituencyParser = createEngineDescription(optConstituencyParserCls, optConstituencyParserArguments); AnalysisEngineDescription ner = createEngineDescription(optNERCls, optNERArguments); AnalysisEngineDescription directSpeech = createEngineDescription(DirectSpeechAnnotator.class, DirectSpeechAnnotator.PARAM_START_QUOTE, optStartQuote); AnalysisEngineDescription srl = createEngineDescription(optSRLCls, optSRLArguments); //Requires DKPro 1.8.0 AnalysisEngineDescription coref = createEngineDescription(optCorefCls, optCorefArguments); //StanfordCoreferenceResolver.PARAM_POSTPROCESSING, true AnalysisEngineDescription writer = createEngineDescription(DARIAHWriter.class, DARIAHWriter.PARAM_TARGET_LOCATION, optOutput, DARIAHWriter.PARAM_OVERWRITE, true); AnalysisEngineDescription annWriter = createEngineDescription(AnnotationWriter.class); AnalysisEngineDescription noOp = createEngineDescription(NoOpAnnotator.class); System.out.println("\nStart running the pipeline (this may take a while)..."); while (!GlobalFileStorage.getInstance().isEmpty()) { try { SimplePipeline.runPipeline(reader, paragraph, (optSegmenter) ? seg : noOp, paragraphSentenceCorrector, frenchQuotesSeg, quotesSeg, (optPOSTagger) ? posTagger : noOp, (optLemmatizer) ? lemma : noOp, (optChunker) ? chunker : noOp, (optMorphTagger) ? morph : noOp, (optHyphenation) ? hyphenation : noOp, directSpeech, (optDependencyParser) ? depParser : noOp, (optConstituencyParser) ? constituencyParser : noOp, (optNER) ? ner : noOp, (optSRL) ? srl : noOp, //Requires DKPro 1.8.0 (optCoref) ? coref : noOp, writer // ,annWriter ); } catch (OutOfMemoryError e) { System.out.println("Out of Memory at file: " + GlobalFileStorage.getInstance().getLastPolledFile().getAbsolutePath()); } } Date enddate = new Date(); double duration = (enddate.getTime() - startDate.getTime()) / (1000 * 60.0); System.out.println("---- DONE -----"); System.out.printf("All files processed in %.2f minutes", duration); } catch (ResourceInitializationException e) { System.out.println("Error when initializing the pipeline."); if (e.getCause() instanceof FileNotFoundException) { System.out.println("File not found. Maybe the input / output path is incorrect?"); System.out.println(e.getCause().getMessage()); } e.printStackTrace(); System.out.println("See error.log for further details"); } catch (UIMAException e) { e.printStackTrace(); System.out.println("Error in the pipeline."); System.out.println("See error.log for further details"); } catch (IOException e) { e.printStackTrace(); System.out .println("Error while reading or writing to the file system. Maybe some paths are incorrect?"); System.out.println("See error.log for further details"); } }
From source file:com.hazelcast.qasonar.utils.WhiteListBuilder.java
private static JsonArray getJsonArrayFromFile(String propertyFileName) { BufferedReader bufferedReader = null; FileReader fileReader = null; try {/*from w w w . j a v a 2 s . c o m*/ fileReader = new FileReader(propertyFileName); bufferedReader = new BufferedReader(fileReader); Gson gson = new Gson(); return gson.fromJson(bufferedReader, JsonArray.class); } catch (FileNotFoundException e) { throw new IllegalArgumentException("Could not read whitelist from file " + propertyFileName, e.getCause()); } finally { closeQuietly(fileReader); closeQuietly(bufferedReader); } }
From source file:com.idiro.utils.db.mysql.MySqlUtils.java
public static boolean changeFormatAfterExport(File in, File out, char delimiter, Collection<String> header, Collection<String> quotes) { //We expect that in is a csv file and out a file boolean ok = true; FileChecker fChIn = new FileChecker(in), fChOut = new FileChecker(out); if (!fChIn.isFile()) { logger.error(fChIn.getFilename() + " is not a directory or does not exist"); return false; }/*from w w w .ja v a2s . c o m*/ if (fChOut.exists()) { if (fChOut.isDirectory()) { logger.error(fChOut.getFilename() + " is a directory"); return false; } logger.warn(fChOut.getFilename() + " already exists, it will be removed"); String out_str = out.getAbsolutePath(); out.delete(); out = new File(out_str); } BufferedWriter bw = null; BufferedReader br = null; try { bw = new BufferedWriter(new FileWriter(out)); logger.debug("read the file" + in.getAbsolutePath()); br = new BufferedReader(new FileReader(in)); String strLine; if (header != null && !header.isEmpty()) { Iterator<String> it = header.iterator(); String headerLine = it.next(); while (it.hasNext()) { headerLine += delimiter + it.next(); } bw.write(headerLine + "\n"); } //Read File Line By Line while ((strLine = br.readLine()) != null) { bw.write(DataFileUtils.addQuotesToLine( DataFileUtils.getCleanLine(strLine.replace(',', delimiter), delimiter, delimiter), quotes, delimiter) + "\n"); } br.close(); bw.close(); } catch (FileNotFoundException e1) { logger.error(e1.getCause() + " " + e1.getMessage()); logger.error("Fail to read " + in.getAbsolutePath()); ok = false; } catch (IOException e1) { logger.error("Error writting, reading on the filesystem from the directory" + fChIn.getFilename() + " to the file " + fChOut.getFilename()); ok = false; } if (ok) { in.delete(); } return ok; }
From source file:org.springframework.data.hadoop.pig.PigUtils.java
private static void registerScriptForPig07X(PigServer pig, InputStream in, Map<String, String> params) throws IOException { try {/*from w w w . j a v a 2s. co m*/ // transform the map type to list type which can been accepted by ParameterSubstitutionPreprocessor List<String> paramList = new ArrayList<String>(); if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { paramList.add(entry.getKey() + "=" + entry.getValue()); } } // do parameter substitution ParameterSubstitutionPreprocessor psp = new ParameterSubstitutionPreprocessor(50); StringWriter writer = new StringWriter(); psp.genSubstitutedFile(new BufferedReader(new InputStreamReader(in)), writer, null, null); GruntParser grunt = new GruntParser(new StringReader(writer.toString())); grunt.setInteractive(false); grunt.setParams(pig); grunt.parseStopOnError(true); } catch (FileNotFoundException e) { LogFactory.getLog(PigServer.class).error(e.getLocalizedMessage()); throw new IOException(e.getCause()); } catch (org.apache.pig.tools.pigscript.parser.ParseException e) { LogFactory.getLog(PigServer.class).error(e.getLocalizedMessage()); throw new IOException(e.getCause()); } catch (org.apache.pig.tools.parameters.ParseException e) { LogFactory.getLog(PigServer.class).error(e.getLocalizedMessage()); throw new IOException(e.getCause()); } }
From source file:epsi.i5.datamining.JsonBuilder.java
/** * This method return un DataEntity with only comment attribute filled from * the json file// ww w . j a v a 2s .co m * * @return */ public List<DataEntity> getSimpleCommentaires(File file) { List<DataEntity> listeCommentaires = new ArrayList(); try { Object objFile = parser.parse(new FileReader(file.getAbsolutePath())); JSONArray jsonArray = (JSONArray) objFile; for (Object obj : jsonArray) { JSONObject jsonObject = (JSONObject) obj; DataEntity commentaire = new DataEntity(); commentaire.setId(jsonObject.get("id")); commentaire.setCommentaires((String) jsonObject.get("commentaires")); listeCommentaires.add(commentaire); } } catch (FileNotFoundException e) { System.out.println("Une erreur est survenue lors de lecture du ficheir JSON"); System.out.println("Cause : " + e.getCause()); System.out.println("Message : " + e.getMessage()); } catch (IOException | ParseException ex) { Logger.getLogger(JsonBuilder.class.getName()).log(Level.SEVERE, null, ex); } return listeCommentaires; }
From source file:org.dataone.proto.trove.mn.service.v1.impl.MNStorageImpl.java
@Override public Identifier create(Identifier pid, InputStream object, SystemMetadata sysmeta) throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidRequest { try {/* w ww . j a v a 2s . c om*/ File systemMetadata = new File(dataoneCacheDirectory + File.separator + "meta" + File.separator + EncodingUtilities.encodeUrlPathSegment(pid.getValue())); TypeMarshaller.marshalTypeToFile(sysmeta, systemMetadata.getAbsolutePath()); if (systemMetadata.exists()) { systemMetadata.setLastModified(sysmeta.getDateSysMetadataModified().getTime()); } else { throw new ServiceFailure("1190", "SystemMetadata not found on FileSystem after create"); } File objectFile = new File(dataoneCacheDirectory + File.separator + "object" + File.separator + EncodingUtilities.encodeUrlPathSegment(pid.getValue())); if (!objectFile.exists() && objectFile.createNewFile()) { objectFile.setReadable(true); objectFile.setWritable(true); objectFile.setExecutable(false); } if (object != null) { FileOutputStream objectFileOutputStream = new FileOutputStream(objectFile); BufferedInputStream inputStream = new BufferedInputStream(object); byte[] barray = new byte[SIZE]; int nRead = 0; while ((nRead = inputStream.read(barray, 0, SIZE)) != -1) { objectFileOutputStream.write(barray, 0, nRead); } objectFileOutputStream.flush(); objectFileOutputStream.close(); inputStream.close(); } } catch (FileNotFoundException ex) { throw new ServiceFailure("1190", ex.getCause().toString() + ":" + ex.getMessage()); } catch (IOException ex) { throw new ServiceFailure("1190", ex.getMessage()); } catch (JiBXException ex) { throw new InvalidSystemMetadata("1180", ex.getMessage()); } return pid; }
From source file:om.sstvencoder.MainActivity.java
private boolean handleIntent(Intent intent) { if (!isIntentTypeValid(intent.getType()) || !isIntentActionValid(intent.getAction())) return false; Uri uri = intent.hasExtra(Intent.EXTRA_STREAM) ? (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM) : intent.getData();// w w w . ja va2 s. c o m if (uri != null) { try { ContentResolver resolver = getContentResolver(); mCropView.setBitmapStream(resolver.openInputStream(uri)); mCropView.rotateImage(getOrientation(resolver, uri)); return true; } catch (FileNotFoundException ex) { if (ex.getCause() instanceof ErrnoException) { if (((ErrnoException) ex.getCause()).errno == OsConstants.EACCES) { requestPermissions(); return false; } } String s = getString(R.string.load_img_err_title) + ": \n" + ex.getMessage(); Toast.makeText(this, s, Toast.LENGTH_LONG).show(); } catch (Exception ex) { String s = Utility.createMessage(ex) + "\n\n" + uri + "\n\n" + intent; showErrorMessage(getString(R.string.load_img_err_title), ex.getMessage(), s); } } else { String s = getString(R.string.load_img_err_txt_unsupported); showErrorMessage(getString(R.string.load_img_err_title), s, s + "\n\n" + intent); } return false; }
From source file:de.tudarmstadt.ukp.clarin.webanno.brat.ajax.controller.CasToBratJsonTest.java
/** * generate brat JSON data for the document *//* www . j a va 2 s.c om*/ @Test public void testGenerateBratJsonGetDocument() throws Exception { MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter(); String jsonFilePath = "target/test-output/output_cas_to_json_document.json"; InputStream is = null; JCas jCas = null; try { // is = new // FileInputStream("src/test/resources/tcf04-karin-wl.xml"); String path = "src/test/resources/"; String file = "tcf04-karin-wl.xml"; CAS cas = JCasFactory.createJCas().getCas(); CollectionReader reader = CollectionReaderFactory.createReader(TcfReader.class, TcfReader.PARAM_SOURCE_LOCATION, path, TcfReader.PARAM_PATTERNS, new String[] { "[+]" + file }); if (!reader.hasNext()) { throw new FileNotFoundException("Annotation file [" + file + "] not found in [" + path + "]"); } reader.getNext(cas); jCas = cas.getJCas(); } catch (FileNotFoundException ex) { LOG.info("The file specified not found " + ex.getCause()); } catch (Exception ex) { LOG.info(ex); } List<String> tagSetNames = new ArrayList<String>(); tagSetNames.add(de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.POS); tagSetNames.add(de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.DEPENDENCY); tagSetNames.add(de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.NAMEDENTITY); tagSetNames.add(de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.COREFERENCE); tagSetNames.add(de.tudarmstadt.ukp.clarin.webanno.api.WebAnnoConst.COREFRELTYPE); BratAnnotatorModel bratannotatorModel = new BratAnnotatorModel(); bratannotatorModel.getPreferences().setWindowSize(10); bratannotatorModel.setSentenceAddress(BratAjaxCasUtil.getFirstSentenceAddress(jCas)); bratannotatorModel.setLastSentenceAddress(BratAjaxCasUtil.getLastSentenceAddress(jCas)); Sentence sentence = BratAjaxCasUtil.selectByAddr(jCas, Sentence.class, bratannotatorModel.getSentenceAddress()); bratannotatorModel.setSentenceBeginOffset(sentence.getBegin()); bratannotatorModel.setSentenceEndOffset(sentence.getEnd()); Project project = new Project(); bratannotatorModel.setProject(project); bratannotatorModel.setMode(Mode.ANNOTATION); GetDocumentResponse response = new GetDocumentResponse(); response.setText(jCas.getDocumentText()); SpanAdapter.renderTokenAndSentence(jCas, response, bratannotatorModel); /* for (AnnotationLayer layer : bratannotatorModel.getAnnotationLayers()) { getAdapter(layer, annotationService).render(jCas, annotationService.listAnnotationFeature(layer), response, bratannotatorModel); }*/ JSONUtil.generateJson(jsonConverter, response, new File(jsonFilePath)); String reference = FileUtils.readFileToString( new File("src/test/resources/output_cas_to_json_document_expected.json"), "UTF-8"); String actual = FileUtils.readFileToString(new File("target/test-output/output_cas_to_json_document.json"), "UTF-8"); assertEquals(reference, actual); }
From source file:com.aleerant.tnssync.PropertiesHandler.java
private void getLdapOraProperties() throws AppException { String ldaporaFile = Paths.get(mTnsAdminPathString, APP_LDAPORA_FILENAME).toString(); Properties ldapOraProperties = new Properties(); try {/*from w w w .j a v a 2 s . c om*/ ldapOraProperties.load(new FileInputStream(ldaporaFile)); } catch (FileNotFoundException e) { throw new AppException(APP_LDAPORA_FILENAME + " file is missing (" + ldaporaFile + "), error message: " + e.getMessage() + ", caused by:" + e.getCause()); } catch (IOException e) { throw new AppException("can not read " + APP_LDAPORA_FILENAME + " file (" + ldaporaFile + "), error message: " + e.getMessage() + ", caused by:" + e.getCause()); } this.mDefaultAdminContext = ldapOraProperties.getProperty("DEFAULT_ADMIN_CONTEXT").replaceAll("[()\\s]", ""); if (this.mDefaultAdminContext == null) { throw new IllegalArgumentException("Missing parameter: DEFAULT_ADMIN_CONTEXT"); } this.mDirectoryServers = ldapOraProperties.getProperty("DIRECTORY_SERVERS", "").replaceAll("[()\\s]", ""); }