List of usage examples for java.lang ClassCastException getMessage
public String getMessage()
From source file:cx.fbn.nevernote.threads.IndexRunner.java
private void indexResourceOffice(Resource r) { Data d = r.getData();//from ww w.jav a 2 s .c o m for (int i = 0; i < 20 && d.getSize() == 0; i++) d = r.getData(); if (d.getSize() == 0) return; QTemporaryFile f = writeResource(d); if (!keepRunning) { return; } InputStream input; try { input = new FileInputStream(new File(f.fileName())); ContentHandler textHandler = new BodyContentHandler(-1); Metadata metadata = new Metadata(); OfficeParser parser = new OfficeParser(); ParseContext context = new ParseContext(); parser.parse(input, textHandler, metadata, context); String[] result = textHandler.toString().split(regex); for (int i = 0; i < result.length && keepRunning; i++) { if (interrupt) { processInterrupt(); } addToIndex(r.getNoteGuid(), result[i], "RESOURCE"); } input.close(); f.close(); } catch (java.lang.ClassCastException e) { logger.log(logger.LOW, "Cast exception: " + e.getMessage()); } catch (FileNotFoundException e) { logger.log(logger.LOW, "FileNotFound exception: " + e.getMessage()); } catch (IOException e) { logger.log(logger.LOW, "IO exception: " + e.getMessage()); } catch (SAXException e) { logger.log(logger.LOW, "SAX exception: " + e.getMessage()); } catch (TikaException e) { logger.log(logger.LOW, "Tika exception: " + e.getMessage()); } catch (Exception e) { logger.log(logger.LOW, "Unknown exception: " + e.getMessage()); } catch (java.lang.NoSuchMethodError e) { logger.log(logger.LOW, "NoSuchMethod error: " + e.getMessage()); } catch (Error e) { logger.log(logger.LOW, "Unknown error: " + e.getMessage()); } }
From source file:cx.fbn.nevernote.threads.IndexRunner.java
private void indexResourcePDF(Resource r) { Data d = r.getData();/*from w w w. j a v a2s .c om*/ for (int i = 0; i < 20 && d.getSize() == 0; i++) d = r.getData(); if (d.getSize() == 0) return; QTemporaryFile f = writeResource(d); if (!keepRunning) { return; } InputStream input; try { input = new FileInputStream(new File(f.fileName())); ContentHandler textHandler = new BodyContentHandler(-1); Metadata metadata = new Metadata(); PDFParser parser = new PDFParser(); ParseContext context = new ParseContext(); parser.parse(input, textHandler, metadata, context); String[] result = textHandler.toString().split(regex); for (int i = 0; i < result.length && keepRunning; i++) { if (interrupt) { processInterrupt(); } addToIndex(r.getNoteGuid(), result[i], "RESOURCE"); } input.close(); f.close(); } catch (java.lang.ClassCastException e) { logger.log(logger.LOW, "Cast exception: " + e.getMessage()); } catch (FileNotFoundException e) { logger.log(logger.LOW, "FileNotFound exception: " + e.getMessage()); } catch (IOException e) { logger.log(logger.LOW, "IO exception: " + e.getMessage()); } catch (SAXException e) { logger.log(logger.LOW, "SAX exception: " + e.getMessage()); } catch (TikaException e) { logger.log(logger.LOW, "Tika exception: " + e.getMessage()); } catch (Exception e) { logger.log(logger.LOW, "Unknown exception: " + e.getMessage()); } catch (java.lang.NoSuchMethodError e) { logger.log(logger.LOW, "NoSuchMethod error: " + e.getMessage()); } catch (Error e) { logger.log(logger.LOW, "Unknown error: " + e.getMessage()); } }
From source file:cx.fbn.nevernote.threads.IndexRunner.java
private void indexResourceOOXML(Resource r) { Data d = r.getData();// w w w . j av a 2s . c o m for (int i = 0; i < 20 && d.getSize() == 0; i++) d = r.getData(); if (d.getSize() == 0) return; QTemporaryFile f = writeResource(d); if (!keepRunning) { return; } InputStream input; try { input = new FileInputStream(new File(f.fileName())); ContentHandler textHandler = new BodyContentHandler(-1); Metadata metadata = new Metadata(); OOXMLParser parser = new OOXMLParser(); ParseContext context = new ParseContext(); parser.parse(input, textHandler, metadata, context); String[] result = textHandler.toString().split(regex); for (int i = 0; i < result.length && keepRunning; i++) { if (interrupt) { processInterrupt(); } addToIndex(r.getNoteGuid(), result[i], "RESOURCE"); } input.close(); f.close(); } catch (java.lang.ClassCastException e) { logger.log(logger.LOW, "Cast exception: " + e.getMessage()); } catch (FileNotFoundException e) { logger.log(logger.LOW, "FileNotFound exception: " + e.getMessage()); } catch (IOException e) { logger.log(logger.LOW, "IO exception: " + e.getMessage()); } catch (SAXException e) { logger.log(logger.LOW, "SAX exception: " + e.getMessage()); } catch (TikaException e) { logger.log(logger.LOW, "Tika exception: " + e.getMessage()); } catch (Exception e) { logger.log(logger.LOW, "Unknown exception: " + e.getMessage()); } catch (java.lang.NoSuchMethodError e) { logger.log(logger.LOW, "NoSuchMethod error: " + e.getMessage()); } catch (Error e) { logger.log(logger.LOW, "Unknown error: " + e.getMessage()); } }
From source file:play.modules.swagger.PlayReader.java
String getPathFromRoute(PathPattern pathPattern, String basePath) { StringBuilder sb = new StringBuilder(); scala.collection.Iterator iter = pathPattern.parts().iterator(); while (iter.hasNext()) { PathPart part = (PathPart) iter.next(); if (part instanceof StaticPart) { sb.append(((StaticPart) part).value()); } else if (part instanceof DynamicPart) { sb.append("{"); sb.append(((DynamicPart) part).name()); sb.append("}"); } else {/*from www.jav a2 s. co m*/ try { sb.append(((StaticPart) part).value()); } catch (ClassCastException e) { Logger.warn(String.format("ClassCastException parsing path from route: %s", e.getMessage())); } } } StringBuilder operationPath = new StringBuilder(); if (basePath.startsWith("/")) basePath = basePath.substring(1); operationPath.append(sb.toString().replaceFirst(basePath, "")); if (!operationPath.toString().startsWith("/")) operationPath.insert(0, "/"); return operationPath.toString(); }
From source file:gov.nih.nci.ncicb.cadsr.bulkloader.util.excel.DBExcelUtility.java
private String getRowXMLData(HSSFSheet hssfsheet, String sheetName, int row, int colcount, String prefix, String coltype[]) {/*from w ww .ja v a 2 s . co m*/ StringBuffer sb = new StringBuffer(); Object cdata = null; int column = 0; try { for (int i = 0; i < colcount; i++) { column = (short) (dataStart_column + i); cdata = ExcelUtility.getObject(hssfsheet, row, (short) column); //sb.append("(AV=" + cdata + "," + cdata.toString().length() + ")"); if (cdata != null && cdata.toString().length() != 0) { if (coltype[i].equalsIgnoreCase(DataType.TYPE_STRING)) { sb.append("<" + prefix + ">" + (String) cdata + "</" + prefix + ">"); } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_INTEGER)) { Integer idata = ExcelUtility.getInteger(hssfsheet, row, (short) (dataStart_column + i)); sb.append("<" + prefix + ">" + idata + "</" + prefix + ">"); } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_DOUBLE)) { Double ddata = ExcelUtility.getDouble(hssfsheet, row, (short) (dataStart_column + i)); sb.append("<" + prefix + ">" + ddata + "</" + prefix + ">"); } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_BOOLEAN)) { Boolean bdata = ExcelUtility.getBoolean(hssfsheet, row, (short) (dataStart_column + i)); sb.append("<" + prefix + ">" + bdata + "</" + prefix + ">"); } else if (coltype[i].equalsIgnoreCase(DataType.TYPE_DATE)) { Date dtval = ExcelUtility.getDate(hssfsheet, row, (short) (dataStart_column + i)); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); StringBuffer dtString = new StringBuffer(); String dt = sdf.format(dtval); //System.out.println("dtval = " + dtval); //System.out.println("dt = " + dtString.toString()); sb.append("<" + prefix + ">" + dt + "</" + prefix + ">"); } } else { sb.append("<none/>"); } } return sb.toString(); } catch (ClassCastException ce) { ce.printStackTrace(); throw new ClassCastException("There is a type problem in the excel worksheet on Sheet='" + sheetName + "', and Cell(" + (row + 1) + "," + (column + 1) + ")" + "\n" + ce.getMessage()); } }
From source file:ch.entwine.weblounge.dispatcher.impl.handler.FileRequestHandlerImpl.java
/** * Handles the request for a file resource that is believed to be in the * content repository. The handler sets the response headers and the writes * the file contents to the response./* ww w .j a va 2 s. com*/ * <p> * This method returns <code>true</code> if the handler is decided to handle * the request, <code>false</code> otherwise. * * @param request * the weblounge request * @param response * the weblounge response */ public boolean service(WebloungeRequest request, WebloungeResponse response) { WebUrl url = request.getUrl(); Site site = request.getSite(); String path = url.getPath(); String fileName = null; // Get hold of the content repository ContentRepository contentRepository = site.getContentRepository(); if (contentRepository == null) { logger.warn("No content repository found for site '{}'", site); return false; } else if (contentRepository.isIndexing()) { logger.debug("Content repository of site '{}' is currently being indexed", site); DispatchUtils.sendServiceUnavailable(request, response); return true; } // Check if the request uri matches the special uri for files. If so, try // to extract the id from the last part of the path. If not, check if there // is a file with the current path. ResourceURI fileURI = null; Resource<? extends FileContent> fileResource = null; try { String id = null; String filePath = null; if (path.startsWith(URI_PREFIX)) { String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/"); uriSuffix = URLDecoder.decode(uriSuffix, "utf-8"); // Check whether we are looking at a uuid or a url path if (uriSuffix.length() == UUID_LENGTH) { id = uriSuffix; } else if (uriSuffix.length() >= UUID_LENGTH) { int lastSeparator = uriSuffix.indexOf('/'); if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) { id = uriSuffix.substring(0, lastSeparator); fileName = uriSuffix.substring(lastSeparator + 1); } else { filePath = uriSuffix; fileName = FilenameUtils.getName(filePath); } } else { filePath = "/" + uriSuffix; fileName = FilenameUtils.getName(filePath); } fileURI = new GeneralResourceURIImpl(site, filePath, id); } else { filePath = path; fileName = FilenameUtils.getName(filePath); fileURI = new FileResourceURIImpl(site, filePath, null); } // Try to load the resource try { fileResource = (Resource<? extends FileContent>) contentRepository.get(fileURI); if (fileResource == null) { logger.debug("No file found at {}", fileURI); return false; } } catch (ClassCastException e) { logger.debug("Resource {} does not extend file resource {}", fileURI); return false; } } catch (ContentRepositoryException e) { logger.error("Error loading file from {}: {}", contentRepository, e); DispatchUtils.sendInternalError(request, response); return true; } catch (UnsupportedEncodingException e) { logger.error("Error decoding file url {} using utf-8: {}", path, e.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } // Try to serve the file logger.debug("File handler agrees to handle {}", path); // Check the request method. Only GET is supported right now. String requestMethod = request.getMethod().toUpperCase(); if ("OPTIONS".equals(requestMethod)) { String verbs = "OPTIONS,GET"; logger.trace("Answering options request to {} with {}", url, verbs); response.setHeader("Allow", verbs); response.setContentLength(0); return true; } else if (!"GET".equals(requestMethod)) { logger.debug("File request handler does not support {} requests", requestMethod); DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response); return true; } // Is it published? // TODO: Fix this. fileResource.isPublished() currently returns false, // as both from and to dates are null (see PublishingCtx) // if (!fileResource.isPublished()) { // logger.debug("Access to unpublished file {}", fileURI); // DispatchUtils.sendNotFound(request, response); // return true; // } // Can the page be accessed by the current user? User user = request.getUser(); try { // TODO: Check permission // PagePermission p = new PagePermission(page, user); // AccessController.checkPermission(p); } catch (SecurityException e) { logger.warn("Access to file {} denied for user {}", fileURI, user); DispatchUtils.sendAccessDenied(request, response); return true; } // Determine the response language by filename Language language = null; if (StringUtils.isNotBlank(fileName)) { for (FileContent c : fileResource.contents()) { if (c.getFilename().equalsIgnoreCase(fileName)) { if (language != null) { logger.debug("Unable to determine language from ambiguous filename"); language = LanguageUtils.getPreferredContentLanguage(fileResource, request, site); break; } language = c.getLanguage(); } } if (language == null) language = LanguageUtils.getPreferredContentLanguage(fileResource, request, site); } else { language = LanguageUtils.getPreferredContentLanguage(fileResource, request, site); } // If the filename did not lead to a language, apply language resolution if (language == null) { logger.warn("File {} does not exist in any supported language", fileURI); DispatchUtils.sendNotFound(request, response); return true; } // Check the modified headers long revalidationTime = MS_PER_DAY; long expirationDate = System.currentTimeMillis() + revalidationTime; if (!ResourceUtils.hasChanged(request, fileResource, language)) { logger.debug("File {} was not modified", fileURI); response.setDateHeader("Expires", expirationDate); DispatchUtils.sendNotModified(request, response); return true; } // Add mime type header FileContent content = fileResource.getContent(language); // If the content is hosted externally, send a redirect and be done with it if (content.getExternalLocation() != null) { try { response.sendRedirect(content.getExternalLocation().toExternalForm()); } catch (IOException e) { logger.debug("Client ignore redirect to {}", content.getExternalLocation()); } return true; } String contentType = content.getMimetype(); if (contentType == null) contentType = MediaType.APPLICATION_OCTET_STREAM; // Set the content type String characterEncoding = response.getCharacterEncoding(); if (StringUtils.isNotBlank(characterEncoding)) response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase()); else response.setContentType(contentType); // Browser caches and proxies are allowed to keep a copy response.setHeader("Cache-Control", "public, max-age=" + revalidationTime); // Add last modified header response.setDateHeader("Last-Modified", ResourceUtils.getModificationDate(fileResource, language).getTime()); // Add ETag header String eTag = ResourceUtils.getETagValue(fileResource); response.setHeader("ETag", eTag); // Set the Expires header response.setDateHeader("Expires", expirationDate); // Add content disposition header response.setHeader("Content-Disposition", "inline; filename=" + content.getFilename()); // Add content size response.setHeader("Content-Length", Long.toString(content.getSize())); // Write the file back to the response InputStream fileContents = null; try { fileContents = contentRepository.getContent(fileURI, language); IOUtils.copy(fileContents, response.getOutputStream()); response.getOutputStream().flush(); return true; } catch (ContentRepositoryException e) { logger.error("Unable to load file {}: {}", new Object[] { fileURI, e.getMessage(), e }); DispatchUtils.sendInternalError(request, response); return true; } catch (EOFException e) { logger.debug("Error writing file '{}' back to client: connection closed by client", fileURI); return true; } catch (IOException e) { if (RequestUtils.isCausedByClient(e)) return true; logger.error("Error sending file {} to the client: {}", fileURI, e.getMessage()); DispatchUtils.sendInternalError(request, response); return true; } finally { IOUtils.closeQuietly(fileContents); } }
From source file:com.buffalokiwi.aerodrome.jet.products.JetAPIProduct.java
/** * Retrieve product variations exceptions by sku. * //w w w .java 2 s .c o m * @param sku Product sku * @return api response * @throws APIException * @throws JetException */ @Override public ProductVariationGroupRec getProductVariations(final String sku) throws APIException, JetException { checkSku(sku); try { return ProductVariationGroupRec.fromJSON(sku, sendGetProductVariations(sku).getJsonObject()); } catch (ClassCastException e) { APILog.error(LOG, "Failed to convert variation_refinements or children_skus to a List"); throw new JetException(e.getMessage(), e); } }
From source file:org.knime.knip.io.nodes.imgwriter2.ImgWriter2NodeModel.java
/** * {@inheritDoc}//from w w w.j av a 2 s .c om */ @SuppressWarnings("unchecked") @Override protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec) throws Exception { checkDimensionMapping(); String directory = null; // only initialize output directory when needed if (!m_useAbsolutePaths.getBooleanValue()) { Path folderPath = createOutputPath(); directory = folderPath.toString(); if (!directory.endsWith("/")) { // fix directory path directory += "/"; } } // loop constants final boolean overwrite = m_overwrite.getBooleanValue(); final boolean useCustomName = m_customNameOption.getBooleanValue(); final boolean useAbsolutPaths = m_useAbsolutePaths.getBooleanValue(); final boolean forceMkdir = m_forceMkdir.getBooleanValue(); final String customName = m_customFileName.getStringValue(); final int nameColIndex = inData[0].getDataTableSpec().findColumnIndex(m_filenameColumn.getStringValue()); final int imgColIndex = inData[0].getDataTableSpec().findColumnIndex(m_imgColumn.getStringValue()); final String format = m_format.getStringValue(); final String compression = m_compression.getStringValue(); /* File name number magic */ // get number of digits needed for padding final int digits = (int) Math.log10(inData[0].getRowCount()) + 1; final String digitStringFormat = "%0" + digits + "d"; int imgCount = 0; // loop variables ImgPlus<T> img; String outfile; boolean error = false; final ImgWriter2 writer = new ImgWriter2().setWriteSequantially(m_writeSequentially.getBooleanValue()) .setFramesPerSecond(m_frameRate.getIntValue()); for (DataRow row : inData[0]) { // set the filename if (useAbsolutPaths) { outfile = ((StringValue) row.getCell(nameColIndex)).getStringValue(); } else if (useCustomName) { outfile = directory + customName + String.format(digitStringFormat, imgCount); } else if (nameColIndex == -1) { outfile = directory + row.getKey().getString(); } else { // file name column configured try { outfile = directory + ((StringValue) row.getCell(nameColIndex)).getStringValue(); } catch (ClassCastException e1) { throw new IllegalArgumentException( "Missing value in the filename column in row: " + row.getKey()); } } outfile += "." + writer.getSuffix(format); // handle file location final File f = FileUtil.resolveToPath(FileUtil.toURL(outfile)).toFile(); if (f.exists()) { if (overwrite) { LOGGER.warn("The file " + outfile + " already exits and will be OVERWRITTEN."); f.delete(); } else { throw new InvalidSettingsException( "The file " + outfile + " exits and must not be overwritten due to user settings."); } // filename contained path to non existent directory } else if (!f.getParentFile().exists()) { if (forceMkdir) { LOGGER.info("Creating directory: " + f.getParentFile().getPath()); FileUtils.forceMkdir(f.getParentFile()); } else { throw new InvalidSettingsException("Output directory " + f.getParentFile().getPath() + " doesn't exist, you can force the creation" + " in the node settings."); } } try { img = ((ImgPlusValue<T>) row.getCell(imgColIndex)).getImgPlus(); } catch (ClassCastException e) { throw new IllegalArgumentException("Missing value in the img column in row: " + row.getKey()); } // create dimensions mapping final int[] map = createDimMapping(img); try { writer.writeImage(img, FileUtil.resolveToPath(FileUtil.toURL(outfile)).toString(), format, compression, map); } catch (final FormatException | IOException e) { LOGGER.error("Error while writing image " + outfile + " : " + e.getMessage(), e); error = true; } catch (final UnsupportedOperationException e) { LOGGER.error("Error while writing image " + outfile + " : " + "Check the filename for illegal characters! " + e.getMessage(), e); error = true; } exec.setProgress((double) imgCount / inData[0].getRowCount()); exec.checkCanceled(); imgCount++; } if (error) { setWarningMessage("Some errors occured during the writing process!"); } return null; }
From source file:argendata.web.controller.AdminController.java
@RequestMapping(method = RequestMethod.POST) public ModelAndView deleteApp(@RequestParam("qName") String qName) { ModelAndView mav = new ModelAndView(); App myApp;// w ww . jav a2s . c o m try { myApp = appService.getApprovedAppByQName(qName); } catch (java.lang.ClassCastException e) { myApp = null; } if (myApp == null) { /* Si no esta en forma semantica, pruebo si esta en la PreApp */ myApp = appService.getPreAppByQName(qName); if (myApp == null) { mav.setViewName("redirect:home"); return mav; } } try { appService.approvedAppDelete(myApp); } catch (Exception e) { logger.error("No se pudo borrar del store semantico"); logger.error(e.getMessage(), e); mav.setViewName("redirect:/bin/static/error"); return mav; } mav.setViewName("redirect:../search/searchAppMain"); return mav; }
From source file:rapture.repo.jdbc.JDBCStructuredStore.java
@Override public String getCursorUsingSql(CallingContext context, String sql) { try {/* ww w .ja va2 s.co m*/ // check entitlements on tables Select select = (Select) CCJSqlParserUtil.parse(sql); SelectConverter selectConverter = getSelectConverter(); select.getSelectBody().accept(selectConverter); checkEntitlements(context, selectConverter.getContext()); // execute query ResultSet rs = getPreparedStatementForCursor(sql).executeQuery(); String uuid = IDGenerator.getUUID(); cache.putCursor(uuid, rs); return uuid; } catch (ClassCastException e) { throw RaptureExceptionFactory.create("Not a select statement: " + sql, e); } catch (JSQLParserException e) { throw RaptureExceptionFactory.create("Failed to parse statement: " + sql, e); } catch (SQLException e) { throw RaptureExceptionFactory .create(String.format("Sql Exception executing cursor query [%s]", e.getMessage())); } }