List of usage examples for java.io IOException IOException
public IOException(Throwable cause)
From source file:hu.bme.mit.trainbenchmark.benchmark.sqlite.driver.SQLiteDriver.java
@Override public void read(final String modelPath) throws IOException, InterruptedException, SQLException { final File modelFile = new File(modelPath); if (!modelFile.exists()) { throw new IOException("Model does not exist: " + modelPath); }/*from w w w .j av a 2 s.c o m*/ connection = DriverManager.getConnection("jdbc:sqlite::memory:"); final Statement statement = connection.createStatement(); statement.setQueryTimeout(3600); final String sql = FileUtils.readFileToString(new File(modelPath)); statement.executeUpdate(sql); // create temporary table (used by the transformations) final PreparedStatement createStatement = connection .prepareStatement("CREATE TEMP TABLE IF NOT EXISTS Variables (Name TEXT PRIMARY KEY, Value LONG);"); createStatement.execute(); }
From source file:edu.kit.cockpit.valuationserver.sfmpersistency.FileUtil.java
/** * checks file for writing/*from w w w . j a v a2 s .c o m*/ * * @param modelFile * @param modelFileName */ public static void checkFileForWriting(File file) throws IOException { checkFileForReading(file); if (!file.canWrite()) { String error = "File '" + file.getAbsolutePath() + "' is write protected"; log.error(error); throw new IOException(error); } }
From source file:com.isec.helperapp.EasySSLSocketFactory.java
private static SSLContext createEasySSLContext() throws IOException { Log.i(TAG, "createEasySSLContext"); try {/*from www . j av a 2 s . com*/ SSLContext context = SSLContext.getInstance("TLS"); context.init(null, TrustAllTrustManager.getTrustManagers(), null); return context; } catch (Exception e) { throw new IOException(e.getMessage()); } }
From source file:com.intellij.diagnostic.DevelopersLoader.java
public static Collection<Developer> fetchDevelopers(ProgressIndicator indicator) throws IOException { List<Developer> developers = new LinkedList<Developer>(); developers.add(Developer.NULL);// ww w . j a v a 2 s. co m HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT); HttpMethod method = new GetMethod(DEVELOPERS_LIST_URL); try { client.executeMethod(method); BufferedReader reader = new BufferedReader( new InputStreamReader(method.getResponseBodyAsStream(), DATA_CHARSET)); try { while (true) { String line = reader.readLine(); if (line == null) break; int i = line.indexOf('\t'); if (i == -1) throw new IOException("Protocol error"); int id = Integer.parseInt(line.substring(0, i)); String name = line.substring(i + 1); developers.add(new Developer(id, name)); indicator.checkCanceled(); } return developers; } finally { reader.close(); } } finally { method.releaseConnection(); } }
From source file:Main.java
/** * This will parse an XML stream and create a DOM document. * * @param fileName The file to get the XML from. * @return The DOM document.//from w w w. ja v a 2 s .com * @throws IOException It there is an error creating the dom. */ public static Document parse(String fileName) throws IOException { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); return builder.parse(fileName); } catch (Exception e) { System.out.println(e.getMessage()); IOException thrown = new IOException(e.getMessage()); throw thrown; } }
From source file:net.dv8tion.jda.core.utils.IOUtil.java
/** * Used as an alternate to Java's nio Files.readAllBytes. * <p>// w ww . ja v a 2s . co m * This customized version for File is provide (instead of just using {@link #readFully(java.io.InputStream)} with a FileInputStream) * because * with a File we can determine the total size of the array and do not need to have a buffer. This results * in a memory footprint that is half the size of {@link #readFully(java.io.InputStream)} * <p> * Code provided from <a href="http://stackoverflow.com/a/6276139">http://stackoverflow.com/a/6276139</a> * * @param file * The file from which we should retrieve the bytes from * @return * A byte[] containing all of the file's data * @throws IOException * Thrown if there is a problem while reading the file. */ public static byte[] readFully(File file) throws IOException { Args.notNull(file, "File"); Args.check(file.exists(), "Provided file does not exist!"); try (InputStream is = new FileInputStream(file)) { // Get the size of the file long length = file.length(); // You cannot create an array using a long type. // It needs to be an int type. // Before converting to an int type, check // to ensure that file is not larger than Integer.MAX_VALUE. if (length > Integer.MAX_VALUE) { throw new IOException("Cannot read the file into memory completely due to it being too large!"); // File is too large } // Create the byte array to hold the data byte[] bytes = new byte[(int) length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } // Close the input stream and return bytes is.close(); return bytes; } }
From source file:Main.java
public static byte[] toByteArray(InputStream input, int size) throws IOException { if (size < 0) throw new IllegalArgumentException("Size must be equal or greater than zero: " + size); if (size == 0) return new byte[0]; byte[] data = new byte[size]; int offset = 0; int byteCount; while ((offset < size) && (byteCount = input.read(data, offset, size - offset)) != -1) offset += byteCount;/*from ww w . ja v a 2 s . com*/ if (offset != size) throw new IOException("Unexpected byte count size. current: " + offset + ", excepted: " + size); return data; }
From source file:com.appeligo.lucene.DidYouMeanIndexer.java
public static void createDefaultSpellIndex(String indexDir, String spellDir) throws IOException { String newSpellDir = spellDir + ".new"; File newSpellDirFile = new File(newSpellDir); if (newSpellDirFile.exists()) { String[] dirFiles = newSpellDirFile.list(); for (String dirFile : dirFiles) { File f = new File(newSpellDirFile, dirFile); if (!f.delete()) { throw new IOException("Could not delete " + f.getAbsolutePath()); }//from ww w .j a v a2 s. com } if (!newSpellDirFile.delete()) { throw new IOException("Could not delete " + newSpellDirFile.getAbsolutePath()); } } /* This was for the original programIndex, but we found out that stemming was bad, and you get better * spelling suggestions if you can specify a single field, so we combined them. for (String field : new String[]{"text","description","programTitle", "episodeTitle", "credits", "genre"}) { createSpellIndex(field, FSDirectory.getDirectory(indexDir), FSDirectory.getDirectory(newSpellDir)); } */ createSpellIndex("compositeField", FSDirectory.getDirectory(indexDir), FSDirectory.getDirectory(newSpellDir)); String oldSpellDir = spellDir + ".old"; File oldSpellDirFile = new File(oldSpellDir); if (oldSpellDirFile.exists()) { String[] dirFiles = oldSpellDirFile.list(); for (String dirFile : dirFiles) { File f = new File(oldSpellDirFile, dirFile); if (!f.delete()) { throw new IOException("Could not delete " + f.getAbsolutePath()); } } if (!oldSpellDirFile.delete()) { throw new IOException("Could not delete " + oldSpellDirFile.getAbsolutePath()); } } File spellDirFile = new File(spellDir); if (spellDirFile.exists() && !spellDirFile.renameTo(oldSpellDirFile)) { throw new IOException("could not rename " + spellDirFile.getAbsolutePath() + " to " + oldSpellDirFile.getAbsolutePath()); } /* there is some small risk here that someone might try to get the spell index when the file isn't there yet */ /* I don't know of any way to really synchronize that from this class, and the risk is minor, unlikely, and not catastrophic */ spellDirFile = new File(spellDir); if (!newSpellDirFile.renameTo(spellDirFile)) { // What really bugs me is you can't close a SpellChecker, and I think that prevents us from renaming // the spell index directory (at least on Windows Vista), so let's copy the files instead /* throw new IOException("could not rename "+newSpellDirFile.getAbsolutePath()+" to "+spellDirFile.getAbsolutePath()); */ if (!spellDirFile.mkdir()) { throw new IOException("Couldn't make directory " + spellDirFile.getAbsolutePath()); } String[] dirFiles = newSpellDirFile.list(); for (String dirFile : dirFiles) { File f = new File(newSpellDirFile, dirFile); File toF = new File(spellDirFile, dirFile); InputStream is = new BufferedInputStream(new FileInputStream(f.getAbsolutePath())); OutputStream os = new BufferedOutputStream(new FileOutputStream(toF.getAbsolutePath())); int b; while ((b = is.read()) != -1) { os.write(b); } is.close(); os.close(); /* I'd like to do this, but the same reason the rename won't work is why this * won't work... this current program still has one or more of the files open. if (!f.delete()) { throw new IOException("Could not delete "+f.getAbsolutePath()); } } if (!newSpellDirFile.delete()) { throw new IOException("Could not delete "+newSpellDirFile.getAbsolutePath()); } */ } } }
From source file:org.mstc.zmq.json.Decoder.java
@SuppressWarnings("unchecked") public static void decode(String input, Field[] fields, Object b) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); if (logger.isDebugEnabled()) logger.debug(input);//ww w. j a v a2 s. com JsonFactory factory = mapper.getFactory(); try (JsonParser jp = factory.createParser(input)) { /* Sanity check: verify that we got "Json Object" */ if (jp.nextToken() != JsonToken.START_OBJECT) { throw new IOException("Expected data to start with an Object"); } /* Iterate over object fields */ while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldName = jp.getCurrentName(); jp.nextToken(); Field field = getField(fieldName, fields); if (field == null) { throw new IOException( "Could not find field [" + fieldName + "] on class " + b.getClass().getName()); } try { if (field.getType().isAssignableFrom(List.class)) { String adder = getAdder(fieldName); TypeFactory t = TypeFactory.defaultInstance(); ParameterizedType listType = (ParameterizedType) field.getGenericType(); Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0]; List list = mapper.readValue(jp.getValueAsString(), t.constructCollectionType(List.class, listClass)); Method m = b.getClass().getDeclaredMethod(adder, Collection.class); m.invoke(b, list); } else if (field.getType().isArray()) { Class<?> type = field.getType(); String setter = getSetter(fieldName); Method m = b.getClass().getDeclaredMethod(setter, field.getType()); logger.info("Field {} is array of {}[], {}, using method {}", field.getName(), field.getType().getComponentType(), jp.getCurrentToken().name(), m); if (jp.getCurrentToken().id() == JsonToken.START_ARRAY.id()) { List list = new ArrayList(); while (jp.nextToken() != JsonToken.END_ARRAY) { String value = jp.getText(); switch (jp.getCurrentToken()) { case VALUE_STRING: list.add(value); break; case VALUE_NUMBER_INT: if (type.getComponentType().isAssignableFrom(double.class)) { list.add(Double.parseDouble(value)); } else if (type.getComponentType().isAssignableFrom(float.class)) { list.add(Float.parseFloat(value)); } else { list.add(Integer.parseInt(value)); } break; case VALUE_NUMBER_FLOAT: logger.info("Add float"); list.add(jp.getFloatValue()); break; case VALUE_NULL: break; default: logger.warn("[3] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } Object array = Array.newInstance(field.getType().getComponentType(), list.size()); for (int i = 0; i < list.size(); i++) { Object val = list.get(i); Array.set(array, i, val); } m.invoke(b, array); } else { if (type.getComponentType().isAssignableFrom(byte.class)) { m.invoke(b, jp.getBinaryValue()); } } } else { String setter = getSetter(fieldName); logger.debug("{}: {}", setter, field.getType().getName()); Method m = b.getClass().getDeclaredMethod(setter, field.getType()); switch (jp.getCurrentToken()) { case VALUE_STRING: m.invoke(b, jp.getText()); break; case VALUE_NUMBER_INT: m.invoke(b, jp.getIntValue()); break; case VALUE_NUMBER_FLOAT: m.invoke(b, jp.getFloatValue()); break; case VALUE_NULL: logger.debug("Skip invoking {}.{}, property is null", b.getClass().getName(), m.getName()); break; case START_OBJECT: StringBuilder sb = new StringBuilder(); while (jp.nextToken() != JsonToken.END_OBJECT) { switch (jp.getCurrentToken()) { case VALUE_STRING: sb.append("\"").append(jp.getText()).append("\""); break; case FIELD_NAME: if (sb.length() > 0) sb.append(","); sb.append("\"").append(jp.getText()).append("\"").append(":"); break; case VALUE_NUMBER_INT: sb.append(jp.getIntValue()); break; case VALUE_NUMBER_FLOAT: sb.append(jp.getFloatValue()); break; case VALUE_NULL: sb.append("null"); break; default: logger.warn("[2] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } String s = String.format("%s%s%s", JsonToken.START_OBJECT.asString(), sb.toString(), JsonToken.END_OBJECT.asString()); Object parsed = getNested(field.getType(), s.getBytes()); m.invoke(b, parsed); break; default: logger.warn("[1] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException e) { logger.error("Failed setting field [{}], builder: {}", fieldName, b.getClass().getName(), e); } } } }
From source file:net.acesinc.data.json.generator.log.FileLogger.java
public FileLogger(Map<String, Object> props) throws IOException { String outputDir = (String) props.get(OUTPUT_DIRECTORY_PROP_NAME); outputDirectory = new File(outputDir); if (!outputDirectory.exists()) { if (!outputDirectory.mkdir()) { if (!outputDirectory.mkdirs()) { throw new IOException("Output directory does not exist and we are unable to create it"); }/*from w w w . java 2 s . co m*/ } } filePrefix = (String) props.get(FILE_PREFIX_PROP_NAME); fileExtension = (String) props.get(FILE_EXTENSION_PROP_NAME); }