Java Code Examples for java.io.FileNotFoundException

The following examples show how to use java.io.FileNotFoundException. These examples are extracted from open source projects.
Example 1
Project: jstorm   File: TestTopology.java    License: Apache License 2.0 6 votes vote down vote up
private static void LoadYaml(String confPath) {

		Yaml yaml = new Yaml();

		try {
			InputStream stream = new FileInputStream(confPath);

			conf = (Map) yaml.load(stream);
			if (conf == null || conf.isEmpty() == true) {
				throw new RuntimeException("Failed to read config file");
			}

		} catch (FileNotFoundException e) {
			System.out.println("No such file " + confPath);
			throw new RuntimeException("No config file");
		} catch (Exception e1) {
			e1.printStackTrace();
			throw new RuntimeException("Failed to read config file");
		}

		return;
	}
 
Example 2
Project: Pomfshare   File: MainActivity.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void displayAndUpload(Host host) {
	ContentResolver cr = getContentResolver();
	if (imageUri != null) {
		ImageView view = (ImageView)findViewById(R.id.sharedImageView);
		view.setImageURI(imageUri);

		ParcelFileDescriptor inputPFD = null; 
		try {
			inputPFD = cr.openFileDescriptor(imageUri, "r");				
		} catch (FileNotFoundException e) {
			Log.e(tag, e.getMessage());
			Toast toast = Toast.makeText(getApplicationContext(), "Unable to read file.", Toast.LENGTH_SHORT);
			toast.show();				
		}

		new Uploader(this, inputPFD, host).execute(imageUri.getLastPathSegment(), cr.getType(imageUri));
	}
}
 
Example 3
Project: mmtf-spark   File: ReadMmtfReduced.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws FileNotFoundException {  
	
	String path = MmtfReader.getMmtfReducedPath();
    
    // instantiate Spark. Each Spark application needs these two lines of code.
    SparkConf conf = new SparkConf().setMaster("local[*]").setAppName(ReadMmtfReduced.class.getSimpleName());
    JavaSparkContext sc = new JavaSparkContext(conf);
	 
    // read list of PDB entries from a local Hadoop sequence file
    List<String> pdbIds = Arrays.asList("1AQ1","1B38","1B39","1BUH"); 
    JavaPairRDD<String, StructureDataInterface> pdb = MmtfReader.readSequenceFile(path, pdbIds, sc);
    
    System.out.println("# structures: " + pdb.count());
    
    // close Spark
    sc.close();
}
 
Example 4
Project: camunda-bpm-platform   File: PluggableProcessEngineTestCase.java    License: Apache License 2.0 6 votes vote down vote up
private static ProcessEngine getOrInitializeCachedProcessEngine() {
  if (cachedProcessEngine == null) {
    try {
      cachedProcessEngine = ProcessEngineConfiguration
              .createProcessEngineConfigurationFromResource("camunda.cfg.xml")
              .buildProcessEngine();
    } catch (RuntimeException ex) {
      if (ex.getCause() != null && ex.getCause() instanceof FileNotFoundException) {
        cachedProcessEngine = ProcessEngineConfiguration
            .createProcessEngineConfigurationFromResource("activiti.cfg.xml")
            .buildProcessEngine();
      } else {
        throw ex;
      }
    }
  }
  return cachedProcessEngine;
}
 
Example 5
Project: droid-stealth   File: LocalStorageProvider.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void includeFile(final MatrixCursor result, final File file)
        throws FileNotFoundException {
    final MatrixCursor.RowBuilder row = result.newRow();
    // These columns are required
    row.add(Document.COLUMN_DOCUMENT_ID, file.getAbsolutePath());
    row.add(Document.COLUMN_DISPLAY_NAME, file.getName());
    String mimeType = getDocumentType(file.getAbsolutePath());
    row.add(Document.COLUMN_MIME_TYPE, mimeType);
    int flags = file.canWrite() ? Document.FLAG_SUPPORTS_DELETE | Document.FLAG_SUPPORTS_WRITE
            : 0;
    // We only show thumbnails for image files - expect a call to
    // openDocumentThumbnail for each file that has
    // this flag set
    if (mimeType.startsWith("image/"))
        flags |= Document.FLAG_SUPPORTS_THUMBNAIL;
    row.add(Document.COLUMN_FLAGS, flags);
    // COLUMN_SIZE is required, but can be null
    row.add(Document.COLUMN_SIZE, file.length());
    // These columns are optional
    row.add(Document.COLUMN_LAST_MODIFIED, file.lastModified());
    // Document.COLUMN_ICON can be a resource id identifying a custom icon.
    // The system provides default icons
    // based on mime type
    // Document.COLUMN_SUMMARY is optional additional information about the
    // file
}
 
Example 6
Project: java-sdk   File: SpeechToTextTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test train language model.
 *
 * @throws InterruptedException the interrupted exception
 * @throws FileNotFoundException the file not found exception
 */
@Test
public void testTrainLanguageModel() throws InterruptedException, FileNotFoundException {
  server.enqueue(
      new MockResponse().addHeader(CONTENT_TYPE, HttpMediaType.APPLICATION_JSON).setBody("{}"));
  String id = "foo";

  TrainLanguageModelOptions trainOptions =
      new TrainLanguageModelOptions.Builder()
          .customizationId(id)
          .wordTypeToAdd(TrainLanguageModelOptions.WordTypeToAdd.ALL)
          .customizationWeight(0.5)
          .build();
  service.trainLanguageModel(trainOptions).execute().getResult();
  final RecordedRequest request = server.takeRequest();

  assertEquals("POST", request.getMethod());
  assertEquals(
      String.format(PATH_TRAIN, id) + "?word_type_to_add=all&customization_weight=" + 0.5,
      request.getPath());
}
 
Example 7
Project: commons-vfs   File: UrlFileObject.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Determines the type of the file.
 */
@Override
protected FileType doGetType() throws Exception {
    try {
        // Attempt to connect & check status
        final URLConnection conn = url.openConnection();
        final InputStream in = conn.getInputStream();
        try {
            if (conn instanceof HttpURLConnection) {
                final int status = ((HttpURLConnection) conn).getResponseCode();
                // 200 is good, maybe add more later...
                if (HttpURLConnection.HTTP_OK != status) {
                    return FileType.IMAGINARY;
                }
            }

            return FileType.FILE;
        } finally {
            in.close();
        }
    } catch (final FileNotFoundException e) {
        return FileType.IMAGINARY;
    }
}
 
Example 8
Project: athenz   File: CryptoExceptionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCryptoExceptions() {

    CryptoException ex = new CryptoException();
    assertNotNull(ex);
    assertEquals(ex.getCode(), CryptoException.CRYPTO_ERROR);

    assertNotNull(new CryptoException(new NoSuchAlgorithmException()));
    assertNotNull(new CryptoException(new InvalidKeyException()));
    assertNotNull(new CryptoException(new NoSuchProviderException()));
    assertNotNull(new CryptoException(new SignatureException()));
    assertNotNull(new CryptoException(new FileNotFoundException()));
    assertNotNull(new CryptoException(new IOException()));
    assertNotNull(new CryptoException(new CertificateException()));
    assertNotNull(new CryptoException(new InvalidKeySpecException()));
    assertNotNull(new CryptoException(new OperatorCreationException("unit-test")));
    assertNotNull(new CryptoException(new PKCSException("unit-test")));
    assertNotNull(new CryptoException(new CMSException("unit-test")));

    ex = new CryptoException(CryptoException.CERT_HASH_MISMATCH, "X.509 Certificate hash mismatch");
    assertEquals(ex.getCode(), CryptoException.CERT_HASH_MISMATCH);
}
 
Example 9
Project: lams   File: ClassPathResource.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * This implementation opens an InputStream for the given class path resource.
 * @see java.lang.ClassLoader#getResourceAsStream(String)
 * @see java.lang.Class#getResourceAsStream(String)
 */
@Override
public InputStream getInputStream() throws IOException {
	InputStream is;
	if (this.clazz != null) {
		is = this.clazz.getResourceAsStream(this.path);
	}
	else if (this.classLoader != null) {
		is = this.classLoader.getResourceAsStream(this.path);
	}
	else {
		is = ClassLoader.getSystemResourceAsStream(this.path);
	}
	if (is == null) {
		throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
	}
	return is;
}
 
Example 10
Project: iBeebo   File: ImgsActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void OnItemClick(View v, int Position, CheckBox checkBox) {
    String filapath = fileTraversal.filecontent.get(Position);
    if (checkBox.isChecked()) {
        checkBox.setChecked(false);
        mSendImgData.removeSendImg(filapath);
    } else {
        try {
            if (mSendImgData.getSendImgs().size() >= 1) {
                Toast.makeText(getApplicationContext(), R.string.send_tomanay_pics, Toast.LENGTH_SHORT).show();
            } else {
                checkBox.setChecked(true);
                Log.i("img", "img choise position->" + Position);
                ImageView imageView = iconImage(filapath, Position, checkBox);
                if (imageView != null) {
                    hashImage.put(Position, imageView);
                    mSendImgData.addSendImg(filapath);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    updateCount(mMenuItem);
}
 
Example 11
Project: MediaSDK   File: DownloadExceptionUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static int getErrorCode(Throwable e) {
    if (e instanceof SocketTimeoutException) {
        return SOCKET_TIMEOUT_ERROR;
    } else if (e instanceof FileNotFoundException) {
        return FILE_NOT_FOUND_ERROR;
    } else if (e instanceof VideoCacheException) {
        if (((VideoCacheException) e).getMsg().equals(FILE_LENGTH_FETCHED_ERROR_STRING)) {
            return FILE_LENGTH_FETCHED_ERROR;
        } else if (((VideoCacheException) e).getMsg().equals(M3U8_FILE_CONTENT_ERROR_STRING)) {
            return M3U8_FILE_CONTENT_ERROR;
        } else if (((VideoCacheException) e).getMsg().equals(MIMETYPE_NULL_ERROR_STRING)) {
            return MIMETYPE_NULL_ERROR;
        } else if(((VideoCacheException) e).getMsg().equals(MIMETYPE_NOT_FOUND_STRING)) {

        }
    } else if (e instanceof UnknownHostException) {
        return UNKNOWN_HOST_ERROR;
    }
    return UNKNOWN_ERROR;
}
 
Example 12
Project: mollyim-android   File: MmsBodyProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {
  Log.i(TAG, "openFile(" + uri + ", " + mode + ")");

  switch (uriMatcher.match(uri)) {
  case SINGLE_ROW:
    Log.i(TAG, "Fetching message body for a single row...");
    File tmpFile = getFile(uri);

    final int fileMode;
    switch (mode) {
    case "w": fileMode = ParcelFileDescriptor.MODE_TRUNCATE |
                         ParcelFileDescriptor.MODE_CREATE   |
                         ParcelFileDescriptor.MODE_WRITE_ONLY; break;
    case "r": fileMode = ParcelFileDescriptor.MODE_READ_ONLY;  break;
    default:  throw new IllegalArgumentException("requested file mode unsupported");
    }

    Log.i(TAG, "returning file " + tmpFile.getAbsolutePath());
    return ParcelFileDescriptor.open(tmpFile, fileMode);
  }

  throw new FileNotFoundException("Request for bad message.");
}
 
Example 13
Project: org.hl7.fhir.core   File: ObservationStatsBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static void buildVitalSignsSet() throws FileNotFoundException, IOException, FHIRFormatError {
  Calendar base = Calendar.getInstance();
  base.add(Calendar.DAY_OF_MONTH, -1);
  Bundle b = new Bundle();
  b.setType(BundleType.COLLECTION);
  b.setId(UUID.randomUUID().toString().toLowerCase());
  
  vitals(b, base, 0, 80, 120, 95, 37.1);
  vitals(b, base, 35, 85, 140, 98, 36.9);
  vitals(b, base, 53, 75, 110, 96, 36.2);
  vitals(b, base, 59, 65, 100, 94, 35.5);
  vitals(b, base, 104, 60, 90, 90, 35.9);
  vitals(b, base, 109, 65, 100, 92, 36.5);
  vitals(b, base, 114, 70, 130, 94, 37.5);
  vitals(b, base, 120, 90, 150, 97, 37.3);
  vitals(b, base, 130, 95, 133, 97, 37.2);
  vitals(b, base, 150, 85, 125, 98, 37.1);
  
  new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream("c:\\temp\\vitals.xml"), b);
}
 
Example 14
Project: maxent_iis   File: DataSet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * ��ȡ���ݼ�
 * @param path
 * @return
 * @throws FileNotFoundException
 */
public static List<Instance> readDataSet(String path) throws FileNotFoundException
{
    File file = new File(path);
    Scanner scanner = new Scanner(file);
    List<Instance> instances = new ArrayList<Instance>();

    while (scanner.hasNextLine())
    {
        String line = scanner.nextLine();
        List<String> tokens = Arrays.asList(line.split("\\s"));
        String s1 = tokens.get(0);
        int label = Integer.parseInt(s1.substring(s1.length() - 1));
        int[] features = new int[tokens.size() - 1];

        for (int i = 1; i < tokens.size(); i++)
        {
            String s = tokens.get(i);
            features[i - 1] = Integer.parseInt(s.substring(s.length() - 1));
        }
        Instance instance = new Instance(label, features);
        instances.add(instance);
    }
    scanner.close();
    return instances;
}
 
Example 15
Project: ache   File: TargetStorageMonitor.java    License: Apache License 2.0 6 votes vote down vote up
public static HashSet<String> readRelevantUrls(String dataPath) {
    String fileRelevantPages = dataPath + "/data_monitor/relevantpages.csv";
    HashSet<String> relevantUrls = new HashSet<>();
    try(Scanner scanner = new Scanner(new File(fileRelevantPages))) {
        while(scanner.hasNext()){
            String nextLine = scanner.nextLine();
            String[] splittedLine = nextLine.split("\t");
            if(splittedLine.length == 3) {
                String url = splittedLine[0];
                relevantUrls.add(url);
            }
        }
        return relevantUrls;
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Failed to load relevant URL from target monitor file: "+fileRelevantPages);
    }
}
 
Example 16
Project: q   File: BaseIndexer.java    License: Apache License 2.0 6 votes vote down vote up
public Map<String, String> getTitleToIds() throws FileNotFoundException, UnsupportedEncodingException, IOException
 {
     Map<String, String> titleIdToName = Maps.newHashMap();

     InputStream is = new BufferedInputStream(new FileInputStream(inputFileName), BUFFER_SIZE);
     BufferedReader reader = new BufferedReader(new InputStreamReader(is, ENCODING), BUFFER_SIZE);
     String lineString = null;
     while ((lineString = reader.readLine()) != null) {
String[] line = lineString.split(Properties.inputDelimiter.get());
String id = line[0];
titleIdToName.put(StringUtils.createIdUsingTestName(id, testName), line[2]);
     }
     reader.close();
     is.close();
     return titleIdToName;
 }
 
Example 17
Project: BIMserver   File: Express2EMF.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public Express2EMF(File schemaFileName, String modelName, String nsUri) {
	schema = new SchemaLoader(schemaFileName.getAbsolutePath()).getSchema();
	eFactory = EcoreFactory.eINSTANCE;
	ePackage = EcorePackage.eINSTANCE;
	schemaPack = eFactory.createEPackage();
	try {
		new DerivedReader(schemaFileName, schema);
	} catch (FileNotFoundException e) {
		LOGGER.error("", e);
	}
	schemaPack.setName(modelName);
	schemaPack.setNsPrefix("iai");
	schemaPack.setNsURI(nsUri);

	createTristate();

	addClasses();
	addSupertypes();
	addSimpleTypes();
	addDerivedTypes();
	addEnumerations();
	addHackedTypes();
	addSelects();
	addAttributes();
	addInverses();
	EClass ifcBooleanClass = (EClass) schemaPack.getEClassifier("IfcBoolean");
	ifcBooleanClass.getESuperTypes().add((EClass) schemaPack.getEClassifier("IfcValue"));
	doRealDerivedAttributes();
	clean();
}
 
Example 18
Project: yago3   File: Theme.java    License: GNU General Public License v3.0 5 votes vote down vote up
/** Assigns the theme to a file (to use data that is already there) */
public synchronized Theme assignToFolder(File folder) throws IOException {
  File f = findFileInFolder(folder);
  if (f == null) throw new FileNotFoundException("Cannot find theme " + this + " in " + folder.getCanonicalPath());
  if (file != null) {
    if (file.equals(f)) return (this);
    else throw new IOException("Theme " + this + " is already assigned to file " + file + ", cannot assign it to " + f);
  }
  file = f;
  cache = null;
  return (this);
}
 
Example 19
Project: dremio-oss   File: DremioHadoopFileSystemWrapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DirectoryStream<FileAttributes> list(Path f) throws FileNotFoundException, IOException {
  try (WaitRecorder recorder = OperatorStats.getWaitRecorder(operatorStats)) {
    return new ArrayDirectoryStream(underlyingFs.listStatus(toHadoopPath(f)));
  } catch(FSError e) {
    throw propagateFSError(e);
  }
}
 
Example 20
Project: FireFiles   File: DocumentsContractApi19.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean delete(Context context, Uri self) {
    try {
        return DocumentsContract.deleteDocument(context.getContentResolver(), self);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 21
Project: openjdk-jdk8u-backup   File: Gen.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void writeIfChanged(byte[] b, FileObject file) throws IOException {
    boolean mustWrite = false;
    String event = "[No need to update file ";

    if (force) {
        mustWrite = true;
        event = "[Forcefully writing file ";
    } else {
        InputStream in;
        byte[] a;
        try {
            // regrettably, there's no API to get the length in bytes
            // for a FileObject, so we can't short-circuit reading the
            // file here
            in = file.openInputStream();
            a = readBytes(in);
            if (!Arrays.equals(a, b)) {
                mustWrite = true;
                event = "[Overwriting file ";

            }
        } catch (FileNotFoundException e) {
            mustWrite = true;
            event = "[Creating file ";
        }
    }

    if (util.verbose)
        util.log(event + file + "]");

    if (mustWrite) {
        OutputStream out = file.openOutputStream();
        out.write(b); /* No buffering, just one big write! */
        out.close();
    }
}
 
Example 22
Project: ache   File: FileSystemTargetRepository.java    License: Apache License 2.0 5 votes vote down vote up
private <T> T readFile(Path filePath) throws IOException, FileNotFoundException {
    if (!Files.exists(filePath)) {
        return null;
    }
    try (InputStream fileStream = new FileInputStream(filePath.toFile())) {
        if(compressData) {
            try(InputStream gzipStream = new InflaterInputStream(fileStream)) {
                return unserializeData(gzipStream);
            }
        } else {
            return unserializeData(fileStream);
        }
    }
}
 
Example 23
Project: Lottery   File: DistributeJob.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 分发文件夹到指定FTP
 */
public void distribute() throws FileNotFoundException, IOException {
	Ftp ftp=ftpMng.findById(ftpId);
	for(String folder:this.folders){
		log.info("distribute folder  "+folder);
		String folderPath=realPathResolver.get(folder);
		String rootPath=realPathResolver.get("");
		if(StringUtils.isNotBlank(folder)&&StringUtils.isNotBlank(folderPath)){
			ftp.storeByFloder(folderPath,rootPath);
		}
	}
}
 
Example 24
Project: jdk8u_jdk   File: FtpURLConnectionLeak.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    FtpServer server = new FtpServer(0);
    server.setFileSystemHandler(new CustomFileSystemHandler("/"));
    server.setAuthHandler(new MyAuthHandler());
    int port = server.getLocalPort();
    server.start();
    URL url = new URL("ftp://localhost:" + port + "/filedoesNotExist.txt");
    for (int i = 0; i < 3; i++) {
        try {
            InputStream stream = url.openStream();
        } catch (FileNotFoundException expectedFirstTimeAround) {
            // should always reach this point since the path does not exist
        } catch (IOException expected) {
            System.out.println("caught expected " + expected);
            int times = 1;
            do {
                // give some time to close the connection...
                System.out.println("sleeping... " + times);
                Thread.sleep(times * 1000);
            } while (server.activeClientsCount() > 0 && times++ < 5);

            if (server.activeClientsCount() > 0) {
                server.killClients();
                throw new RuntimeException("URLConnection didn't close the" +
                        " FTP connection on FileNotFoundException");
            }
        } finally {
            server.terminate();
        }
    }
}
 
Example 25
Project: http4e   File: BusinessJob.java    License: Apache License 2.0 5 votes vote down vote up
private void addMultipart_Parts( MultipartPostMethod method, Map<String, String> parameterizedMap){
   for (Iterator it = model.getParameters().entrySet().iterator(); it.hasNext();) {
      Map.Entry me = (Map.Entry) it.next();
      String key = (String) me.getKey();
      List values = (List) me.getValue();
      StringBuilder sb = new StringBuilder();
      int cnt = 0;
      for (Iterator it2 = values.iterator(); it2.hasNext();) {
         String val = (String) it2.next();
         if (cnt != 0) {
            sb.append(",");
         }
         sb.append(val);
         cnt++;
      }

      String parameterizedVal = ParseUtils.getParametizedArg(sb.toString(), parameterizedMap);

      if (parameterizedVal.startsWith("@")) {
         String path = "";
         String contentType = "";
         try {
            path = parameterizedVal.substring(1, parameterizedVal.length()).trim();
            path = path.replace('\\', '/');
            contentType = getContentType(getFileExt(path));
            File f = new File(path);
            method.addPart(new FilePart(key, f, contentType, null));
            // postMethod.addParameter("file", f);
            // postMethod.addPart(new FilePart("file", f));
         } catch (FileNotFoundException fnfe) {
            ExceptionHandler.handle(fnfe);
         }

      } else {
         method.addPart(new StringPart(key, parameterizedVal));

      }
   }
}
 
Example 26
Project: drftpd   File: DirectoryHandle.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param reason
 * @throws FileNotFoundException if this Directory does not exist
 */
public void abortAllTransfers(String reason) throws FileNotFoundException {
    for (FileHandle file : getFilesUnchecked()) {
        try {
            file.abortTransfers(reason);
        } catch (FileNotFoundException e) {
        }
    }
}
 
Example 27
Project: tus-java-client   File: TusUpload.java    License: MIT License 5 votes vote down vote up
/**
 * Create a new TusUpload object using the supplied File object. The corresponding {@link
 * InputStream}, size and fingerprint will be automatically set.
 *
 * @param file The file whose content should be later uploaded.
 * @throws FileNotFoundException Thrown if the file cannot be found.
 */
public TusUpload(@NotNull File file) throws FileNotFoundException {
    size = file.length();
    setInputStream(new FileInputStream(file));

    fingerprint = String.format("%s-%d", file.getAbsolutePath(), size);

    metadata = new HashMap<String, String>();
    metadata.put("filename", file.getName());
}
 
Example 28
Project: sakai   File: SakaiMessageHandlerTest.java    License: Educational Community License v2.0 5 votes vote down vote up
public void writeData(SmartClient client, String resource) throws IOException {
    client.dataStart();
    InputStream is = getClass().getResourceAsStream(resource);
    if(is == null) {
        throw new FileNotFoundException("Couldn't find in classpath: "+ resource);
    }
    byte[] bytes = IOUtils.toByteArray(is);
    client.dataWrite(bytes, bytes.length);
    client.dataEnd();
}
 
Example 29
Project: spring4-understanding   File: ResourceHttpRequestHandlerTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void writeContentNotGettingInputStream() throws Exception {
	Resource resource = mock(Resource.class);
	given(resource.getInputStream()).willThrow(FileNotFoundException.class);

	this.handler.writeContent(this.response, resource);

	assertEquals(200, this.response.getStatus());
	assertEquals(0, this.response.getContentLength());
}
 
Example 30
Project: java-technology-stack   File: PluggableSchemaResolver.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public InputSource resolveEntity(String publicId, @Nullable String systemId) throws IOException {
	if (logger.isTraceEnabled()) {
		logger.trace("Trying to resolve XML entity with public id [" + publicId +
				"] and system id [" + systemId + "]");
	}

	if (systemId != null) {
		String resourceLocation = getSchemaMappings().get(systemId);
		if (resourceLocation != null) {
			Resource resource = new ClassPathResource(resourceLocation, this.classLoader);
			try {
				InputSource source = new InputSource(resource.getInputStream());
				source.setPublicId(publicId);
				source.setSystemId(systemId);
				if (logger.isTraceEnabled()) {
					logger.trace("Found XML schema [" + systemId + "] in classpath: " + resourceLocation);
				}
				return source;
			}
			catch (FileNotFoundException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Could not find XML schema [" + systemId + "]: " + resource, ex);
				}
			}
		}
	}
	return null;
}
 
Example 31
Project: secure-data-service   File: ZipFileValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void zipFileHasPath() throws FileNotFoundException {
    AbstractMessageReport report = new DummyMessageReport();
    ReportStats reportStats = new SimpleReportStats();
    Source source = new JobSource(null);

    file = IngestionTest.getFile("zip/ZipWithPath.zip");
    boolean isValid = zipFileValidator.isValid(file, report, reportStats, source, null);
    Assert.assertFalse(isValid);

}
 
Example 32
Project: openjdk-jdk9   File: InetAddress.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Lookup the host name  corresponding to the IP address provided.
 * Search the configured host file a host name corresponding to
 * the specified IP address.
 *
 * @param addr byte array representing an IP address
 * @return {@code String} representing the host name mapping
 * @throws UnknownHostException
 *             if no host found for the specified IP address
 */
@Override
public String getHostByAddr(byte[] addr) throws UnknownHostException {
    String hostEntry;
    String host = null;

    String addrString = addrToString(addr);
    try (Scanner hostsFileScanner = new Scanner(new File(hostsFile), "UTF-8")) {
        while (hostsFileScanner.hasNextLine()) {
            hostEntry = hostsFileScanner.nextLine();
            if (!hostEntry.startsWith("#")) {
                hostEntry = removeComments(hostEntry);
                if (hostEntry.contains(addrString)) {
                    host = extractHost(hostEntry, addrString);
                    if (host != null) {
                        break;
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
        throw new UnknownHostException("Unable to resolve address "
                + addrString + " as hosts file " + hostsFile
                + " not found ");
    }

    if ((host == null) || (host.equals("")) || (host.equals(" "))) {
        throw new UnknownHostException("Requested address "
                + addrString
                + " resolves to an invalid entry in hosts file "
                + hostsFile);
    }
    return host;
}
 
Example 33
Project: gemfirexd-oss   File: EncryptedLOBFile.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructs the EncryptedLOBFile object with encryption support.
 *
 * @param lobFile StorageFile Object for which file will be created
 * @param df data factory for encryption and decription
 * @throws FileNotFoundException if the file exists but is a directory or
 * cannot be opened
 */
EncryptedLOBFile(StorageFile lobFile, DataFactory df)
                                            throws FileNotFoundException {
    super(lobFile);
    this.df = df;
    blockSize = df.getEncryptionBlockSize();
    tail = new byte [blockSize];
    tailSize = 0;
}
 
Example 34
Project: openjdk-8   File: SelectFdsLimit.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void openFiles(int fn, File f) throws FileNotFoundException, IOException {
    testFIS = new FileInputStream[FDTOOPEN];
    for (;;) {
        if (0 == fn)
            break;
        FileInputStream fis = new FileInputStream(f);
        testFIS[--fn] = fis;
    }
}
 
Example 35
Project: big-c   File: FileContextTestHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isDir(FileContext fc, Path p) throws IOException {
  try {
    return fc.getFileStatus(p).isDirectory();
  } catch (FileNotFoundException e) {
    return false;
  }
}
 
Example 36
Project: openjdk-jdk8u-backup   File: SecuritySupport.java    License: GNU General Public License v2.0 5 votes vote down vote up
FileInputStream getFileInputStream(final File file)
throws FileNotFoundException
{
    try {
        return (FileInputStream)
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws FileNotFoundException {
                return new FileInputStream(file);
            }
        });
    } catch (PrivilegedActionException e) {
        throw (FileNotFoundException)e.getException();
    }
}
 
Example 37
Project: hottub   File: MiscTests.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void test6856415() {
    // No pkcs library on win-x64, so we bail out.
    if (is64Bit && isWindows) {
        return;
    }
    StringBuilder sb = new StringBuilder();
    sb.append("public static void main(String... args) {\n");
    sb.append("java.security.Provider p = new sun.security.pkcs11.SunPKCS11(args[0]);\n");
    sb.append("java.security.Security.insertProviderAt(p, 1);\n");
    sb.append("}");
    File testJar = new File("Foo.jar");
    testJar.delete();
    try {
        createJar(testJar, sb.toString());
    } catch (FileNotFoundException fnfe) {
        throw new RuntimeException(fnfe);
    }
    TestResult tr = doExec(javaCmd,
            "-Djava.security.manager", "-jar", testJar.getName(), "foo.bak");
    for (String s : tr.testOutput) {
        System.out.println(s);
}
    if (!tr.contains("java.security.AccessControlException:" +
            " access denied (\"java.lang.RuntimePermission\"" +
            " \"accessClassInPackage.sun.security.pkcs11\")")) {
        System.out.println(tr.status);
    }
}
 
Example 38
Project: xtext-core   File: JavaIoFileSystemAccess.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.4
 */
@Override
public InputStream readBinaryFile(String fileName, String outputCfgName) throws RuntimeIOException {
	File file = getFile(fileName, outputCfgName);
	try {
		return new BufferedInputStream(new FileInputStream(file));
	} catch (FileNotFoundException e) {
		throw new RuntimeIOException(e);
	}
}
 
Example 39
Project: paintera   File: PainteraConfigYaml.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static Map<?, ?> readConfig() throws IOException {
	final Yaml yaml = new Yaml();
	try (final InputStream fis = new FileInputStream(PAINTERA_YAML.toFile())) {
		// TODO is this cast always safe?
		// TODO make this type safe, maybe create config class
		final Map<?, ?> data = (Map<?, ?>) yaml.load(fis);
		LOG.debug("Loaded paintera info: {}", data);
		return data;
	} catch (final FileNotFoundException e) {
		LOG.debug("Paintera config file not found: {}", e.getMessage());
	}
	return new HashMap<>();
}
 
Example 40
Project: deeplearning4j   File: FastTextTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadIterator() throws FileNotFoundException {
    SentenceIterator iter = new BasicLineIterator(inputFile.getAbsolutePath());
     FastText
            .builder()
            .supervised(true)
            .iterator(iter)
            .build()
            .loadIterator();
}