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. 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 Project: Pomfshare   Source 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 2
Source Project: mmtf-spark   Source 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 3
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 4
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 5
Source Project: java-sdk   Source 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 6
Source Project: commons-vfs   Source 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 7
Source Project: athenz   Source 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 8
Source Project: lams   Source 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 9
Source Project: iBeebo   Source 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 10
Source Project: MediaSDK   Source 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 11
@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 12
Source Project: org.hl7.fhir.core   Source 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 13
Source Project: maxent_iis   Source 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 14
Source Project: ache   Source 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 15
Source Project: q   Source 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 16
Source Project: jstorm   Source File: TestTopology.java    License: 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 17
Source Project: BIMserver   Source 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
Source Project: yago3   Source 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
Source Project: dremio-oss   Source 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
Source Project: FireFiles   Source 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
Source Project: openjdk-jdk8u-backup   Source 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
Source Project: ache   Source 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
Source Project: Lottery   Source 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
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
Source Project: http4e   Source 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
Source Project: drftpd   Source 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
Source Project: tus-java-client   Source 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
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
@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
Source Project: java-technology-stack   Source 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;
}