List of usage examples for java.io IOException getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:de.tudarmstadt.lt.seg.sentence.RuleSplitter.java
private boolean checkSentenceBoundaryLookAhead() { // get the next approximate token or sentence if (_cp < 0) return true; try {//from www . j a va 2s.c om _reader.mark(1000); _tokenizer.init(_reader); if (!_tokenizer.hasNext()) return true; String next_token = _tokenizer.next().asString(); _reader.reset(); if (_rules._post_boundary_checker_list.isCompleteSentence(next_token)) return _rules._post_boundary_checker_rules.isCompleteSentence(next_token); return false; } catch (IOException e) { System.err.format("%s: %s%n", e.getClass().getName(), e.getMessage()); } return false; }
From source file:org.sipfoundry.preflight.NTP.java
public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService, InetAddress bindAddress) { ResultCode results = NONE;/* w w w . j a v a2s . c o m*/ if (networkResources.ntpServers == null) { journalService.println("No NTP servers provided, skipping test."); results = NTP_SERVERS_MISSING; } else { journalService.println("Starting NTP servers test."); NTPUDPClient client = new NTPUDPClient(); client.setDefaultTimeout(timeout * 1000); try { client.open(bindPort, bindAddress); for (InetAddress ntpServer : networkResources.ntpServers) { journalService.println("NTP test for server: " + ntpServer.getCanonicalHostName()); try { TimeInfo info = client.getTime(ntpServer); journalService.println(new String(processResponse(info))); } catch (IOException e) { client.close(); if (e.getClass() == java.net.SocketTimeoutException.class) { journalService.println(" NTP request timed out."); results = NTP_SERVER_FAILURE; } else { journalService.println(" NTP request error: " + e.getMessage()); results = NTP_TEST_FAILURE; } } } } catch (SocketException e) { journalService.println("Unable to create NTP client: " + e.getMessage()); results = NTP_TEST_FAILURE; } } journalService.println(""); return results; }
From source file:edu.ehu.galan.lite.algorithms.ranked.supervised.tfidf.corpus.wikipedia.WikiCorpusBuilder.java
private void initializeIndex(String index) { final File docDir = new File(index); Date start = new Date(); try {//from w ww . j a v a 2 s.c o m System.out.println("Indexing to directory '" + docDir.getAbsolutePath() + "'..."); Directory dir = FSDirectory.open(new File(index)); Analyzer analyzer = new AnalyzerEnglish(Version.LUCENE_40); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer); //// in the directory, removing any // previously indexed documents: iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE); // Optional: for better indexing performance, if you // are indexing many documents, increase the RAM // buffer. But if you do this, increase the max heap // size to the JVM (eg add -Xmx512m or -Xmx1g): // iwc.setRAMBufferSizeMB(1024.0); writer = new IndexWriter(dir, iwc); // NOTE: if you want to maximize search performance, // you can optionally call forceMerge here. This can be // a terribly costly operation, so generally it's only // worth it when your index is relatively static (ie // you're done adding documents to it): // // writer.forceMerge(1); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } }
From source file:photosharing.api.conx.SearchTagsDefinition.java
/** * searches for tags based in the IBM Connections Cloud - Files service, and limit results to documents only * /* w w w .jav a 2 s .c o m*/ * @see photosharing.api.base.APIDefinition#run(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void run(HttpServletRequest request, HttpServletResponse response) { /** * check if query is empty, send SC_PRECONDITION_FAILED 412 */ String query = request.getParameter("q"); if (query == null || query.isEmpty()) { response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); } /** * get the users bearer token */ HttpSession session = request.getSession(false); OAuth20Data data = (OAuth20Data) session.getAttribute(OAuth20Handler.CREDENTIALS); String bearer = data.getAccessToken(); /** * The query should be cleansed before passing it to the backend * * Example * http://localhost:9080/photoSharing/api/searchTags?q=s * maps to * https://apps.collabservnext.com/files/oauth/api/tags/feed?format=json&scope=document&pageSize=16&filter=a * * Response Data * {"pageSize":2,"startIndex":1,"hasMore":true,"items":[{"name":"a","weight":482}]} */ Request get = Request.Get(getApiUrl(query)); get.addHeader("Authorization", "Bearer " + bearer); try { Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Content is returned else if (code == HttpStatus.SC_OK) { ServletOutputStream out = response.getOutputStream(); InputStream in = hr.getEntity().getContent(); IOUtils.copy(in, out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } // Unexpected status else { JSONObject obj = new JSONObject(); obj.put("error", "unexpected content"); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("IOException " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("JSONException " + e.toString()); } }
From source file:io.helixservice.feature.configuration.cloudconfig.CloudConfigResourceLocator.java
private Optional<InputStream> requestCloudConfigProperties(String resourcePath, Optional<InputStream> result) { String cloudConfigResource = resourcePath.substring(0, resourcePath.lastIndexOf(APPLICATION_YAML_FILE)) .replace("default", "default"); String url = serviceUri + "/" + cloudConfigResource; try {//from www . j ava 2 s .co m HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.addRequestProperty(AUTHORIZATION_HEADER, httpBasicHeader); if (connection.getResponseCode() == 200) { InputStream inputStream = connection.getInputStream(); InputStream extractedPropertiesInputStream = extractProperties(inputStream); result = Optional.of(extractedPropertiesInputStream); inputStream.close(); } else { LOG.error("Unable to get Cloud Config due to httpStatusCode=" + connection.getResponseCode() + " for cloudConfigUrl=" + url); } } catch (IOException e) { LOG.error("Unable to connect to Cloud Config server at cloudConfigUrl=" + url + " exception=" + e.getClass().getSimpleName() + " exceptionMessage=" + e.getMessage()); } return result; }
From source file:photosharing.api.conx.PhotoDefinition.java
/** * retrieves a profile photo based on the person's key * //from w ww. j av a2s . c o m * @see photosharing.api.base.APIDefinition#run(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void run(HttpServletRequest request, HttpServletResponse response) { /** * check if query is empty, send SC_PRECONDITION_FAILED - 412 */ String query = request.getParameter("key"); if (query == null || query.isEmpty()) { response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); } else { /** * get the users bearer token */ HttpSession session = request.getSession(false); Object oData = session.getAttribute(OAuth20Handler.CREDENTIALS); if (oData == null) { logger.warning("OAuth20Data is null"); } OAuth20Data data = (OAuth20Data) oData; String bearer = data.getAccessToken(); try { /** * Example URL: * http://localhost:9080/photoSharing/api/photo?uid=key maps to * https://apps.collabservnext.com/profiles/photo.do * * and results in an image */ String apiUrl = getApiUrl(query); logger.info("api url is " + apiUrl); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired - 403 if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized // SC_UNAUTHORIZED (401) else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Content is returned // OK (200) else if (code == HttpStatus.SC_OK) { //Headers response.setContentType(hr.getFirstHeader("Content-Type").getValue()); response.setHeader("content-length", hr.getFirstHeader("content-length").getValue()); // Streams InputStream in = hr.getEntity().getContent(); IOUtils.copy(in, response.getOutputStream()); IOUtils.closeQuietly(in); IOUtils.closeQuietly(response.getOutputStream()); } else { // Unexpected Result response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Photo Definition - IOException " + e.toString()); } } }
From source file:org.apache.axis.attachments.MultiPartDimeInputStream.java
public Part getAttachmentByReference(final String[] id) throws org.apache.axis.AxisFault { //First see if we have read it in yet. Part ret = null;/*w ww. j av a 2 s . c o m*/ try { for (int i = id.length - 1; ret == null && i > -1; --i) { ret = (AttachmentPart) parts.get(id[i]); } if (null == ret) { ret = readTillFound(id); } log.debug(Messages.getMessage("return02", "getAttachmentByReference(\"" + id + "\"", (ret == null ? "null" : ret.toString()))); } catch (java.io.IOException e) { throw new org.apache.axis.AxisFault(e.getClass().getName() + e.getMessage()); } return ret; }
From source file:org.apache.pig.backend.local.executionengine.POStore.java
@Override public Tuple getNext() throws IOException { // get all tuples from input, and store them. DataBag b = BagFactory.getInstance().newDefaultBag(); Tuple t;//from w w w. j a va 2 s . c om while ((t = (Tuple) ((PhysicalOperator) opTable.get(inputs[0])).getNext()) != null) { b.add(t); } try { StoreFunc func = (StoreFunc) PigContext.instantiateFuncFromSpec(funcSpec); f.store(b, func, pigContext); // a result has materialized, track it! LocalResult materializedResult = new LocalResult(this.outFileSpec); materializedResults.put(logicalKey, materializedResult); } catch (IOException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { IOException ne = new IOException(e.getClass().getName() + ": " + e.getMessage()); ne.setStackTrace(e.getStackTrace()); throw ne; } return null; }
From source file:utils.CifsNetworkConfig.java
/** * Copy file per JCIFS Client library using CIFS/SMB-protocol * // w w w . j a va2 s. co m * @param sourceFile File to send * @param destinationFilePath destination path where to send the file * @param deleteSourceFile delete source file after it has been successfully sent to the network share * * @throws IOException */ public void networkCopy(File sourceFile, String destinationFilePath, boolean deleteSourceFile) throws IOException { SmbFileOutputStream sfos = null; FileInputStream sourceInputStream = null; try { this.currentSmbFile = new SmbFile(destinationFilePath, auth); if (!currentSmbFile.exists()) { log.debug("SMB file will be created new: " + currentSmbFile.getPath()); String parentDirPath = currentSmbFile.toString(); parentDirPath = parentDirPath.substring(0, parentDirPath.lastIndexOf('/') + 1); SmbFile parentDir = new SmbFile(parentDirPath, auth); if (!parentDir.exists()) { log.debug("SMB directory for smb-file will be created new: " + parentDir.getPath()); parentDir.mkdirs(); } currentSmbFile.createNewFile(); } sfos = new SmbFileOutputStream(currentSmbFile); sourceInputStream = new FileInputStream(sourceFile); IOUtils.copy(sourceInputStream, currentSmbFile.getOutputStream()); log.info("Send file: " + sourceFile.getAbsolutePath() + " sucessfully to " + currentSmbFile.getPath()); } catch (IOException e) { log.error(e.getClass().getName() + " occured on sending file: " + sourceFile.getAbsolutePath()); log.error(e.getMessage()); throw e; } finally { if (sfos != null) { try { sfos.close(); } catch (IOException e) { log.error("Cannot close smbFileOutputstream"); log.error(e.getMessage()); throw e; } } if (sourceInputStream != null) { sourceInputStream.close(); } if (deleteSourceFile) { GlobalParameters.deleteFile(sourceFile); } } }
From source file:net.sourceforge.pmd.docs.DeadLinksChecker.java
private int computeHttpResponse(String url) { try {/*ww w .j a va2 s. c om*/ final HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection(); httpURLConnection.setRequestMethod("HEAD"); httpURLConnection.setConnectTimeout(5000); httpURLConnection.setReadTimeout(15000); httpURLConnection.connect(); final int responseCode = httpURLConnection.getResponseCode(); String response = "HTTP " + responseCode; if (httpURLConnection.getHeaderField("Location") != null) { response += ", Location: " + httpURLConnection.getHeaderField("Location"); } LOG.fine("response: " + response + " on " + url); // success (HTTP 2xx) or redirection (HTTP 3xx) return responseCode; } catch (IOException ex) { LOG.fine("response: " + ex.getClass().getName() + " on " + url + " : " + ex.getMessage()); return 599; } }