List of usage examples for java.io FileNotFoundException toString
public String toString()
From source file:org.tinygroup.jspengine.compiler.TagLibraryInfoImpl.java
/** * Constructor which builds a TagLibraryInfoImpl by parsing a TLD. *///w ww . j a va2 s. c o m public TagLibraryInfoImpl(JspCompilationContext ctxt, ParserController pc, String prefix, String uriIn, String[] location, ErrorDispatcher err) throws JasperException { super(prefix, uriIn); this.ctxt = ctxt; this.parserController = pc; this.pageInfo = pc.getCompiler().getPageInfo(); this.err = err; InputStream in = null; JarFile jarFile = null; if (location == null) { // The URI points to the TLD itself or to a JAR file in which the // TLD is stored location = generateTLDLocation(uri, ctxt); } try { if (!location[0].endsWith("jar")) { // Location points to TLD file try { in = getResourceAsStream(location[0]); if (in == null) { throw new FileNotFoundException(location[0]); } } catch (FileNotFoundException ex) { err.jspError("jsp.error.file.not.found", location[0]); } parseTLD(ctxt, location[0], in, null); // Add TLD to dependency list PageInfo pageInfo = ctxt.createCompiler(false).getPageInfo(); if (pageInfo != null) { pageInfo.addDependant(location[0]); } } else { // Tag library is packaged in JAR file try { URL jarFileUrl = new URL("jar:" + location[0] + "!/"); JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection(); conn.setUseCaches(false); conn.connect(); jarFile = conn.getJarFile(); ZipEntry jarEntry = jarFile.getEntry(location[1]); in = jarFile.getInputStream(jarEntry); parseTLD(ctxt, location[0], in, jarFileUrl); } catch (Exception ex) { err.jspError("jsp.error.tld.unable_to_read", location[0], location[1], ex.toString()); } } } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { } } } }
From source file:org.apache.webdav.cmd.Client.java
void executeScript(String scriptname) { try {/*from ww w . j a v a 2s . c om*/ FileInputStream script = new FileInputStream(scriptname); Client scriptClient = new Client(script, out); scriptClient.setDisplayPrompt(false); out.println("Executing script: " + scriptname); scriptClient.run(); out.println("Script " + scriptname + " complete."); script.close(); } catch (FileNotFoundException ex) { out.println("Error: Script " + scriptname + " not found."); } catch (IOException ex) { out.println("Error: " + ex.toString() + " during execution of " + scriptname); } }
From source file:main.java.vasolsim.common.file.ExamBuilder.java
/** * Writes an exam to an XML file//from w w w. j a va 2 s . co m * * @param exam the exam to be written * @param examFile the target file * @param password the passphrase locking the restricted content * @param overwrite if an existing file can be overwritten * * @return if the write was successful * * @throws VaSolSimException */ public static boolean writeExam(@Nonnull Exam exam, @Nonnull File examFile, @Nonnull String password, boolean overwrite) throws VaSolSimException { logger.info("beginning exam export -> " + exam.getTestName()); logger.debug("checking export destination..."); /* * check the file creation status and handle it */ //if it exists if (examFile.isFile()) { logger.trace("exam file exists, checking overwrite..."); //can't overwrite if (!overwrite) { logger.error("file already present and cannot overwrite"); throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS); } //can overwrite, clear the existing file else { logger.trace("overwriting..."); PrintWriter printWriter; try { printWriter = new PrintWriter(examFile); } catch (FileNotFoundException e) { logger.error("internal file presence check failed", e); throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK); } printWriter.print(""); printWriter.close(); } } //no file, create one else { logger.trace("exam file does not exist, creating..."); if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) { logger.error("could not create empty directories for export"); throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS); } try { logger.trace("creating files..."); if (!examFile.createNewFile()) { logger.error("could not create empty file for export"); throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE); } } catch (IOException e) { logger.error("io error on empty file creation", e); throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION); } } logger.debug("initializing weak cryptography scheme..."); /* * initialize the cryptography system */ String encryptedHash; Cipher encryptionCipher; try { logger.trace("hashing password into key..."); //hash the password byte[] hash; MessageDigest msgDigest = MessageDigest.getInstance("SHA-512"); msgDigest.update(password.getBytes()); hash = GenericUtils.validate512HashTo128Hash(msgDigest.digest()); logger.trace("initializing cipher"); encryptionCipher = GenericUtils.initCrypto(hash, Cipher.ENCRYPT_MODE); encryptedHash = GenericUtils .convertBytesToHexString(GenericUtils.applyCryptographicCipher(hash, encryptionCipher)); } catch (NoSuchAlgorithmException e) { logger.error("FAILED. could not initialize crypto", e); throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } logger.debug("initializing the document builder..."); /* * initialize the document */ Document examDoc; Transformer examTransformer; try { logger.trace("create document builder factory instance -> create new doc"); examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); logger.trace("set document properties"); examTransformer = TransformerFactory.newInstance().newTransformer(); examTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); examTransformer.setOutputProperty(OutputKeys.METHOD, "xml"); examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd"); examTransformer.setOutputProperty(INDENTATION_KEY, "4"); } catch (ParserConfigurationException e) { logger.error("parser was not configured correctly", e); throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e); } catch (TransformerConfigurationException e) { logger.error("transformer was not configured properly"); throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e); } logger.debug("building document..."); /* * build exam info */ logger.trace("attaching root..."); Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME); examDoc.appendChild(root); logger.trace("attaching info..."); Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME); root.appendChild(info); //exam info logger.trace("attaching exam info..."); GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc); GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc); GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc); GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc); GenericUtils.appendSubNode(XML_DATE_ELEMENT_NAME, exam.getDate(), info, examDoc); //start security xml section logger.trace("attaching security..."); Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME); root.appendChild(security); GenericUtils.appendSubNode(XML_ENCRYPTED_VALIDATION_HASH_ELEMENT_NAME, encryptedHash, security, examDoc); GenericUtils.appendSubNode(XML_PARAMETRIC_INITIALIZATION_VECTOR_ELEMENT_NAME, GenericUtils.convertBytesToHexString(encryptionCipher.getIV()), security, examDoc); GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME, Boolean.toString(exam.isReportingStats()), security, examDoc); GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME, Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsDestinationEmail() == null ? GenericUtils.NO_EMAIL.getBytes() : exam.getStatsDestinationEmail().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsSenderEmail() == null ? GenericUtils.NO_EMAIL.getBytes() : exam.getStatsSenderEmail().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_PASSWORD_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsSenderPassword() == null ? GenericUtils.NO_DATA.getBytes() : exam.getStatsSenderPassword().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsSenderSMTPAddress() == null ? GenericUtils.NO_SMTP.getBytes() : exam.getStatsSenderSMTPAddress().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( Integer.toString(exam.getStatsSenderSMTPPort()).getBytes(), encryptionCipher)), security, examDoc); logger.debug("checking exam content integrity..."); ArrayList<QuestionSet> questionSets = exam.getQuestionSets(); if (GenericUtils.checkExamIntegrity(exam).size() == 0) { logger.debug("exporting exam content..."); for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) { QuestionSet qSet = questionSets.get(setsIndex); logger.trace("exporting question set -> " + qSet.getName()); Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME); root.appendChild(qSetElement); GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1), qSetElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME, (qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1) : qSet.getName(), qSetElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME, qSet.getResourceType().toString(), qSetElement, examDoc); if (qSet.getResourceType() != GenericUtils.ResourceType.NONE && qSet.getResources() != null) { logger.debug("exporting question set resources..."); for (BufferedImage img : qSet.getResources()) { if (img != null) { try { logger.trace("writing image..."); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(img, "png", out); out.flush(); GenericUtils.appendCDATASubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME, new String(Base64.encodeBase64(out.toByteArray())), qSetElement, examDoc); } catch (IOException e) { throw new VaSolSimException( "Error: cannot write images to byte array for transport"); } } } } //TODO export problem in this subroutine for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) { Question question = qSet.getQuestions().get(setIndex); logger.trace("exporting question -> " + question.getName()); Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME); qSetElement.appendChild(qElement); logger.trace("question id -> " + setIndex); GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1), qElement, examDoc); logger.trace("question name -> " + question.getName()); GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME, (question.getName().equals("")) ? "Question " + (setIndex + 1) : question.getName(), qElement, examDoc); logger.trace("question test -> " + question.getQuestion()); GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement, examDoc); logger.trace("question answer scramble -> " + Boolean.toString(question.getScrambleAnswers())); GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME, Boolean.toString(question.getScrambleAnswers()), qElement, examDoc); logger.trace("question answer order matters -> " + Boolean.toString(question.getAnswerOrderMatters())); GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME, Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc); logger.debug("exporting correct answer choices..."); for (AnswerChoice answer : question.getCorrectAnswerChoices()) { logger.trace("exporting correct answer choice(s) -> " + answer.getAnswerText()); GenericUtils .appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( answer.getAnswerText().getBytes(), encryptionCipher)), qElement, examDoc); } logger.debug("exporting answer choices..."); for (int questionIndex = 0; questionIndex < question.getAnswerChoices() .size(); questionIndex++) { if (question.getAnswerChoices().get(questionIndex).isActive()) { AnswerChoice ac = question.getAnswerChoices().get(questionIndex); logger.trace("exporting answer choice -> " + ac.getAnswerText()); Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME); qElement.appendChild(acElement); logger.trace("answer choice id -> " + questionIndex); GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME, Integer.toString(questionIndex + 1), acElement, examDoc); logger.trace("answer choice visible id -> " + ac.getVisibleChoiceID()); GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME, ac.getVisibleChoiceID(), acElement, examDoc); logger.trace("answer text -> " + ac.getAnswerText()); GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement, examDoc); } } } } } else { logger.error("integrity check failed"); PopupManager.showMessage(errorsToOutput(GenericUtils.checkExamIntegrity(exam))); return false; } logger.debug("transforming exam..."); try { examTransformer.transform(new DOMSource(examDoc), new StreamResult(examFile)); } catch (TransformerException e) { logger.error("exam export failed (transformer error)", e); return false; } logger.debug("transformation done"); logger.info("exam export successful"); return true; }
From source file:eu.planets_project.tb.gui.backing.ExperimentBean.java
private Collection<Map<String, String>> helperGetDataNamesAndURIS(String expStage) { Collection<Map<String, String>> ret = new Vector<Map<String, String>>(); DataHandler dh = new DataHandlerImpl(); //when we're calling this in design experiment -> fetch the input data refs if (expStage.equals("design experiment")) { Map<String, String> localFileRefs = this.getExperimentInputData(); for (String key : localFileRefs.keySet()) { boolean found = false; try { Map<String, String> map = new HashMap<String, String>(); //retrieve URI String fInput = localFileRefs.get(key); DigitalObjectRefBean dobr = dh.get(fInput); if (dobr != null) { URI uri = dobr.getDownloadUri(); map.put("uri", uri.toString()); map.put("name", this.createShortDoName(dobr)); map.put("inputID", key); ret.add(map);//from www . j ava 2 s. co m found = true; } else { log.error("Digital Object " + key + " could not be found!"); } } catch (FileNotFoundException e) { log.error(e.toString()); } // Catch lost items... if (!found) { Map<String, String> map = new HashMap<String, String>(); String fInput = localFileRefs.get(key); map.put("uri", fInput); map.put("name", "ERROR: Digital Object Not Found: " + getLeafnameFromPath(fInput)); map.put("inputID", key); ret.add(map); } } } //when we're calling this in evaluate experiment -> fetch the external eval data refs if (expStage.equals("evaluate expeirment") && this.getEvaluationExternalDigoRefs() != null) { for (String digoRef : this.getEvaluationExternalDigoRefs()) { try { Map<String, String> map = new HashMap<String, String>(); DigitalObjectRefBean dobr = dh.get(digoRef); if (dobr != null) { URI uri = dobr.getDownloadUri(); map.put("uri", uri.toString()); map.put("name", this.createShortDoName(dobr)); map.put("inputID", dobr.getDomUri() + ""); ret.add(map); } else { log.error("Digital Object " + digoRef + " could not be found!"); } } catch (FileNotFoundException e) { log.error(e.toString()); } } } return ret; }
From source file:org.apache.hadoop.hive.ql.exec.DCLTask.java
private int showGrants(ShowGrantsDesc showGntsDesc) throws HiveException, AuthorizeException { String userName = showGntsDesc.getUser(); if (userName == null) { userName = SessionState.get().getUserName(); }/*from w w w. j a va 2 s . c o m*/ User user = db.getUser(userName); try { if (user == null) { FileSystem fs = showGntsDesc.getResFile().getFileSystem(conf); DataOutput outStream = (DataOutput) fs.open(showGntsDesc.getResFile()); String errMsg = "User " + userName + " does not exist"; outStream.write(errMsg.getBytes("UTF-8")); ((FSDataOutputStream) outStream).close(); return 0; } } catch (FileNotFoundException e) { LOG.info("show grants: " + StringUtils.stringifyException(e)); return 1; } catch (IOException e) { LOG.info("show grants: " + StringUtils.stringifyException(e)); return 1; } try { LOG.info("DCLTask: got grant privilege for " + user.getName()); FileSystem fs = showGntsDesc.getResFile().getFileSystem(conf); DataOutput outStream = (DataOutput) fs.create(showGntsDesc.getResFile()); List<AuthorizeEntry> entries = SessionState.get().getAuthorizer().getAllPrivileges(userName); if (entries == null || entries.isEmpty()) { return 0; } for (AuthorizeEntry e : entries) { switch (e.getPrivLevel()) { case GLOBAL_LEVEL: outStream.writeBytes("Global grants: "); break; case DATABASE_LEVEL: outStream.writeBytes(String.format("Grants on database %s:", e.getDb().getName())); break; case TABLE_LEVEL: outStream.writeBytes(String.format("Grants on table %s.%s:", e.getTable().getDbName(), e.getTable().getTableName())); break; case COLUMN_LEVEL: String fields = ""; if (e.getFields() != null && !e.getFields().isEmpty()) { for (FieldSchema f : e.getFields()) { fields += f.getName() + ","; } } else { fields = "<null>"; } outStream.writeBytes(String.format("Grants on column %s.%s.[%s]:", e.getTable().getDbName(), e.getTable().getTableName(), fields)); break; default: } for (Privilege p : e.getRequiredPrivs()) { outStream.writeBytes(p.toString() + " "); } outStream.write(terminator); } LOG.info("DCLTask: written data for " + user.getName()); ((FSDataOutputStream) outStream).close(); } catch (FileNotFoundException e) { LOG.info("show grants: " + StringUtils.stringifyException(e)); return 1; } catch (IOException e) { LOG.info("show grants: " + StringUtils.stringifyException(e)); return 1; } catch (Exception e) { throw new HiveException(e.toString()); } return 0; }
From source file:manager.doCreateToy.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . ja v a 2 s. c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String categoryList = ""; String fileName = null; if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); imageFile = new File(item.getName()); fileName = name; } else { if (item.getFieldName().equals("toyID")) { toyID = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("toyName")) { toyName = item.getString(); } if (item.getFieldName().equals("description")) { description = item.getString(); } if (item.getFieldName().equals("category")) { categoryList += item.getString(); } if (item.getFieldName().equals("secondHand")) { secondHand = item.getString(); } if (item.getFieldName().equals("cashpoint")) { cashpoint = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("qty")) { qty = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("discount")) { discount = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("uploadString")) { base64String = item.getString(); } //if(item.getFieldName().equals("desc")) // desc= item.getString(); } } category = categoryList.split(";"); //File uploaded successfully //request.setAttribute("message", "File Uploaded Successfully" + desc); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } File file = imageFile; if (!(fileName == null)) { try { /* * Reading a Image file from file system */ FileInputStream imageInFile = new FileInputStream(file); byte imageData[] = new byte[(int) file.length()]; imageInFile.read(imageData); /* * Converting Image byte array into Base64 String */ String imageDataString = encodeImage(imageData); request.setAttribute("test", imageDataString); /* * Converting a Base64 String into Image byte array */ //byte[] imageByteArray = decodeImage(imageDataString); /* * Write a image byte array into file system */ //FileOutputStream imageOutFile = new FileOutputStream("C:\\Users\\Mesong\\Pictures\\Screenshots\\30.png"); //imageOutFile.write(imageByteArray); //request.setAttribute("photo", imageDataString); // toyDB toydb = new toyDB(); //Toy t = toydb.listToyByID(1); // toydb.updateToy(t.getToyID(), imageDataString, t.getCashpoint(), t.getQTY(), t.getDiscount()); imageInFile.close(); //request.getRequestDispatcher("managerPage/result.jsp").forward(request, response); //imageOutFile.close(); imgString = imageDataString; System.out.println("Image Successfully Manipulated!"); } catch (FileNotFoundException e) { out.println("Image not found" + e.getMessage()); } catch (IOException ioe) { System.out.println("Exception while reading the Image " + ioe); } } try { toyDB toydb = new toyDB(); // out.println("s"); // int toyID = Integer.parseInt(request.getParameter("toyID")); // String toyName = request.getParameter("toyName"); // String description = request.getParameter("description"); // // String toyIcon = request.getParameter("toyIcon"); // // String[] category = request.getParameterValues("category"); // String secondHand = request.getParameter("secondHand"); // if(toyIcon==null) toyIcon = ""; // int cashpoint = Integer.parseInt(request.getParameter("cashpoint")); // int qty = Integer.parseInt(request.getParameter("qty")); // int discount = Integer.parseInt(request.getParameter("discount")); //toydb.updateToy(toyID, toyName,description, toyIcon, cashpoint, qty, discount); if (!base64String.equals("")) imgString = base64String; toydb.createToy(toyName, description, imgString, cashpoint, qty, discount); //for(String c : category) // out.println(c); out.println(toyID); out.println(description); out.println(toyIcon); out.println(cashpoint); out.println(qty); out.println(discount); toyCategoryDB toyCatdb = new toyCategoryDB(); // toyCatdb.deleteToyType(toyID); for (String c : category) { toyCatdb.createToyCategory(Integer.parseInt(c), toyID); } if (!secondHand.equals("")) { secondHandDB seconddb = new secondHandDB(); SecondHand sh = seconddb.searchSecondHand(Integer.parseInt(secondHand)); int secondHandCashpoint = sh.getCashpoint(); toydb.updateToySecondHand(toyID, Integer.parseInt(secondHand)); toydb.updateToy(toyID, imgString, secondHandCashpoint, qty, discount); } else { toydb.updateToySecondHand(toyID, -1); } //out.println(imgString); response.sendRedirect("doSearchToy"); } catch (Exception e) { out.println(e.toString()); } finally { out.close(); } }
From source file:com.android.mms.ui.MessageUtils.java
/** * M: read app drawable resource and create a new file in /data/data/com.android.mms/files path. * @param context//w w w. j ava2 s . c om * @param fileName * @return */ public static boolean createFileForResource(Context context, String fileName, int fileResourceId) { OutputStream os = null; InputStream ins = null; try { os = context.openFileOutput(fileName, Context.MODE_PRIVATE); ins = context.getResources().openRawResource(fileResourceId); byte[] buffer = new byte[2048]; for (int len = 0; (len = ins.read(buffer)) != -1;) { os.write(buffer, 0, len); } return true; } catch (FileNotFoundException e) { MmsLog.e(TAG, "create file failed.", e); return false; } catch (IOException e) { MmsLog.e(TAG, "create file failed.", e); return false; } finally { try { if (null != ins) { ins.close(); } if (null != os) { os.close(); } } catch (IOException e) { MmsLog.e(TAG, "createFileForResource:" + e.toString()); } } }
From source file:org.apache.slider.client.SliderClient.java
/** * Launched service execution. This runs {@link #exec()} * then catches some exceptions and converts them to exit codes * @return an exit code/*from w ww . j a v a 2s. co m*/ * @throws Throwable */ @Override public int runService() throws Throwable { try { return exec(); } catch (FileNotFoundException nfe) { throw new NotFoundException(nfe, nfe.toString()); } catch (PathNotFoundException nfe) { throw new NotFoundException(nfe, nfe.toString()); } }
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String GetIniData(String sSection, String sKey, String sFile) { String sRet = ""; String sComp = ""; String sLine = ""; boolean bFound = false; BufferedReader in = null;/* ww w. j ava2 s .c o m*/ String sTmpFileName = fixFileName(sFile); try { in = new BufferedReader(new FileReader(sTmpFileName)); sComp = "[" + sSection + "]"; while ((sLine = in.readLine()) != null) { if (sLine.equalsIgnoreCase(sComp)) { bFound = true; break; } } if (bFound) { sComp = (sKey + " =").toLowerCase(); while ((sLine = in.readLine()) != null) { if (sLine.toLowerCase().contains(sComp)) { String[] temp = null; temp = sLine.split("="); if (temp != null) { if (temp.length > 1) sRet = temp[1].trim(); } break; } } } in.close(); } catch (FileNotFoundException e) { sComp = e.toString(); } catch (IOException e) { sComp = e.toString(); } return (sRet); }
From source file:org.wikipedia.nirvana.NirvanaBasicBot.java
public void startWithConfig(String cfg, Map<String, String> launch_params) { properties = new Properties(); try {//w ww. j a v a2 s . c o m InputStream in = new FileInputStream(cfg); if (cfg.endsWith(".xml")) { properties.loadFromXML(in); } else { properties.load(in); } in.close(); } catch (FileNotFoundException e) { System.out.println("ABORT: file " + cfg + " not found"); return; } catch (IOException e) { System.out.println("ABORT: Error reading config: " + cfg); return; } initLog(); String login = properties.getProperty("wiki-login"); String pw = properties.getProperty("wiki-password"); if (login == null || pw == null || login.isEmpty() || pw.isEmpty()) { String accountFile = properties.getProperty("wiki-account-file"); if (accountFile == null || accountFile.isEmpty()) { System.out.println("ABORT: login info not found in properties"); log.fatal("wiki-login or wiki-password or wiki-account-file is not specified in settings"); return; } Properties loginProp = new Properties(); try { InputStream in = new FileInputStream(accountFile); if (accountFile.endsWith(".xml")) { loginProp.loadFromXML(in); } else { loginProp.load(in); } in.close(); } catch (FileNotFoundException e) { System.out.println("ABORT: file " + accountFile + " not found"); log.fatal("ABORT: file " + accountFile + " not found"); return; } catch (IOException e) { System.out.println("ABORT: failed to read " + accountFile); log.fatal("failed to read " + accountFile + " : " + e); return; } login = loginProp.getProperty("wiki-login"); pw = loginProp.getProperty("wiki-password"); if (login == null || pw == null || login.isEmpty() || pw.isEmpty()) { System.out.println("ABORT: login info not found in file " + accountFile); log.fatal("wiki-login or wiki-password or wiki-account-file is not found in file " + accountFile); return; } } log.info("login=" + login + ",password=(not shown)"); LANGUAGE = properties.getProperty("wiki-lang", LANGUAGE); log.info("language=" + LANGUAGE); DOMAIN = properties.getProperty("wiki-domain", DOMAIN); log.info("domain=" + DOMAIN); PROTOCOL = properties.getProperty("wiki-protocol", PROTOCOL); log.info("protocol=" + PROTOCOL); COMMENT = properties.getProperty("update-comment", COMMENT); MAX_LAG = Integer.valueOf(properties.getProperty("wiki-maxlag", String.valueOf(MAX_LAG))); THROTTLE_TIME_MS = Integer .valueOf(properties.getProperty("wiki-throttle", String.valueOf(THROTTLE_TIME_MS))); log.info("comment=" + COMMENT); DEBUG_MODE = properties.getProperty("debug-mode", DEBUG_MODE ? YES : NO).equals(YES); log.info("DEBUG_MODE=" + DEBUG_MODE); if (!loadCustomProperties(launch_params)) { log.fatal("Failed to load all required properties. Exiting..."); return; } String domain = DOMAIN; if (domain.startsWith(".")) { domain = LANGUAGE + DOMAIN; } wiki = createWiki(domain, SCRIPT_PATH, PROTOCOL); configureWikiBeforeLogin(); log.info("login to " + domain + ", login: " + login + ", password: (not shown)"); try { wiki.login(login, pw.toCharArray()); } catch (FailedLoginException e) { log.fatal("Failed to login to " + LANGUAGE + ".wikipedia.org, login: " + login + ", password: " + pw); return; } catch (IOException e) { log.fatal(e.toString()); e.printStackTrace(); return; } if (DEBUG_MODE) { wiki.setDumpMode(); } log.warn("BOT STARTED"); try { go(); } catch (InterruptedException e) { onInterrupted(e); } wiki.logout(); log.warn("EXIT"); }