java.io.FileNotFoundException Java Examples

The following examples show how to use java.io.FileNotFoundException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpeechToTextTest.java    From java-sdk with 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 #2
Source File: ClassPathResource.java    From lams with 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 #3
Source File: ImgsActivity.java    From iBeebo with 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 #4
Source File: PluggableProcessEngineTestCase.java    From camunda-bpm-platform with 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
Source File: LocalStorageProvider.java    From droid-stealth with 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
Source File: CryptoExceptionTest.java    From athenz with 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 #7
Source File: UrlFileObject.java    From commons-vfs with 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
Source File: MainActivity.java    From Pomfshare with 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 #9
Source File: DownloadExceptionUtils.java    From MediaSDK with 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 #10
Source File: MmsBodyProvider.java    From mollyim-android with 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 #11
Source File: ObservationStatsBuilder.java    From org.hl7.fhir.core with 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 #12
Source File: DataSet.java    From maxent_iis with 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 #13
Source File: TargetStorageMonitor.java    From ache with 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 #14
Source File: BaseIndexer.java    From q with 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 #15
Source File: FileUtils.java    From reader with MIT License 5 votes vote down vote up
private void threadhelper(final FileOp f, final CallbackContext callbackContext){
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            try {
                f.run();
            } catch ( Exception e) {
                e.printStackTrace();
                if( e instanceof EncodingException){
                    callbackContext.error(FileUtils.ENCODING_ERR);
                } else if(e instanceof FileNotFoundException) {
                    callbackContext.error(FileUtils.NOT_FOUND_ERR);
                } else if(e instanceof FileExistsException) {
                    callbackContext.error(FileUtils.PATH_EXISTS_ERR);
                } else if(e instanceof NoModificationAllowedException ) {
                    callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
                } else if(e instanceof InvalidModificationException ) {
                    callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
                } else if(e instanceof MalformedURLException ) {
                    callbackContext.error(FileUtils.ENCODING_ERR);
                } else if(e instanceof IOException ) {
                    callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
                } else if(e instanceof EncodingException ) {
                    callbackContext.error(FileUtils.ENCODING_ERR);
                } else if(e instanceof TypeMismatchException ) {
                    callbackContext.error(FileUtils.TYPE_MISMATCH_ERR);
                } else {
                	callbackContext.error(FileUtils.UNKNOWN_ERR);
                }
            }
        }
    });
}
 
Example #16
Source File: CameraLauncher.java    From jpHolo with MIT License 5 votes vote down vote up
/**
 * In the special case where the default width, height and quality are unchanged
 * we just write the file out to disk saving the expensive Bitmap.compress function.
 *
 * @param uri
 * @throws FileNotFoundException
 * @throws IOException
 */
private void writeUncompressedImage(Uri uri) throws FileNotFoundException,
        IOException {
    FileInputStream fis = new FileInputStream(FileHelper.stripFileProtocol(imageUri.toString()));
    OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
    byte[] buffer = new byte[4096];
    int len;
    while ((len = fis.read(buffer)) != -1) {
        os.write(buffer, 0, len);
    }
    os.flush();
    os.close();
    fis.close();
}
 
Example #17
Source File: SwiftRestClient.java    From sahara-extra with Apache License 2.0 5 votes vote down vote up
/**
 * Create a container -if it already exists, do nothing
 *
 * @param containerName the container name
 * @throws IOException IO problems
 * @throws SwiftBadRequestException invalid container name
 * @throws SwiftInvalidResponseException error from the server
 */
public void createContainer(String containerName) throws IOException {
  SwiftObjectPath objectPath = new SwiftObjectPath(containerName, "");
  try {
    //see if the data is there
    headRequest("createContainer", objectPath, NEWEST);
  } catch (FileNotFoundException ex) {
    int status = 0;
    try {
      status = putRequest(objectPath);
    } catch (FileNotFoundException e) {
      //triggered by a very bad container name.
      //re-insert the 404 result into the status
      status = SC_NOT_FOUND;
    }
    if (status == SC_BAD_REQUEST) {
      throw new SwiftBadRequestException(
        "Bad request -authentication failure or bad container name?",
        status,
        "PUT",
        null);
    }
    if (!isStatusCodeExpected(status,
            SC_OK,
            SC_CREATED,
            SC_ACCEPTED,
            SC_NO_CONTENT)) {
      throw new SwiftInvalidResponseException("Couldn't create container "
              + containerName +
              " for storing data in Swift." +
              " Try to create container " +
              containerName + " manually ",
              status,
              "PUT",
              null);
    } else {
      throw ex;
    }
  }
}
 
Example #18
Source File: Util.java    From ZeusHotfix with MIT License 5 votes vote down vote up
/**
 * 复制文件
 *
 * @param fromPathName
 * @param toPathName
 * @return
 */
public static int copy(String fromPathName, String toPathName) {
    try {
        File newFile = new File(toPathName);
        File parentFile = newFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        InputStream from = new FileInputStream(fromPathName);
        return copy(from, toPathName);
    } catch (FileNotFoundException e) {
        return -1;
    }
}
 
Example #19
Source File: Utils.java    From DoraemonKit with Apache License 2.0 5 votes vote down vote up
static Resources getResources(Context context, Request data) throws FileNotFoundException {
  if (data.resourceId != 0 || data.uri == null) {
    return context.getResources();
  }

  String pkg = data.uri.getAuthority();
  if (pkg == null) throw new FileNotFoundException("No package provided: " + data.uri);
  try {
    PackageManager pm = context.getPackageManager();
    return pm.getResourcesForApplication(pkg);
  } catch (PackageManager.NameNotFoundException e) {
    throw new FileNotFoundException("Unable to obtain resources for package: " + data.uri);
  }
}
 
Example #20
Source File: Application.java    From Passbook with Apache License 2.0 5 votes vote down vote up
void saveData(Context context) {
    if(mLocalVersion <= Options.mSyncVersion) {
        mLocalVersion++;
    }
    byte[] cipher = mCrypto.encrypt(mAccountManager.getBytes());
    byte[] header = FileHeader.build(APP_VERSION, mCrypto.getIterationCount(),
            Crypto.SALT_LENGTH, mCrypto.getIvLength(), mLocalVersion);
    byte[] keyInfo = mCrypto.getSaltAndIvBytes();
    try {
        FileOutputStream fos = context.openFileOutput(DATA_FILE, Context.MODE_PRIVATE);
        fos.write(header);
        fos.write(keyInfo);
        fos.write(cipher);
        int size = header.length + keyInfo.length + cipher.length;
        if (mBuffer == null || mBuffer.length != size) {
            mBuffer = new byte[size];
        }
        System.arraycopy(header, 0, mBuffer, 0, header.length);
        System.arraycopy(keyInfo, 0, mBuffer, header.length, keyInfo.length);
        System.arraycopy(cipher, 0, mBuffer, header.length + keyInfo.length, cipher.length);
        fos.close();
        mFileHeader = FileHeader.parse(mBuffer);
        mAccountManager.onSaved();
    }catch (FileNotFoundException e) {
        Log.w("Passbook", "File not found");
    }
    catch(IOException ioe) {
        Log.e("Passbook", "IOException");
    }
}
 
Example #21
Source File: FHIRMappingLanguageTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static Stream<Arguments> data()
  throws FileNotFoundException, IOException, ParserConfigurationException, SAXException {
  Document tests = XMLUtil.parseToDom(TestingUtilities.loadTestResource("r5", "fml", "manifest.xml"));
  Element test = XMLUtil.getFirstChild(tests.getDocumentElement());
  List<Arguments> objects = new ArrayList<>();
  while (test != null && test.getNodeName().equals("test")) {
    objects.add(Arguments.of(test.getAttribute("name"), test.getAttribute("source"), test.getAttribute("map"),
      test.getAttribute("output")));
    test = XMLUtil.getNextSibling(test);
  }
  return objects.stream();
}
 
Example #22
Source File: MainDexListBuilder.java    From Box with Apache License 2.0 5 votes vote down vote up
/**
 * Keep classes annotated with runtime annotations.
 */
private void keepAnnotated(Path path) throws FileNotFoundException {
    for (ClassPathElement element : path.getElements()) {
        forClazz:
            for (String name : element.list()) {
                if (name.endsWith(CLASS_EXTENSION)) {
                    DirectClassFile clazz = path.getClass(name);
                    if (hasRuntimeVisibleAnnotation(clazz)) {
                        filesToKeep.add(name);
                    } else {
                        MethodList methods = clazz.getMethods();
                        for (int i = 0; i<methods.size(); i++) {
                            if (hasRuntimeVisibleAnnotation(methods.get(i))) {
                                filesToKeep.add(name);
                                continue forClazz;
                            }
                        }
                        FieldList fields = clazz.getFields();
                        for (int i = 0; i<fields.size(); i++) {
                            if (hasRuntimeVisibleAnnotation(fields.get(i))) {
                                filesToKeep.add(name);
                                continue forClazz;
                            }
                        }
                    }
                }
            }
    }
}
 
Example #23
Source File: FileUtil.java    From imsdk-android with MIT License 5 votes vote down vote up
/**
 * Return the bytes in file by stream.
 *
 * @param file The file.
 * @return the bytes in file
 */
public static byte[] readFile2BytesByStream(final File file) {
    if (!isFileExists(file)) return null;
    try {
        return is2Bytes(new FileInputStream(file));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #24
Source File: PainteraConfigYaml.java    From paintera with 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 #25
Source File: JavaIoFileSystemAccess.java    From xtext-core with 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 #26
Source File: MiscTests.java    From hottub with 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 #27
Source File: TestTopology.java    From jstorm with Apache License 2.0 5 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 #28
Source File: FileContextTestHelper.java    From big-c with 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 #29
Source File: SelectFdsLimit.java    From openjdk-8 with 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 #30
Source File: EncryptedLOBFile.java    From gemfirexd-oss with 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;
}