List of usage examples for java.io IOException getLocalizedMessage
public String getLocalizedMessage()
From source file:org.zenoss.zep.index.impl.lucene.LuceneQueryBuilder.java
private static Term[] getMatchingTerms(String fieldName, IndexReader reader, String value) throws ZepException { // Don't search for matches if text doesn't contain wildcards if (value.indexOf('*') == -1 && value.indexOf('?') == -1) return new Term[] { new Term(fieldName, value) }; logger.debug("getMatchingTerms: field={}, value={}", fieldName, value); List<Term> matches = new ArrayList<Term>(); Automaton automaton = WildcardQuery.toAutomaton(new Term(fieldName, value)); CompiledAutomaton compiled = new CompiledAutomaton(automaton); try {/*from w w w .ja va 2s . com*/ Terms terms = SlowCompositeReaderWrapper.wrap(reader).terms(fieldName); TermsEnum wildcardTermEnum = compiled.getTermsEnum(terms); BytesRef match; while (wildcardTermEnum.next() != null) { match = wildcardTermEnum.term(); logger.debug("Match: {}", match); matches.add(new Term(fieldName, match.utf8ToString())); } return matches.toArray(new Term[matches.size()]); } catch (IOException e) { throw new ZepException(e.getLocalizedMessage(), e); } }
From source file:org.zenoss.zep.index.impl.lucene.LuceneQueryBuilder.java
/** * Tokenizes the given query using the same behavior as when the field is analyzed. * * @param fieldName The field name in the index. * @param analyzer The analyzer to use to tokenize the query. * @param query The query to tokenize. * @return The tokens from the query./*from w w w .j a va 2 s . c om*/ * @throws ZepException If an exception occur. */ private static List<String> getTokens(String fieldName, Analyzer analyzer, String query) throws ZepException { final List<String> tokens = new ArrayList<String>(); try { TokenStream ts = analyzer.tokenStream(fieldName, new StringReader(query)); CharTermAttribute term = ts.addAttribute(CharTermAttribute.class); try { ts.reset(); while (ts.incrementToken()) { tokens.add(term.toString()); } ts.end(); } catch (IOException e) { throw new ZepException(e.getLocalizedMessage(), e); } finally { ts.close(); } } catch (IOException e) { throw new ZepException(e.getLocalizedMessage(), e); } return tokens; }
From source file:it.uniud.ailab.dcore.launchers.Launcher.java
/** * Decide what Distillation (single or directory) execute and run it. *//*from ww w .j a va 2s . c om*/ private static void doWork() { switch (mode) { case EVALUATION: evaluate(); break; case TRAINING_GENERATION: generateTrainingSet(); break; default: try { if (inputPath.isFile()) { analyzeFile(inputPath); } else { analyzeDir(inputPath); } } catch (IOException ioe) { System.err.println(ioe.getLocalizedMessage()); System.err.println(ioe.toString()); } } }
From source file:com.truebanana.http.HTTPResponse.java
protected static HTTPResponse from(HTTPRequest request, HttpURLConnection connection, InputStream content) { HTTPResponse response = new HTTPResponse(); response.originalRequest = request;//w w w . ja v a2 s . co m if (content != null) { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] data = new byte[16384]; int nRead; while ((nRead = content.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); response.content = buffer.toByteArray(); } catch (IOException e) { e.printStackTrace(); } } try { response.statusCode = connection.getResponseCode(); } catch (IOException e) { } String message = null; try { message = connection.getResponseMessage(); } catch (IOException e) { message = e.getLocalizedMessage(); } response.responseMessage = response.statusCode + (message != null ? " " + message : ""); response.headers = connection.getHeaderFields(); response.requestURL = connection.getURL().toString(); return response; }
From source file:com.example.httpjson.AppEngineClient.java
public static Response getOrPost(Request request) { mErrorMessage = null;/*from w ww . j a v a 2 s . c o m*/ HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); // ... OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { int a = conn.getResponseCode(); if (a == 401) { response = new Response(a, conn.getHeaderFields(), new byte[] {}); } InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": " + e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:it.geosolutions.tools.compress.file.Compressor.java
/** * @param outputDir/*from w ww .j av a 2s .c om*/ * The directory where the zipfile will be created * @param zipFileBaseName * The basename of hte zip file (i.e.: a .zip will be appended) * @param folder * The folder that will be compressed * @return The created zipfile, or null if an error occurred. * @deprecated TODO UNTESTED */ public static File deflate(final File outputDir, final String zipFileBaseName, final File folder) { // Create a buffer for reading the files byte[] buf = new byte[4096]; // Create the ZIP file final File outZipFile = new File(outputDir, zipFileBaseName + ".zip"); if (outZipFile.exists()) { if (LOGGER.isInfoEnabled()) LOGGER.info("The output file already exists: " + outZipFile); return outZipFile; } ZipOutputStream out = null; BufferedOutputStream bos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(outZipFile); bos = new BufferedOutputStream(fos); out = new ZipOutputStream(bos); Collector c = new Collector(null); List<File> files = c.collect(folder); // Compress the files for (File file : files) { FileInputStream in = null; try { in = new FileInputStream(file); if (file.isDirectory()) { out.putNextEntry(new ZipEntry(Path.toRelativeFile(folder, file).getPath())); } else { // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(FilenameUtils.getBaseName(file.getName()))); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } } finally { try { // Complete the entry out.closeEntry(); } catch (IOException e) { } IOUtils.closeQuietly(in); } } } catch (IOException e) { LOGGER.error(e.getLocalizedMessage(), e); return null; } finally { // Complete the ZIP file IOUtils.closeQuietly(bos); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(out); } return outZipFile; }
From source file:org.owasp.proxy.Main.java
private static ProxySelector getProxySelector(Configuration config) { String proxy = config.proxy;/*w ww . j ava 2 s .c o m*/ final java.net.Proxy upstream; if ("DIRECT".equals(proxy)) { upstream = java.net.Proxy.NO_PROXY; } else { java.net.Proxy.Type type = null; if (proxy.startsWith("PROXY ")) { type = java.net.Proxy.Type.HTTP; } else if (proxy.startsWith("SOCKS ")) { type = java.net.Proxy.Type.SOCKS; } else throw new IllegalArgumentException("Unknown Proxy type: " + proxy); proxy = proxy.substring(6); // "SOCKS " or "PROXY " int c = proxy.indexOf(':'); if (c == -1) throw new IllegalArgumentException("Illegal proxy address: " + proxy); InetSocketAddress addr = new InetSocketAddress(proxy.substring(0, c), Integer.parseInt(proxy.substring(c + 1))); upstream = new java.net.Proxy(type, addr); } ProxySelector ps = new ProxySelector() { @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { logger.info("Proxy connection to " + uri + " via " + sa + " failed! " + ioe.getLocalizedMessage()); } @Override public List<java.net.Proxy> select(URI uri) { return Arrays.asList(upstream); } }; return ps; }
From source file:com.example.pabrto.AppEngineClient.java
public static Response getOrPost(Request request) { mErrorMessage = null;/*ww w . j av a 2s.c om*/ HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); // ... OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { int a = conn.getResponseCode(); InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": " + e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:com.google.cloud.hadoop.gcsio.GoogleCloudStorageIntegrationTest.java
/** * Delete buckets that were temporarily created during tests. */// ww w . j av a 2s. c o m static void deleteBuckets() { for (String bucket : bucketsToDelete) { try { gcsit.clearBucket(bucket); gcsit.delete(bucket); } catch (IOException e) { log.warn("deleteBuckets: " + e.getLocalizedMessage()); } } bucketsToDelete.clear(); }
From source file:com.willwinder.universalgcodesender.utils.FirmwareUtils.java
/** * Copy any missing files from the the jar's resources/firmware_config/ dir * into the settings/firmware_config dir. *//* www . j a va 2s .c om*/ public synchronized static void initialize() { System.out.println("Initializing firmware... ..."); File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME); // Create directory if it's missing. if (!firmwareConfig.exists()) { firmwareConfig.mkdirs(); } FileSystem fileSystem = null; // Copy firmware config files. try { final String dir = "/resources/firmware_config/"; URI location = FirmwareUtils.class.getResource(dir).toURI(); Path myPath; if (location.getScheme().equals("jar")) { try { // In case the filesystem already exists. fileSystem = FileSystems.getFileSystem(location); } catch (FileSystemNotFoundException e) { // Otherwise create the new filesystem. fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap()); } myPath = fileSystem.getPath(dir); } else { myPath = Paths.get(location); } Stream<Path> files = Files.walk(myPath, 1); for (Path path : (Iterable<Path>) () -> files.iterator()) { System.out.println(path); final String name = path.getFileName().toString(); File fwConfig = new File(firmwareConfig, name); if (name.endsWith(".json")) { boolean copyFile = !fwConfig.exists(); ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path)); // If the file is outdated... ask the user (once). if (fwConfig.exists()) { ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig)); boolean outOfDate = current.getVersion() < jarSetting.getVersion(); if (outOfDate && !userNotified && !overwriteOldFiles) { int result = NarrowOptionPane.showNarrowConfirmDialog(200, Localization.getString("settings.file.outOfDate.message"), Localization.getString("settings.file.outOfDate.title"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); overwriteOldFiles = result == JOptionPane.OK_OPTION; userNotified = true; } if (overwriteOldFiles) { copyFile = true; jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom; } } // Copy file from jar to firmware_config directory. if (copyFile) { try { save(fwConfig, jarSetting); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } } } } } catch (Exception ex) { String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"), ex.getLocalizedMessage()); GUIHelpers.displayErrorDialog(errorMessage); logger.log(Level.SEVERE, errorMessage, ex); } finally { if (fileSystem != null) { try { fileSystem.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Problem closing filesystem.", ex); } } } configFiles.clear(); for (File f : firmwareConfig.listFiles()) { try { ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class); //ConfigLoader config = new ConfigLoader(f); configFiles.put(config.getName(), new ConfigTuple(config, f)); } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) { GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath()); } } }