Java Code Examples for java.io.FileNotFoundException

The following are top voted examples for showing how to use java.io.FileNotFoundException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: hacktoolkit-android_lib   File: FileUtils.java View source code Vote up 7 votes
public static ArrayList<String> readLines(Activity activity, String filename) throws IOException {
	Context context = activity.getApplicationContext();
	ArrayList<String> lines = new ArrayList<String>();
	try {
		FileInputStream fin = context.openFileInput(filename);
		if (fin != null) {
			InputStreamReader inputStreamReader = new InputStreamReader(fin);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String line;
			while (( line = bufferedReader.readLine() ) != null) {
				lines.add(line);
			}
			fin.close();
		}
	} catch (FileNotFoundException fnfe) {
		fnfe.printStackTrace();
	}
	return lines;
}
 
Example 2
Project: RadialFx   File: RadialGlobalMenu.java View source code Vote up 7 votes
private ImageView getImageView(final String path) {
ImageView imageView = null;
try {
    imageView = ImageViewBuilder.create()
	    .image(new Image(new FileInputStream(path))).build();
} catch (final FileNotFoundException e) {
    e.printStackTrace();
}
assert (imageView != null);
return imageView;

   }
 
Example 3
Project: Magnolia   File: DataTransporter.java View source code Vote up 7 votes
/**
 * @param file
 * @return XSL stream for Xml file or <code>null</code>
 */
protected static InputStream getXslStreamForXmlFile(File file) {
    InputStream xslStream = null;
    String xlsFilename = StringUtils.substringBeforeLast(file.getAbsolutePath(), ".") + ".xsl";
    File xslFile = new File(xlsFilename);
    if (xslFile.exists()) {
        try {
            xslStream = new FileInputStream(xslFile);
            log.info("XSL file for [" + file.getName() + "] found (" + xslFile.getName() + ")");
        } catch (FileNotFoundException e) { // should never happen (xslFile.exists())
            e.printStackTrace();
        }
    }
    return xslStream;
}
 
Example 4
Project: The-Digital-Parrot   File: ParrotModelFactory.java View source code Vote up 6 votes
public static ParrotModelFactory getInstance(Style style) {
	// get rid of classification status output 
	PelletOptions.USE_CLASSIFICATION_MONITOR = MonitorType.NONE;
	
	OntModel model = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC);
	
	File cacheDir = new File(System.getProperty("user.home") + File.separator + ".digital-parrot" + File.separator + "owl");
	if (cacheDir.exists() && cacheDir.isDirectory() && cacheDir.canRead()) {
		OntDocumentManager docManager = model.getDocumentManager();
		docManager.addAltEntry(URL_WGS84_POS, "file:" + cacheDir.getAbsolutePath() + File.separator + "wgs84_pos");
		docManager.addAltEntry(URL_TIME_AND_PLACE, "file:" + cacheDir.getAbsolutePath() + File.separator + "TimeAndPlace.owl");
		docManager.addAltEntry(URL_MEMORIES, "file:" + cacheDir.getAbsolutePath() + File.separator + "Memories.owl");
		docManager.addAltEntry(URL_FOAF, "file:" + cacheDir.getAbsolutePath() + File.separator + "foaf");
		docManager.addAltEntry(URL_INTERACTION, "file:" + cacheDir.getAbsolutePath() + File.separator + "Interaction.owl");
		docManager.addAltEntry(URL_CONFERENCES, "file:" + cacheDir.getAbsolutePath() + File.separator + "Conferences.owl");
		docManager.addAltEntry(URL_DIGITAL_PARROT, "file:" + cacheDir.getAbsolutePath() + File.separator + "DigitalParrot.owl");
	
		try {
			model.read(new FileReader(new File(cacheDir + File.separator + "annotated-types.rdf")), null);
		} catch (FileNotFoundException e) {
			e.printStackTrace(System.err);
		}
	}
	
	switch (style) {
	case TABLE:
		return new TableModelFactory(model);
	case GRAPH:
		return new GraphModelFactory(model);
	case COMBINED:
		return new CombinedModelFactory(model);
	default:
		throw new IllegalArgumentException("No such style: " + style);
	}
}
 
Example 5
Project: richfaces   File: ExternalContextImpl.java View source code Vote up 6 votes
@Override
public InputStream getResourceAsStream(String path) {
    File file = new File(webRoot, path);
    if (file.exists()) {
        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return null;
}
 
Example 6
Project: interface_sdk   File: ModuleManagerManifestLoader.java View source code Vote up 6 votes
/**
 * Creates a ModuleManagerMetaData object
 *
 * @param   path File path to a manifest for a module manager.
 */
public static ModuleManagerMetaData load(String path)
        throws ManifestLoadException {
    try {
        //return load(new FileInputStream(new File(path)));
        File f = new File(path);
        return load(new FileInputStream(new File(path)));
    } catch (FileNotFoundException e) {
        // TODO logging
        e.printStackTrace();
        throw new ManifestLoadException("Could not find the manifest file");
    }
}
 
Example 7
Project: extFM-Tooling   File: YMSTransformation.java View source code Vote up 6 votes
public void writeFile(File file, final Object object) {
	FileOutputStream fop = null;
	ByteArrayOutputStream out = new ByteArrayOutputStream();

	try {
		fop = new FileOutputStream(file);
	} catch (FileNotFoundException e1) {
		e1.printStackTrace();
	}
	Marshaller m;
	try {
		m = Context.getInstance().getJAXBContext().createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
		m.marshal(object, out);
		fop.write(out.toByteArray());
		fop.flush();
		fop.close();
	} catch (JAXBException | IOException e) {
		e.printStackTrace();
	}
	// get the content in bytes
	System.out.println("Done");
}
 
Example 8
Project: srht-android   File: Config.java View source code Vote up 6 votes
private static void write(){
    try {
        PrintWriter writer = new PrintWriter(jsonFile);
        writer.println(json.toString());
        writer.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example 9
Project: Android_Blog_Demos   File: GenerateValueFiles.java View source code Vote up 6 votes
private void generateXmlFile(int w, int h) {

		StringBuffer sbForWidth = new StringBuffer();
		sbForWidth.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
		sbForWidth.append("<resources>");
		float cellw = w * 1.0f / baseW;

		System.out.println("width : " + w + "," + baseW + "," + cellw);
		for (int i = 1; i < baseW; i++) {
			sbForWidth.append(WTemplate.replace("{0}", i + "").replace("{1}",
					change(cellw * i) + ""));
		}
		sbForWidth.append(WTemplate.replace("{0}", baseW + "").replace("{1}",
				w + ""));
		sbForWidth.append("</resources>");

		StringBuffer sbForHeight = new StringBuffer();
		sbForHeight.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
		sbForHeight.append("<resources>");
		float cellh = h *1.0f/ baseH;
		System.out.println("height : "+ h + "," + baseH + "," + cellh);
		for (int i = 1; i < baseH; i++) {
			sbForHeight.append(HTemplate.replace("{0}", i + "").replace("{1}",
					change(cellh * i) + ""));
		}
		sbForHeight.append(HTemplate.replace("{0}", baseH + "").replace("{1}",
				h + ""));
		sbForHeight.append("</resources>");

		File fileDir = new File(dirStr + File.separator
				+ VALUE_TEMPLATE.replace("{0}", h + "")//
						.replace("{1}", w + ""));
		fileDir.mkdir();

		File layxFile = new File(fileDir.getAbsolutePath(), "lay_x.xml");
		File layyFile = new File(fileDir.getAbsolutePath(), "lay_y.xml");
		try {
			PrintWriter pw = new PrintWriter(new FileOutputStream(layxFile));
			pw.print(sbForWidth.toString());
			pw.close();
			pw = new PrintWriter(new FileOutputStream(layyFile));
			pw.print(sbForHeight.toString());
			pw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
 
Example 10
Project: wso2-synapse   File: JsonFormatterTest.java View source code Vote up 6 votes
/**
 * NOTE: Under this test class, we cannot test the creation of JSON arrays by giving xml processing instructions to the
 * xml input string object. The reason is that when doing stringToOm and setting the SOAP child with addChild() method,
 * the addChild() method throws an exception saying that it does not support the xml PI node type.
 */

public void testCase() {
    try {
        InputStream inputStream = Util.getJson(0);

        MessageFormatter formatter = Util.newJsonFormatter();
        MessageContext messageContext = Util.newMessageContext();
        JsonUtil.newJsonPayload(messageContext, inputStream, false, false);
        OutputStream out = Util.newOutputStream();
        formatter.writeTo(messageContext, null, out, false);
        assertTrue(JsonDataSourceTest.expectedJSON.equals(out.toString()));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        assertTrue(false);
    } catch (AxisFault axisFault) {
        axisFault.printStackTrace();
        assertTrue(false);
    }
}
 
Example 11
Project: AirPlayer   File: BitmapUtils.java View source code Vote up 6 votes
public static Bitmap getBitmap(Context context, Uri uri) {
    Bitmap bm = null;
    if (uri != null) {
        try {
            bm = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    return bm;
}
 
Example 12
Project: ndogen_stalled   File: GeneratorUtils.java View source code Vote up 6 votes
public static void createSourceFile(String outFile, String srcCode, boolean append) {
	PrintWriter writer = null;
	try {
		File file = new File(outFile);
		File parentDir = file.getParentFile();
		if(parentDir != null) {
			parentDir.mkdirs();
		}
		writer = new PrintWriter(file);
		writer.write(srcCode);
		writer.close();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
		if (writer != null)
			writer.close();
	}
}
 
Example 13
Project: ldbc_snb_datagen   File: ConfigParser.java View source code Vote up 6 votes
public static Configuration readConfig(Configuration conf, String paramsFile ) {
    try {
        readConfig(conf, new FileInputStream(paramsFile));
    } catch (FileNotFoundException e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        System.exit(-1);
    }
    return conf;
}
 
Example 14
Project: mjprof   File: PathDataSourcePlugin.java View source code Vote up 6 votes
public PathDataSourcePlugin(String fileName) {
    this.fileName = fileName;

    try {
        reader = new BufferedReader(new FileReader(fileName));
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
 
Example 15
Project: xface-android   File: XXmlParser.java View source code Vote up 6 votes
/**
 * ?????????
 *
 * @param path
 *            ???
 */
public void setPath(String path) {
    if(null == path)
    {
        return;
    }
    File file = new File(path);
    try {
        setInput(new FileInputStream(file));
    } catch (FileNotFoundException e) {
        XLog.e(CLASS_NAME, "Can't find :" + path);
        e.printStackTrace();
    }
}
 
Example 16
Project: JAME   File: JSManager.java View source code Vote up 6 votes
/**
 * @param node
 * @param basedir
 * @param file
 * @throws JSException
 */
public static void execute(final RenderContext renderContext, final JSContext jsContext, final Node node, final File basedir, final File file) throws JSException {
	try {
		execute(renderContext, jsContext, node, basedir, new FileInputStream(file), file.getName());
	}
	catch (FileNotFoundException x) {
		throw new JSException(x.getMessage(), x);
	}
}
 
Example 17
Project: SharkFW   File: FSInformation.java View source code Vote up 6 votes
/**
 * Return an InputStream that allows streaming data into information object.
 * @return InputStream to information object
 */
@Override
public InputStream getInputStream() throws SharkKBException {
    try {
        return new FileInputStream(this.contentFile);
    } catch (FileNotFoundException ex) {
        throw new SharkKBException(ex.getMessage());
    }
}
 
Example 18
Project: hank   File: SQLEnvironmentsNotifierFactory.java View source code Vote up 6 votes
private EnvironmentYamlConfigurator(String environmentFilename, String databaseEnvironment) throws InvalidConfigurationException {
  this.databaseEnvironment = databaseEnvironment;
  try {
    loadFromFile(environmentFilename);
  } catch (FileNotFoundException e) {
    throw new InvalidConfigurationException("Can't find config file " + e.getMessage());
  }
}
 
Example 19
Project: tdq-studio-se   File: PlatformPathUtil.java View source code Vote up 6 votes
public static String getFilePathByPlatformURL(URL url) throws IOException {
    String filePath = url.getPath();
    try {
        url.openConnection().getInputStream();
    } catch (FileNotFoundException e) {
        // try to get the absolute path from exception message
        final String msg = e.getMessage();
        if (filePath.endsWith("/")) {
            filePath = filePath.substring(0, filePath.length() - 1);
        }
        final String osFilePath = filePath.replace("/", File.separator); //$NON-NLS-1$
        final int idx = msg.indexOf(osFilePath);
        if (idx > 0) {
            return msg.substring(0, idx + filePath.length());
        }
    }
    return filePath;
}
 
Example 20
Project: TestingStaff   File: LogoutRequestListener.java View source code Vote up 6 votes
@Override
  public void onFileNotFoundException(FileNotFoundException e, final Object state) {
final String message = e.getMessage();

mHandler.post(new Runnable() {
	public void run() {
		if(snsService != null)
              {
              	snsService.loggoutStatus(context, false, message);
              }
	}
});
  }
 
Example 21
Project: tcf   File: LocalTypedElement.java View source code Vote up 6 votes
/**
 * Return an input stream that opens that locally cached file to provide the
 * content.
 *
 * @return a buffered input stream containing the contents of this file
 * @exception CoreException
 *                if the contents of this storage could not be accessed
 */
@Override
protected InputStream createStream() throws CoreException {
	try {
		File cacheFile = node.getCacheFile();
		return new BufferedInputStream(new FileInputStream(cacheFile));
	} catch (FileNotFoundException e) {
		IStatus error = new Status(IStatus.ERROR,
				UIPlugin.getUniqueIdentifier(), e.getMessage(), e);
		throw new CoreException(error);
	}
}
 
Example 22
Project: mini-git-server   File: JettyServer.java View source code Vote up 6 votes
private Resource getBaseResource() throws IOException {
  if (baseResource == null) {
    try {
      baseResource = unpackWar();
    } catch (FileNotFoundException err) {
      if (err.getMessage() == GerritLauncher.NOT_ARCHIVED) {
        baseResource = useDeveloperBuild();
      } else {
        throw err;
      }
    }
  }
  return baseResource;
}
 
Example 23
Project: node-go-better-than-random   File: GameWriter.java View source code Vote up 6 votes
public GameWriter(GameFile gameFile, ConstGameTree tree,
                  String application, String version) throws ErrorMessage
{
    OutputStream out;
    try
    {
        out = new FileOutputStream(gameFile.m_file);
    }
    catch (FileNotFoundException e)
    {
        throw new ErrorMessage(e.getMessage());
    }
    switch (gameFile.m_format)
    {
    case SGF:
        new SgfWriter(out, tree, application, version);
        break;
    case XML:
        String xmlApplication = application;
        if (xmlApplication != null && version != null)
            xmlApplication = xmlApplication + ":" + version;
        new XmlWriter(out, tree, xmlApplication);
        break;
    }
}
 
Example 24
Project: picard-tools   File: MetricsFile.java View source code Vote up 6 votes
/**
 * Convenience method to read all the Metric beans from a metrics file.
 * @param file to be read.
 * @return list of beans from the file.
 */
public static List<? extends MetricBase> readBeans(final File file) {
    try {
        final MetricsFile<MetricBase, Comparable<?>> metricsFile = new MetricsFile<MetricBase, Comparable<?>>();
        metricsFile.read(new FileReader(file));
        return metricsFile.getMetrics();
    } catch (FileNotFoundException e) {
        throw new SAMException(e.getMessage(), e);
    }
}
 
Example 25
Project: dtangler   File: ItemDependenciesStreamParser.java View source code Vote up 6 votes
private BufferedReader getBufferedIOReader(File file) {
	if (file == null || file.getAbsolutePath() == null)
		throw new DtException(
				"could not read text file input: file name not specified");
	try {
		return new BufferedReader(new FileReader(file.getAbsolutePath()));
	} catch (FileNotFoundException e) {
		throw new DtException("could not read from file "
				+ file.getAbsolutePath() + ": " + e.getMessage());
	}
}
 
Example 26
Project: gluu-opendj   File: GenerateMessageFile.java View source code Vote up 6 votes
private InputStream getStubFile() {
  InputStream result = null;

  File stub = new File(getProjectBase(), MESSAGES_FILE_STUB);
  if ( stub.exists() ) {
    // this is the OpenDS's ant project calling
    // Stub is located at OPENDS_ROOT/resource/Messages.java.stub
    try {
      result = new FileInputStream(stub);
    } catch (FileNotFoundException e) {
      // should neven happen
      throw new BuildException("Unable to load template " +
            MESSAGES_FILE_STUB + ":  " + e.getMessage());
    }
  } else {
    // this is the example plugin's ant project calling
    // Stub is located at build-tools.jar:resource/Messages.java.stub
    result = getClass().getResourceAsStream(MESSAGES_FILE_STUB);
  }

  return result;
}
 
Example 27
Project: korsakow-editor   File: ResourceManager.java View source code Vote up 6 votes
public InputStream getResourceStream(String name) throws MissingResourceException {
	try {
		return new FileInputStream(getResourceFile(name));
	} catch (FileNotFoundException e) {
		throw new MissingResourceException(e.getMessage(), clazz.getCanonicalName(), name);
	}
}
 
Example 28
Project: xmind   File: MindMapImageExporter.java View source code Vote up 6 votes
/**
 * 
 */
private void recreateTargetStreamFromFile() {
    FileUtils.ensureFileParent(targetFile);
    try {
        this.targetStream = new FileOutputStream(targetFile);
        this.streamToClose = this.targetStream;
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}
 
Example 29
Project: yarep   File: VirtualFileSystemNode.java View source code Vote up 6 votes
/**
 * @see org.wyona.yarep.core.Node#getOutputStream()
 */
public OutputStream getOutputStream() throws RepositoryException {
    try {
        if (isCollection()) {
            if (getRepository().getAlternative() != null) {
                File alternativeFile = new File(contentFile, getRepository().getAlternative());
                if (alternativeFile.isFile()) {
                    return new VirtualFileSystemOutputStream(this, alternativeFile);
                } else {
                    throw new RepositoryException("Is not a file: " + alternativeFile);
                }
            } else {
                throw new RepositoryException("Is a directory: " + this.contentFile);
            }
        } else {
            //return new FileOutputStream(this.contentFile);
            log.debug("Write content to '" + contentFile + "'");
            return new VirtualFileSystemOutputStream(this, this.contentFile);
        }
    } catch (FileNotFoundException e) {
        throw new RepositoryException(e.getMessage(), e);
    }
    //return getProperty(PROPERTY_CONTENT).getOutputStream();
}
 
Example 30
Project: transdroid   File: TtorrentAdapter.java View source code Vote up 6 votes
private String makeUploadRequest(String path, String file, Log log) throws DaemonException {

		try {

			// Setup request using POST
			HttpPost httppost = new HttpPost(buildWebUIUrl(path));
			File upload = new File(URI.create(file));
			Part[] parts = {new FilePart("torrentfile", upload)};
			httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
			return makeWebRequest(httppost, log);

		} catch (FileNotFoundException e) {
			throw new DaemonException(ExceptionType.FileAccessError, e.toString());
		}

	}
 
Example 31
Project: baker-android   File: DownloadThread.java View source code Vote up 6 votes
/**
 * Prepare the destination file to receive data. If the file already exists,
 * we'll set up appropriately for resumption.
 */
private void setupDestinationFile(State state, InnerState innerState)
        throws StopRequest {
    if (state.mFilename != null) { // only true if we've already run a
                                   // thread for this download
        if (!Helpers.isFilenameValid(state.mFilename)) {
            // this should never happen
            throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                    "found invalid internal destination filename");
        }
        // We're resuming a download that got interrupted
        File f = new File(state.mFilename);
        if (f.exists()) {
            long fileLength = f.length();
            if (fileLength == 0) {
                // The download hadn't actually started, we can restart from
                // scratch
                f.delete();
                state.mFilename = null;
            } else if (mInfo.mETag == null) {
                // This should've been caught upon failure
                f.delete();
                throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
                        "Trying to resume a download that can't be resumed");
            } else {
                // All right, we'll be able to resume this download
                try {
                    state.mStream = new FileOutputStream(state.mFilename, true);
                } catch (FileNotFoundException exc) {
                    throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + exc.toString(), exc);
                }
                innerState.mBytesSoFar = (int) fileLength;
                if (mInfo.mTotalBytes != -1) {
                    innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
                }
                innerState.mHeaderETag = mInfo.mETag;
                innerState.mContinuingDownload = true;
            }
        }
    }

    if (state.mStream != null) {
        closeDestination(state);
    }
}
 
Example 32
Project: packages_providers_downloadprovider   File: DownloadThread.java View source code Vote up 6 votes
/**
 * Prepare the destination file to receive data.  If the file already exists, we'll set up
 * appropriately for resumption.
 */
private void setupDestinationFile(State state, InnerState innerState)
        throws StopRequest {
    if (!TextUtils.isEmpty(state.mFilename)) { // only true if we've already run a thread for this download
        if (!Helpers.isFilenameValid(state.mFilename)) {
            // this should never happen
            throw new StopRequest(Downloads.Impl.STATUS_FILE_ERROR,
                    "found invalid internal destination filename");
        }
        // We're resuming a download that got interrupted
        File f = new File(state.mFilename);
        if (f.exists()) {
            long fileLength = f.length();
            if (fileLength == 0) {
                // The download hadn't actually started, we can restart from scratch
                f.delete();
                state.mFilename = null;
            } else if (mInfo.mETag == null && !mInfo.mNoIntegrity) {
                // This should've been caught upon failure
                f.delete();
                throw new StopRequest(Downloads.Impl.STATUS_CANNOT_RESUME,
                        "Trying to resume a download that can't be resumed");
            } else {
                // All right, we'll be able to resume this download
                try {
                    state.mStream = new FileOutputStream(state.mFilename, true);
                } catch (FileNotFoundException exc) {
                    throw new StopRequest(Downloads.Impl.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + exc.toString(), exc);
                }
                innerState.mBytesSoFar = (int) fileLength;
                if (mInfo.mTotalBytes != -1) {
                    innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
                }
                innerState.mHeaderETag = mInfo.mETag;
                innerState.mContinuingDownload = true;
            }
        }
    }

    if (state.mStream != null && mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL
            && !isDrmFile(state)) {
        closeDestination(state);
    }
}
 
Example 33
Project: Unity35AndroidSplitter   File: DownloadThread.java View source code Vote up 6 votes
/**
 * Prepare the destination file to receive data. If the file already exists,
 * we'll set up appropriately for resumption.
 */
private void setupDestinationFile(State state, InnerState innerState)
        throws StopRequest {
    if (state.mFilename != null) { // only true if we've already run a
                                   // thread for this download
        if (!Helpers.isFilenameValid(state.mFilename)) {
            // this should never happen
            throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                    "found invalid internal destination filename");
        }
        // We're resuming a download that got interrupted
        File f = new File(state.mFilename);
        if (f.exists()) {
            long fileLength = f.length();
            if (fileLength == 0) {
                // The download hadn't actually started, we can restart from
                // scratch
                f.delete();
                state.mFilename = null;
            } else if (mInfo.mETag == null) {
                // This should've been caught upon failure
                f.delete();
                throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
                        "Trying to resume a download that can't be resumed");
            } else {
                // All right, we'll be able to resume this download
                try {
                    state.mStream = new FileOutputStream(state.mFilename, true);
                } catch (FileNotFoundException exc) {
                    throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + exc.toString(), exc);
                }
                innerState.mBytesSoFar = (int) fileLength;
                if (mInfo.mTotalBytes != -1) {
                    innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
                }
                innerState.mHeaderETag = mInfo.mETag;
                innerState.mContinuingDownload = true;
            }
        }
    }

    if (state.mStream != null) {
        closeDestination(state);
    }
}
 
Example 34
Project: UnityOBBDownloader   File: DownloadThread.java View source code Vote up 6 votes
/**
 * Prepare the destination file to receive data. If the file already exists,
 * we'll set up appropriately for resumption.
 */
private void setupDestinationFile(State state, InnerState innerState)
        throws StopRequest {
    if (state.mFilename != null) { // only true if we've already run a
                                   // thread for this download
        if (!Helpers.isFilenameValid(state.mFilename)) {
            // this should never happen
            throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                    "found invalid internal destination filename");
        }
        // We're resuming a download that got interrupted
        File f = new File(state.mFilename);
        if (f.exists()) {
            long fileLength = f.length();
            if (fileLength == 0) {
                // The download hadn't actually started, we can restart from
                // scratch
                f.delete();
                state.mFilename = null;
            } else if (mInfo.mETag == null) {
                // This should've been caught upon failure
                f.delete();
                throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
                        "Trying to resume a download that can't be resumed");
            } else {
                // All right, we'll be able to resume this download
                try {
                    state.mStream = new FileOutputStream(state.mFilename, true);
                } catch (FileNotFoundException exc) {
                    throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + exc.toString(), exc);
                }
                innerState.mBytesSoFar = (int) fileLength;
                if (mInfo.mTotalBytes != -1) {
                    innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
                }
                innerState.mHeaderETag = mInfo.mETag;
                innerState.mContinuingDownload = true;
            }
        }
    }

    if (state.mStream != null) {
        closeDestination(state);
    }
}
 
Example 35
Project: apache-nutch-fork   File: CollectionManager.java View source code Vote up 6 votes
/**
 * Save collections into file
 * 
 * @throws Exception
 */
public void save() throws IOException {
  try {
    final FileOutputStream fos = new FileOutputStream(new File(configfile
        .getFile()));
    final Document doc = new DocumentImpl();
    final Element collections = doc
        .createElement(Subcollection.TAG_COLLECTIONS);
    final Iterator iterator = collectionMap.values().iterator();

    while (iterator.hasNext()) {
      final Subcollection subCol = (Subcollection) iterator.next();
      final Element collection = doc
          .createElement(Subcollection.TAG_COLLECTION);
      collections.appendChild(collection);
      final Element name = doc.createElement(Subcollection.TAG_NAME);
      name.setNodeValue(subCol.getName());
      collection.appendChild(name);
      final Element whiteList = doc
          .createElement(Subcollection.TAG_WHITELIST);
      whiteList.setNodeValue(subCol.getWhiteListString());
      collection.appendChild(whiteList);
      final Element blackList = doc
          .createElement(Subcollection.TAG_BLACKLIST);
      blackList.setNodeValue(subCol.getBlackListString());
      collection.appendChild(blackList);
    }

    DomUtil.saveDom(fos, collections);
    fos.flush();
    fos.close();
  } catch (FileNotFoundException e) {
    throw new IOException(e.toString());
  }
}
 
Example 36
Project: googleplaycrawler   File: CollectionManager.java View source code Vote up 6 votes
/**
 * Save collections into file
 * 
 * @throws Exception
 */
public void save() throws IOException {
  try {
    final FileOutputStream fos = new FileOutputStream(new File(configfile
        .getFile()));
    final Document doc = new DocumentImpl();
    final Element collections = doc
        .createElement(Subcollection.TAG_COLLECTIONS);
    final Iterator iterator = collectionMap.values().iterator();

    while (iterator.hasNext()) {
      final Subcollection subCol = (Subcollection) iterator.next();
      final Element collection = doc
          .createElement(Subcollection.TAG_COLLECTION);
      collections.appendChild(collection);
      final Element name = doc.createElement(Subcollection.TAG_NAME);
      name.setNodeValue(subCol.getName());
      collection.appendChild(name);
      final Element whiteList = doc
          .createElement(Subcollection.TAG_WHITELIST);
      whiteList.setNodeValue(subCol.getWhiteListString());
      collection.appendChild(whiteList);
      final Element blackList = doc
          .createElement(Subcollection.TAG_BLACKLIST);
      blackList.setNodeValue(subCol.getBlackListString());
      collection.appendChild(blackList);
    }

    DomUtil.saveDom(fos, collections);
    fos.flush();
    fos.close();
  } catch (FileNotFoundException e) {
    throw new IOException(e.toString());
  }
}
 
Example 37
Project: Jancilla   File: XMLSchemaValidator.java View source code Vote up 6 votes
/**
 * The method checks if the document is well-formed. 
 *  
 * @param documentUrl URL of the document
 * @return Returns <code>true</code> if the document is well-formed otherwise <code>false</code>.
 */
public static boolean isWellFormed(String documentUrl) {
	boolean result = false;
	try {
		result = isWellFormed(new FileInputStream(documentUrl));
	} catch (FileNotFoundException e) {
		result = false;
		mParseErrorText += e.toString();
	}
	
	return result;
}
 
Example 38
Project: WatchList   File: CollectionManager.java View source code Vote up 6 votes
/**
 * Save collections into file
 * 
 * @throws Exception
 */
public void save() throws IOException {
  try {
    final FileOutputStream fos = new FileOutputStream(new File(configfile
        .getFile()));
    final Document doc = new DocumentImpl();
    final Element collections = doc
        .createElement(Subcollection.TAG_COLLECTIONS);
    final Iterator iterator = collectionMap.values().iterator();

    while (iterator.hasNext()) {
      final Subcollection subCol = (Subcollection) iterator.next();
      final Element collection = doc
          .createElement(Subcollection.TAG_COLLECTION);
      collections.appendChild(collection);
      final Element name = doc.createElement(Subcollection.TAG_NAME);
      name.setNodeValue(subCol.getName());
      collection.appendChild(name);
      final Element whiteList = doc
          .createElement(Subcollection.TAG_WHITELIST);
      whiteList.setNodeValue(subCol.getWhiteListString());
      collection.appendChild(whiteList);
      final Element blackList = doc
          .createElement(Subcollection.TAG_BLACKLIST);
      blackList.setNodeValue(subCol.getBlackListString());
      collection.appendChild(blackList);
    }

    DomUtil.saveDom(fos, collections);
    fos.flush();
    fos.close();
  } catch (FileNotFoundException e) {
    throw new IOException(e.toString());
  }
}
 
Example 39
Project: konkamusic   File: DownloadThread.java View source code Vote up 6 votes
/**
 * ??????????????????????????????? Prepare the destination file to receive data. If the file already exists, we'll set up appropriately for resumption.
 */
private void setupDestinationFile(State state, InnerState innerState) throws StopRequest {
	if (!TextUtils.isEmpty(state.mFilename)) { // only true if we've already???????
		// run a thread for this
		// download
		if (!Helpers.isFilenameValid(state.mFilename)) {
			// this should never happen
			throw new StopRequest(Downloads.STATUS_FILE_ERROR, "found invalid internal destination filename");
		}
		// We're resuming a download that got interrupted
		File f = new File(state.mFilename);
		if (f.exists()) {
			long fileLength = f.length();
			if (fileLength == 0) {
				// The download hadn't actually started, we can restart from
				// scratch
				f.delete();
				state.mFilename = null;
			} else if (mInfo.mETag == null && !mInfo.mNoIntegrity) {//mInfo.mNoIntegrity????true
				// This should've been caught upon failure
				f.delete();
				throw new StopRequest(Downloads.STATUS_CANNOT_RESUME, "Trying to resume a download that can't be resumed");
			} else {
				// All right, we'll be able to resume this download
				try {
					state.mStream = new FileOutputStream(state.mFilename, true);
				} catch (FileNotFoundException exc) {
					throw new StopRequest(Downloads.STATUS_FILE_ERROR, "while opening destination for resuming: " + exc.toString(), exc);
				}
				innerState.mBytesSoFar = (int) fileLength;
				if (mInfo.mTotalBytes != -1) {
					innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
				}
				innerState.mHeaderETag = mInfo.mETag;
				innerState.mContinuingDownload = true;
			}
		}
	}

	if (state.mStream != null && mInfo.mDestination == Downloads.DESTINATION_EXTERNAL) {
		closeDestination(state);
	}
}
 
Example 40
Project: xbnjava   File: ATDetectInternet.java View source code Vote up 6 votes
/**
   <p>Do it. Uh huh. Oh yeah.</p>
 */
public void execute() throws BuildException  {
   if(sUrl == null  ||  sUrl.length() == 0)  {
      throw  new BuildException("Parameter url ('" + sUrl + "') is null or empty.");
   }

   if(sProperty == null  ||  sProperty.length() == 0)  {
      throw  new BuildException("Parameter property ('" + sProperty + "') is null or empty.");
   }

   //Copied from xbn.util.Utility.appendWebPageSource

   try  {
      URL url = new URL(sUrl);
      InputStream isUNUSED = url.openStream();
      getProject().setProperty(sProperty, "true");
   }  catch(UnknownHostException uhx)  {
      System.out.println("INTERNET IS NOT AVAILABLE, or provided host is invalid. " + uhx.toString());
   }  catch(MalformedURLException mux)  {
      throw  new BuildException("Parameter url ('" + sUrl + "') is a malformed url. " + mux.toString() + ". (It does seem that we are connected to the internet, otherwise a uhx would have been thrown.)");
   }  catch(FileNotFoundException fnfx)  {
      throw  new BuildException("Parameter url ('" + sUrl + "') is invalid. " + fnfx.toString() + ". (It does seem that we are connected to the internet, otherwise a uhx would have been thrown.)");
   }  catch(IOException iox)  {
      System.out.println("INTERNET IS NOT AVAILABLE. " + iox.toString());
   }
}
 
Example 41
Project: core-android   File: DownloadThread.java View source code Vote up 6 votes
/**
 * Prepare the destination file to receive data. If the file already exists,
 * we'll set up appropriately for resumption.
 */
private void setupDestinationFile(State state, InnerState innerState)
        throws StopRequest {
    if (state.mFilename != null) { // only true if we've already run a
                                   // thread for this download
        if (!Helpers.isFilenameValid(state.mFilename)) {
            // this should never happen
            throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                    "found invalid internal destination filename");
        }
        // We're resuming a download that got interrupted
        File f = new File(state.mFilename);
        if (f.exists()) {
            long fileLength = f.length();
            if (fileLength == 0) {
                // The download hadn't actually started, we can restart from
                // scratch
                f.delete();
                state.mFilename = null;
            } else if (mInfo.mETag == null) {
                // This should've been caught upon failure
                f.delete();
                throw new StopRequest(DownloaderService.STATUS_CANNOT_RESUME,
                        "Trying to resume a download that can't be resumed");
            } else {
                // All right, we'll be able to resume this download
                try {
                    state.mStream = new FileOutputStream(state.mFilename, true);
                } catch (FileNotFoundException exc) {
                    throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + exc.toString(), exc);
                }
                innerState.mBytesSoFar = (int) fileLength;
                if (mInfo.mTotalBytes != -1) {
                    innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
                }
                innerState.mHeaderETag = mInfo.mETag;
                innerState.mContinuingDownload = true;
            }
        }
    }

    if (state.mStream != null) {
        closeDestination(state);
    }
}
 
Example 42
Project: deb-kitkat-storage-access-framework   File: SkyDriveProvider.java View source code Vote up 6 votes
/**
 * ????????????????
 * 
 * @param documentId
 * @throws FileNotFoundException
 */
@Override
public void deleteDocument(String documentId) throws FileNotFoundException {
    // FIXME ????????delete???????????why?
    // java.lang.SecurityException: android:deleteDocument: Neither user 10079 nor current process has write permission on content://com.uphyca.kitkat.storage.documents/document/file.1528683a3710d39f.1528683A3710D39F!1109.
    //   at android.app.ContextImpl.enforceForUri(ContextImpl.java:1811)
    //   at android.app.ContextImpl.enforceCallingOrSelfUriPermission(ContextImpl.java:1840)
    //   at android.content.ContextWrapper.enforceCallingOrSelfUriPermission(ContextWrapper.java:622)
    //   at android.provider.DocumentsProvider.call(DocumentsProvider.java:499)
    //   at android.content.ContentProvider$Transport.call(ContentProvider.java:325)
    //   at android.content.ContentProviderClient.call(ContentProviderClient.java:392)
    //   at android.provider.DocumentsContract.deleteDocument(DocumentsContract.java:812)
    //   at android.provider.DocumentsContract.deleteDocument(DocumentsContract.java:796)
    //   at com.uphyca.kitkat.storage.ui.MainFragment$4.doInBackground(MainFragment.java:221)
    //   at com.uphyca.kitkat.storage.ui.MainFragment$4.doInBackground(MainFragment.java:1)
    //   at android.os.AsyncTask$2.call(AsyncTask.java:288)
    //   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    //   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    //   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    //   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    //   at java.lang.Thread.run(Thread.java:841)

    try {
        mSkyDriveClient.delete(documentId);
    } catch (IOException e) {
        FileNotFoundException fileNotFound = new FileNotFoundException(e.getMessage());
        fileNotFound.initCause(e);
        throw fileNotFound;
    }
}
 
Example 43
Project: IOCipher   File: IoBridge.java View source code Vote up 6 votes
/**
 * java.io only throws FileNotFoundException when opening files, regardless of what actually
 * went wrong. Additionally, java.io is more restrictive than POSIX when it comes to opening
 * directories: POSIX says read-only is okay, but java.io doesn't even allow that. We also
 * have an Android-specific hack to alter the default permissions.
 */
public static FileDescriptor open(String path, int flags) throws FileNotFoundException {
    FileDescriptor fd = null;
    try {
        // On Android, we don't want default permissions to allow global access.
        int mode = ((flags & O_ACCMODE) == O_RDONLY) ? 0 : 0600;
        fd = Libcore.os.open(path, flags, mode);
        if (fd.valid()) {
            // Posix open(2) fails with EISDIR only if you ask for write permission.
            // Java disallows reading directories too.
            if (S_ISDIR(Libcore.os.fstat(fd).st_mode)) {
                throw new ErrnoException("open", EISDIR);
            }
        }
        return fd;
    } catch (ErrnoException errnoException) {
        try {
            if (fd != null) {
                IoUtils.close(fd);
            }
        } catch (IOException ignored) {
        }
        FileNotFoundException ex = new FileNotFoundException(path + ": " + errnoException.getMessage());
        ex.initCause(errnoException);
        throw ex;
    }
}
 
Example 44
Project: jgit   File: FileSender.java View source code Vote up 6 votes
FileSender(final File path) throws FileNotFoundException {
	this.path = path;
	this.source = new RandomAccessFile(path, "r");

	try {
		this.lastModified = path.lastModified();
		this.fileLen = source.getChannel().size();
		this.end = fileLen;
	} catch (IOException e) {
		try {
			source.close();
		} catch (IOException closeError) {
			// Ignore any error closing the stream.
		}

		final FileNotFoundException r;
		r = new FileNotFoundException(MessageFormat.format(HttpServerText.get().cannotGetLengthOf, path));
		r.initCause(e);
		throw r;
	}
}
 
Example 45
Project: commons-eid   File: BeIDCard.java View source code Vote up 6 votes
/**
 * Selects a file to read on the card
 * 
 * @param fileId
 *            the file to read
 * @return this BeIDCard Instance, to allow method chaining.
 * @throws CardException
 * @throws FileNotFoundException
 */
public BeIDCard selectFile(final byte[] fileId) throws CardException,
		FileNotFoundException {
	this.logger.debug("selecting file");
	final ResponseAPDU responseApdu = transmitCommand(
			BeIDCommandAPDU.SELECT_FILE, fileId);
	if (0x9000 != responseApdu.getSW()) {
		final FileNotFoundException fnfEx = new FileNotFoundException(
				"wrong status word after selecting file: "
						+ Integer.toHexString(responseApdu.getSW()));
		fnfEx.initCause(new ResponseAPDUException(responseApdu));
		throw fnfEx;
	}

	try {
		// SCARD_E_SHARING_VIOLATION fix
		Thread.sleep(20);
	} catch (final InterruptedException e) {
		throw new RuntimeException("sleep error: " + e.getMessage());
	}

	return this;
}
 
Example 46
Project: j2objc   File: IoBridge.java View source code Vote up 6 votes
/**
 * java.io only throws FileNotFoundException when opening files, regardless of what actually
 * went wrong. Additionally, java.io is more restrictive than POSIX when it comes to opening
 * directories: POSIX says read-only is okay, but java.io doesn't even allow that. We also
 * have an Android-specific hack to alter the default permissions.
 */
public static FileDescriptor open(String path, int flags) throws FileNotFoundException {
    FileDescriptor fd = null;
    try {
        // On Android, we don't want default permissions to allow global access.
        int mode = ((flags & O_ACCMODE) == O_RDONLY) ? 0 : 0600;
        fd = Libcore.os.open(path, flags, mode);
        // Posix open(2) fails with EISDIR only if you ask for write permission.
        // Java disallows reading directories too.
        if (isDirectory(path)) {
            throw new ErrnoException("open", EISDIR);
        }
        return fd;
    } catch (ErrnoException errnoException) {
        try {
            if (fd != null) {
                IoUtils.close(fd);
            }
        } catch (IOException ignored) {
        }
        FileNotFoundException ex = new FileNotFoundException(path + ": " + errnoException.getMessage());
        ex.initCause(errnoException);
        throw ex;
    }
}
 
Example 47
Project: android_platform_libcore   File: IoBridge.java View source code Vote up 6 votes
/**
 * java.io only throws FileNotFoundException when opening files, regardless of what actually
 * went wrong. Additionally, java.io is more restrictive than POSIX when it comes to opening
 * directories: POSIX says read-only is okay, but java.io doesn't even allow that. We also
 * have an Android-specific hack to alter the default permissions.
 */
public static FileDescriptor open(String path, int flags) throws FileNotFoundException {
    FileDescriptor fd = null;
    try {
        // On Android, we don't want default permissions to allow global access.
        int mode = ((flags & O_ACCMODE) == O_RDONLY) ? 0 : 0600;
        fd = Libcore.os.open(path, flags, mode);
        if (fd.valid()) {
            // Posix open(2) fails with EISDIR only if you ask for write permission.
            // Java disallows reading directories too.
            if (S_ISDIR(Libcore.os.fstat(fd).st_mode)) {
                throw new ErrnoException("open", EISDIR);
            }
        }
        return fd;
    } catch (ErrnoException errnoException) {
        try {
            if (fd != null) {
                IoUtils.close(fd);
            }
        } catch (IOException ignored) {
        }
        FileNotFoundException ex = new FileNotFoundException(path + ": " + errnoException.getMessage());
        ex.initCause(errnoException);
        throw ex;
    }
}
 
Example 48
Project: iaf   File: StreamUtil.java View source code Vote up 6 votes
public static OutputStream getOutputStream(Object target) throws IOException {
	if (target instanceof OutputStream) {
		return (OutputStream) target;
	} 
	if (target instanceof String) {
		String filename=(String)target;
		if (StringUtils.isEmpty(filename)) {
			throw new IOException("target string cannot be empty but must contain a filename");
		}
		try {
			return new FileOutputStream(filename);
		} catch (FileNotFoundException e) {
			FileNotFoundException fnfe = new FileNotFoundException("cannot create file ["+filename+"]");
			fnfe.initCause(e);
			throw fnfe;					
		}
	}
	return null;
}
 
Example 49
Project: IKVM.NET-cvs-clone   File: Win32ShellFolderManager2.java View source code Vote up 6 votes
@Override
public ShellFolder createShellFolder(File file) throws FileNotFoundException {
    try{
        return new Win32ShellFolder2(file);
    }catch(IOException ex){
        FileNotFoundException fnfex = new FileNotFoundException("File " + file.getAbsolutePath() + " not found");
        fnfex.initCause(ex);
        throw fnfex;
    }
}
 
Example 50
Project: TNT4J   File: TrackerConfigStore.java View source code Vote up 6 votes
private BufferedReader getConfigReader(String fileName) throws IOException {
BufferedReader reader = null;
IOException exc = null;

try {
	if (fileName != null) {
		reader = new BufferedReader(new FileReader(fileName));
		return reader;
	}
} catch (IOException err) {
	exc = err;
}

String tnt4JResource = "/" + TNT4J_PROPERTIES;
InputStream ins = getClass().getResourceAsStream(tnt4JResource);
if (ins == null) {
	FileNotFoundException ioe =  new FileNotFoundException("Resource '" + tnt4JResource + "' not found");
	ioe.initCause(exc);
	throw ioe;
}
reader = new BufferedReader(new InputStreamReader(ins));
return reader;
  }
 
Example 51
Project: android-libcore64   File: IoBridge.java View source code Vote up 6 votes
/**
 * java.io only throws FileNotFoundException when opening files, regardless of what actually
 * went wrong. Additionally, java.io is more restrictive than POSIX when it comes to opening
 * directories: POSIX says read-only is okay, but java.io doesn't even allow that. We also
 * have an Android-specific hack to alter the default permissions.
 */
public static FileDescriptor open(String path, int flags) throws FileNotFoundException {
    FileDescriptor fd = null;
    try {
        // On Android, we don't want default permissions to allow global access.
        int mode = ((flags & O_ACCMODE) == O_RDONLY) ? 0 : 0600;
        fd = Libcore.os.open(path, flags, mode);
        if (fd.valid()) {
            // Posix open(2) fails with EISDIR only if you ask for write permission.
            // Java disallows reading directories too.
            if (S_ISDIR(Libcore.os.fstat(fd).st_mode)) {
                throw new ErrnoException("open", EISDIR);
            }
        }
        return fd;
    } catch (ErrnoException errnoException) {
        try {
            if (fd != null) {
                IoUtils.close(fd);
            }
        } catch (IOException ignored) {
        }
        FileNotFoundException ex = new FileNotFoundException(path + ": " + errnoException.getMessage());
        ex.initCause(errnoException);
        throw ex;
    }
}
 
Example 52
Project: android_packages_apps_DocumentsUI   File: DocumentInfo.java View source code Vote up 6 votes
public static FileNotFoundException asFileNotFoundException(Throwable t)
        throws FileNotFoundException {
    if (t instanceof FileNotFoundException) {
        throw (FileNotFoundException) t;
    }
    final FileNotFoundException fnfe = new FileNotFoundException(t.getMessage());
    fnfe.initCause(t);
    throw fnfe;
}
 
Example 53
Project: android-sdk-sources-for-api-level-23   File: DocumentInfo.java View source code Vote up 6 votes
public static FileNotFoundException asFileNotFoundException(Throwable t)
        throws FileNotFoundException {
    if (t instanceof FileNotFoundException) {
        throw (FileNotFoundException) t;
    }
    final FileNotFoundException fnfe = new FileNotFoundException(t.getMessage());
    fnfe.initCause(t);
    throw fnfe;
}
 
Example 54
Project: incubator-slider   File: LongLivedProcess.java View source code Vote up 6 votes
/**
 * Exec the process
 * @return the process
 * @throws IOException on aany failure to start the process
 * @throws FileNotFoundException if the process could not be found
 */
private Process spawnChildProcess() throws IOException {
  if (process != null) {
    throw new IOException("Process already started");
  }
  if (LOG.isDebugEnabled()) {
    LOG.debug("Spawning process:\n " + describeBuilder());
  }
  try {
    process = processBuilder.start();
  } catch (IOException e) {
    // on windows, upconvert DOS error 2 from ::CreateProcess()
    // to its real meaning: FileNotFound
    if (e.toString().contains("CreateProcess error=2")) {
      FileNotFoundException fnfe =
          new FileNotFoundException(e.toString());
      fnfe.initCause(e);
      throw fnfe;
    } else {
      throw e;
    }
  }
  return process;
}
 
Example 55
Project: Appsii   File: ThemingUtils.java View source code Vote up 6 votes
public static InputStream createWallpaperInputStream(Context context, String preferenceValue)
        throws FileNotFoundException {
    File file = new File(preferenceValue);
    if (file.exists()) {
        return new FileInputStream(file);
    }

    Uri uri = Uri.parse(preferenceValue);
    ContentResolver contentResolver = context.getContentResolver();
    try {
        return contentResolver.openInputStream(uri);
    } catch (SecurityException e) {
        Log.i("ThemingUtils", "unable to open background image", e);
        FileNotFoundException fileNotFoundException = new FileNotFoundException(e.getMessage());
        fileNotFoundException.initCause(e);
        throw fileNotFoundException;
    }
}
 
Example 56
Project: classlib6   File: FileChannelImpl.java View source code Vote up 6 votes
private VMFileHandle open (String path, int mode) throws FileNotFoundException
{
  try
  {
      return VMIOUtils.getAPI().open(VMFile.getNormalizedPath(path), VMOpenMode.valueOf(mode));
  }
  catch (IOException e)
  {
      FileNotFoundException fnf = new FileNotFoundException("can't find "+path);
      fnf.initCause(e);
      throw fnf;
  }
}
 
Example 57
Project: metafacture-core   File: ResourceUtil.java View source code Vote up 6 votes
private static void throwFileNotFoundException(final String name,
		final Throwable t) throws FileNotFoundException {
	final FileNotFoundException e = new FileNotFoundException(
			"No file, resource or URL found: " + name);
	if (t != null) {
		e.initCause(t);
	}
	throw e;
}
 
Example 58
Project: liferay-ide   File: ZipUtil.java View source code Vote up 6 votes
public static ZipFile open(final File file)

		throws IOException

	{
		try {
			return new ZipFile(file);
		}
		catch (FileNotFoundException e) {
			final FileNotFoundException fnfe = new FileNotFoundException(file.getAbsolutePath());

			fnfe.initCause(e);

			throw fnfe;
		}
	}
 
Example 59
Project: ARTPart   File: IoBridge.java View source code Vote up 6 votes
/**
 * java.io only throws FileNotFoundException when opening files, regardless of what actually
 * went wrong. Additionally, java.io is more restrictive than POSIX when it comes to opening
 * directories: POSIX says read-only is okay, but java.io doesn't even allow that. We also
 * have an Android-specific hack to alter the default permissions.
 */
public static FileDescriptor open(String path, int flags) throws FileNotFoundException {
    FileDescriptor fd = null;
    try {
        // On Android, we don't want default permissions to allow global access.
        int mode = ((flags & O_ACCMODE) == O_RDONLY) ? 0 : 0600;
        fd = Libcore.os.open(path, flags, mode);
        // Posix open(2) fails with EISDIR only if you ask for write permission.
        // Java disallows reading directories too.
        if (S_ISDIR(Libcore.os.fstat(fd).st_mode)) {
            throw new ErrnoException("open", EISDIR);
        }
        return fd;
    } catch (ErrnoException errnoException) {
        try {
            if (fd != null) {
                IoUtils.close(fd);
            }
        } catch (IOException ignored) {
        }
        FileNotFoundException ex = new FileNotFoundException(path + ": " + errnoException.getMessage());
        ex.initCause(errnoException);
        throw ex;
    }
}
 
Example 60
Project: OpenClinica   File: XmlSchemaValidationHelper.java View source code Vote up 6 votes
public void validateAgainstSchema(File xmlFile, File xsdFile) {
    try {
        // parse an XML document into a DOM tree
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        DocumentBuilder parser = builderFactory.newDocumentBuilder();
        Document document = parser.parse(xmlFile);

        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        // load a WXS schema, represented by a Schema instance
        Source schemaFile = new StreamSource(xsdFile);
        Schema schema = factory.newSchema(schemaFile);

        // create a Validator instance, which can be used to validate an
        // instance document
        Validator validator = schema.newValidator();

        // validate the DOM tree
        validator.validate(new DOMSource(document));

    } catch (FileNotFoundException ex) {
        throw new OpenClinicaSystemException("File was not found", ex.getCause());
    } catch (IOException ioe) {
        throw new OpenClinicaSystemException("IO Exception", ioe.getCause());
    } catch (SAXParseException spe) {
        //spe.printStackTrace();
        throw new OpenClinicaSystemException("Line : " + spe.getLineNumber() + " - " + spe.getMessage(), spe.getCause());
    } catch (SAXException e) {
        throw new OpenClinicaSystemException(e.getMessage(), e.getCause());
    } catch (ParserConfigurationException pce) {
        throw new OpenClinicaSystemException(pce.getMessage(), pce.getCause());
    }
}
 
Example 61
Project: OpenClinica   File: XmlSchemaValidationHelper.java View source code Vote up 6 votes
public void validateAgainstSchema(String xml, File xsdFile) {
    try {
        // parse an XML document into a DOM tree
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        DocumentBuilder parser = builderFactory.newDocumentBuilder();
        Document document = parser.parse(xml);

        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        // load a WXS schema, represented by a Schema instance
        Source schemaFile = new StreamSource(xsdFile);
        Schema schema = factory.newSchema(schemaFile);

        // create a Validator instance, which can be used to validate an
        // instance document
        Validator validator = schema.newValidator();

        // validate the DOM tree
        validator.validate(new DOMSource(document));

    } catch (FileNotFoundException ex) {
        throw new OpenClinicaSystemException("File was not found", ex.getCause());
    } catch (IOException ioe) {
        throw new OpenClinicaSystemException("IO Exception", ioe.getCause());
    } catch (SAXParseException spe) {
        //spe.printStackTrace();
        throw new OpenClinicaSystemException("Line : " + spe.getLineNumber() + " - " + spe.getMessage(), spe.getCause());
    } catch (SAXException e) {
        throw new OpenClinicaSystemException(e.getMessage(), e.getCause());
    } catch (ParserConfigurationException pce) {
        throw new OpenClinicaSystemException(pce.getMessage(), pce.getCause());
    }
    
}
 
Example 62
Project: flare-spork   File: PigServer.java View source code Vote up 6 votes
/**
 * Register a pig script file.  The parameters in the file will be substituted with the values in the map and the parameter files
 * The values in params Map will override the value in parameter file if they have the same parameter
 * @param fileName  pig script
 * @param params  the key is the parameter name, and the value is the parameter value
 * @param paramsFiles   files which have the parameter setting
 * @throws IOException
 */
public void registerScript(String fileName, Map<String,String> params,List<String> paramsFiles) throws IOException {
    FileInputStream fis = null;
    try{
        fis = new FileInputStream(fileName);
        registerScript(fis, params, paramsFiles);
    }catch (FileNotFoundException e){
        log.error(e.getLocalizedMessage());
        throw new IOException(e.getCause());
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}
 
Example 63
Project: spork-streaming   File: PigServer.java View source code Vote up 6 votes
/**
 * Register a pig script file.  The parameters in the file will be substituted with the values in the map and the parameter files
 * The values in params Map will override the value in parameter file if they have the same parameter
 * @param fileName  pig script
 * @param params  the key is the parameter name, and the value is the parameter value
 * @param paramsFiles   files which have the parameter setting
 * @throws IOException
 */
public void registerScript(String fileName, Map<String,String> params,List<String> paramsFiles) throws IOException {
    FileInputStream fis = null;
    try{
        fis = new FileInputStream(fileName);
        registerScript(fis, params, paramsFiles);
    }catch (FileNotFoundException e){
        log.error(e.getLocalizedMessage());
        throw new IOException(e.getCause());
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}
 
Example 64
Project: linshare-core   File: ClamavVirusScannerServiceImpl.java View source code Vote up 6 votes
public boolean check(File fileToCheck) throws TechnicalException {
	try {
		InputStream fileAsStream = new FileInputStream(fileToCheck);
		return check(fileAsStream);
	} catch (FileNotFoundException e) {
		throw new TechnicalException(
				TechnicalErrorCode.VIRUS_SCANNER_COMMUNICATION_FAILED, e
						.getMessage(), e.getCause());
	}

}
 
Example 65
Project: PonIC   File: PigServer.java View source code Vote up 6 votes
/**
 * Register a pig script file.  The parameters in the file will be substituted with the values in the map and the parameter files
 * The values in params Map will override the value in parameter file if they have the same parameter
 * @param fileName  pig script
 * @param params  the key is the parameter name, and the value is the parameter value
 * @param paramsFiles   files which have the parameter setting
 * @throws IOException
 */
public void registerScript(String fileName, Map<String,String> params,List<String> paramsFiles) throws IOException {
    FileInputStream fis = null;
    try{
        fis = new FileInputStream(fileName);
        registerScript(fis, params, paramsFiles);
    }catch (FileNotFoundException e){
        log.error(e.getLocalizedMessage());
        throw new IOException(e.getCause());
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}
 
Example 66
Project: turnus   File: XmlProfilingWeightsReader.java View source code Vote up 6 votes
public ProfilingWeights read(Network network, File file) {
	try {
		InputStream is = new BufferedInputStream(new FileInputStream(file));
		return read(network, is);
	} catch (FileNotFoundException e) {
		throw new TurnusRuntimeException("Error parsing the workload file "
				+ file, e.getCause());
	}
}
 
Example 67
Project: factura-electronica   File: PublicKeyLoader.java View source code Vote up 6 votes
public PublicKeyLoader(String certificateLocation) {
    try {
        this.setX509Certificate(new FileInputStream(certificateLocation));
    } catch (FileNotFoundException fnfe) {
        throw new KeyException("La ubicación del archivo de la llave pública es incorrecta", fnfe.getCause());
    }
}
 
Example 68
Project: factura-electronica   File: PrivateKeyLoader.java View source code Vote up 6 votes
/**
 * @param privateKeyLocation    private key located in filesystem
 * @param keyPassword           private key password
 *
 * @throws KeyException thrown when any security exception occurs
 */
public void setPrivateKey(String privateKeyLocation, String keyPassword) {

    InputStream privateKeyInputStream = null;

    try {
        privateKeyInputStream = new FileInputStream(privateKeyLocation);
    }catch (FileNotFoundException fnfe){
        throw new KeyException("La ubicación del archivo de la llave privada es incorrecta", fnfe.getCause());
    }

    this.setPrivateKey(privateKeyInputStream, keyPassword);
}
 
Example 69
Project: DrakkarKeel   File: FileStoreServant.java View source code Vote up 5 votes
/**
 *
 * @param name
 * @param num
 * @param current
 * @return
 * @throws FileAccessException
 */
public FilePrx read(String name, int num, Ice.Current current) throws FileAccessException {
     OutputMonitor.printLine("Read File: ", OutputMonitor.INFORMATION_MESSAGE);    
    int option = 0;
    File analyzedFile = null;
    String newPath = null;
    FilePrx fileprx = null;

    option = analyzedRequestFile(name);

    //create cache dir
    if (!cache.exists()) {
        cache.mkdir();
    }

    switch (option) {
        case LOCAL_FILE:
            OutputMonitor.printLine("Local File: ", OutputMonitor.INFORMATION_MESSAGE);
            analyzedFile = new File(name);
            break;

        case SVN_FILE:

            getSVNRepoUrl(name, svnCache);
            getSVNFilePath(name, svnCache);

            Map<String, SVNData> list = svnController.getSvnRepositoriesDB();
            SVNData data = null;
            if (!list.isEmpty() && list.containsKey(svnCache.getRepoName())) {
                data = list.get(svnCache.getRepoName());

                newPath = getFilePathCache(SVN_FILE, svnCache.getFilePath());
                if (newPath != null && (new File(newPath).exists() == false)) {

                    svnController.displayFile(svnCache.getUrl(), data.getUser(), DrakkarSecurity.decryptPassword(data.getPassword()), svnCache.getFilePath(), newPath);

                } else {
                    OutputMonitor.printLine("File exists: ", OutputMonitor.ERROR_MESSAGE);
                }
                analyzedFile = new File(newPath);

            } else {
                OutputMonitor.printLine("The repository " + svnCache.getRepoName() + " is not indexed", OutputMonitor.ERROR_MESSAGE);
            }

            break;

        case FTP_FILE:

            //todo> hacer el m'etodo que extrae el file del ftp
            newPath = getFilePathCache(FTP_FILE, "");
            analyzedFile = new File(newPath);
            break;

    }

    if (analyzedFile != null) {
        try {
            ObjectPrx file = this.communication.getAdapter().addWithUUID(
                    new FileServant(analyzedFile, num));
            fileprx = FilePrxHelper.uncheckedCast(file);
        } catch (FileNotFoundException ex) {
            throw new FileAccessException(ex.getMessage());
        }
    } else {
        OutputMonitor.printLine("File null.", OutputMonitor.ERROR_MESSAGE);
    }

    return fileprx;
}
 
Example 70
Project: MyDownloadDemo   File: DownloadThread.java View source code Vote up 5 votes
/**
 * Prepare the destination file to receive data. If the file already exists,
 * we'll set up appropriately for resumption.
 */
private void setupDestinationFile(State state, InnerState innerState)
		throws StopRequest {
	if (!TextUtils.isEmpty(state.mFilename)) { // only true if we've already
		// run a thread for this
		// download
		if (!Helpers.isFilenameValid(state.mFilename)) {
			// this should never happen
			throw new StopRequest(Downloads.STATUS_FILE_ERROR,
					"found invalid internal destination filename");
		}
		// We're resuming a download that got interrupted
		File f = new File(state.mFilename);
		if (f.exists()) {
			long fileLength = f.length();
			if (fileLength == 0) {
				// The download hadn't actually started, we can restart from
				// scratch
				f.delete();
				state.mFilename = null;
			} else if (mInfo.mETag == null && !mInfo.mNoIntegrity) {
				// This should've been caught upon failure
				f.delete();
				throw new StopRequest(Downloads.STATUS_CANNOT_RESUME,
						"Trying to resume a download that can't be resumed");
			} else {
				// All right, we'll be able to resume this download
				try {
					state.mStream = new FileOutputStream(state.mFilename,
							true);
				} catch (FileNotFoundException exc) {
					throw new StopRequest(Downloads.STATUS_FILE_ERROR,
							"while opening destination for resuming: "
									+ exc.toString(), exc);
				}
				innerState.mBytesSoFar = (int) fileLength;
				if (mInfo.mTotalBytes != -1) {
					innerState.mHeaderContentLength = Long
							.toString(mInfo.mTotalBytes);
				}
				innerState.mHeaderETag = mInfo.mETag;
				innerState.mContinuingDownload = true;
			}
		}
	}

	if (state.mStream != null
			&& mInfo.mDestination == Downloads.DESTINATION_EXTERNAL) {
		closeDestination(state);
	}
}
 
Example 71
Project: kabeja   File: DXFParser.java View source code Vote up 5 votes
public void parse(InputStream input, DraftDocument doc,Map properties)
    throws ParseException {
	this.doc=doc;
    String currentKey = "";
    key = false;
    linecount = 0;
    parse = false;

    //initialize 
   String encoding = null;
   if(properties.containsKey(DraftDocument.PROPERTY_ENCODING)){
	   encoding = (String)properties.get(DraftDocument.PROPERTY_ENCODING);
   }else{
	   encoding = DEFAULT_ENCODING;
   }
    
    doc.setProperty(DraftDocument.PROPERTY_ENCODING, encoding);
    //the StreamFilters
    this.buildFilterChain();

    BufferedReader in = null;

    try {
        if ("".equals(encoding)) {
            BufferedInputStream buf = new BufferedInputStream(input);
            buf.mark(9000);

            try {
                BufferedReader r = new BufferedReader(new InputStreamReader(
                            buf));
                CodePageParser p = new CodePageParser();
                encoding = p.parseEncoding(r);
                buf.reset();

                in = new BufferedReader(new InputStreamReader(buf, encoding));
            } catch (IOException e1) {
                buf.reset();
                in = new BufferedReader(new InputStreamReader(buf));
            }
        } else {
            in = new BufferedReader(new InputStreamReader(input, encoding));
        }

        key = true;
        sectionstarts = false;
        DXFValue value= new DXFValue();
        while ((line = in.readLine()) != null) {
            linecount++;
            if (key) {
                currentKey = line;
                key = false;
            } else {
                int keyCode = Integer.parseInt(currentKey.trim());
                //the filter chain
                value.setValue(line);
                filter.parseGroup(keyCode,value);
                // parseGroup(currentKey, line);
                key = true;
            }
        }

        // finish last parsing
        if (parse) {
            currentHandler.endSection();
        }
    } catch (FileNotFoundException e) {
        throw new ParseException(e.toString());
    } catch (IOException ioe) {
        throw new ParseException(ioe.toString());
    } finally {
        try {
            in.close();
        } catch (IOException ex) {
            // Nothing to do
        }
    }
}
 
Example 72
Project: nicehair   File: DownloadThread.java View source code Vote up 5 votes
/**
 * Prepare the destination file to receive data.  If the file already exists, we'll set up
 * appropriately for resumption.
 */
private void setupDestinationFile(State state, InnerState innerState)
        throws StopRequest {
    
    if (!TextUtils.isEmpty(state.mFilename)) {
        // only true if we've already run a thread for this download
        if (!Helper.isFilenameValid(state.mFilename, state.mSourceType)) {
            // this should never happen
            throw new StopRequest(DownloadManager.Impl.STATUS_FILE_ERROR,
                    "found invalid internal destination filename");
        }
        
        // We're resuming a download that got interrupted
        File f = new File(state.mFilename);
        if (f.exists()) {
            long fileLength = f.length();
            if (fileLength == 0) {
                // The download hadn't actually started, we can restart from scratch
                f.delete();
                state.mFilename = null;
            } else if (mInfo.mETag == null) {
                // This should've been caught upon failure
                f.delete();
                throw new StopRequest(DownloadManager.Impl.STATUS_CANNOT_RESUME,
                        "Trying to resume a download that can't be resumed");
            } else {
                // All right, we'll be able to resume this download
                try {
                    state.mStream = new FileOutputStream(state.mFilename, true);
		FileInputStream fis = new FileInputStream(state.mFilename);
		DigestInputStream dis = new DigestInputStream(fis, state.mDigester);
		byte[] buffer = new byte[8192];
		while (dis.read(buffer) != -1) {
			// read the digest
		}
		dis.close();
		fis.close();
                } catch (FileNotFoundException exc) {
                    throw new StopRequest(DownloadManager.Impl.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + exc.toString(), exc);
                } catch (IOException e) {
                	throw new StopRequest(DownloadManager.Impl.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + e.toString(), e);
	}
                innerState.mBytesSoFar = (int) fileLength;
                if (mInfo.mTotalBytes != -1) {
                    innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
                }
                innerState.mHeaderETag = mInfo.mETag;
                innerState.mContinuingDownload = true;
            }
        }
    }

    if (state.mStream != null
            && mInfo.mDestination == DownloadManager.Impl.DESTINATION_EXTERNAL) {
        closeDestination(state);
    }
}