label
int64
0
1
func1
stringlengths
173
53.1k
func2
stringlengths
173
53.1k
id
int64
0
901k
0
private static void grab(String urlString) throws MalformedURLException, IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); BufferedReader in = null; StringBuffer sb = new StringBuffer(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; boolean f = false; while ((inputLine = in.readLine()) != null) { inputLine = inputLine.trim(); if (inputLine.startsWith("<tbody>")) { f = true; continue; } if (inputLine.startsWith("</table>")) { f = false; continue; } if (f) { sb.append(inputLine); sb.append("\n"); } } process(sb.toString()); }
public static byte[] expandPasswordToKeySSHCom(String password, int keyLen) { try { if (password == null) { password = ""; } MessageDigest md5 = MessageDigest.getInstance("MD5"); int digLen = md5.getDigestLength(); byte[] buf = new byte[((keyLen + digLen) / digLen) * digLen]; int cnt = 0; while (cnt < keyLen) { md5.update(password.getBytes()); if (cnt > 0) { md5.update(buf, 0, cnt); } md5.digest(buf, cnt, digLen); cnt += digLen; } byte[] key = new byte[keyLen]; System.arraycopy(buf, 0, key, 0, keyLen); return key; } catch (Exception e) { throw new Error("Error in SSH2KeyPairFile.expandPasswordToKeySSHCom: " + e); } }
900,700
1
public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(QZ.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(QZ.PHRASES.getPhrase("26") + " " + QZ.PHRASES.getPhrase("27") + ": " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(QZ.PHRASES.getPhrase("19") + dest_name + QZ.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(QZ.PHRASES.getPhrase("31")); } else throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) try { source.close(); } catch (IOException e) { ; } if (destination != null) try { destination.close(); } catch (IOException e) { ; } } }
public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESENC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.encrypt(reader, writer, key, mode); }
900,701
0
public static void copierFichier(URL url, File destination) throws CopieException, IOException { if (destination.exists()) { throw new CopieException("ERREUR : Copie du fichier '" + url.getPath() + "' vers '" + destination.getPath() + "' impossible!\n" + "CAUSE : Le fichier destination existe d�j�."); } URLConnection urlConnection = url.openConnection(); InputStream httpStream = urlConnection.getInputStream(); FileOutputStream destinationFile = new FileOutputStream(destination); byte buffer[] = new byte[512 * 1024]; int nbLecture; while ((nbLecture = httpStream.read(buffer)) != -1) { destinationFile.write(buffer, 0, nbLecture); } log.debug("(COPIE) Copie du fichier : " + url.getPath() + " --> " + destination.getPath()); httpStream.close(); destinationFile.close(); }
private static boolean insereTutorial(final Connection con, final Tutorial tut, final Autor aut, final Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodTutorial(con, tut); String titulo = tut.getTitulo().replaceAll("['\"]", ""); String coment = tut.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO tutorial VALUES(" + tut.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO tut_aut VALUES(" + tut.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "TUTORIAL: Database error", JOptionPane.ERROR_MESSAGE); System.out.print(e.getMessage()); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } }
900,702
1
@Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); }
protected void sendDoc(File indir, File outdir, File orig, Document doc, ServiceEndpoint ep) { ep.setMethod("simpleDocumentTransfer"); Document response = null; try { response = protocolHandler.sendMessage(ep, doc); } catch (TransportException e) { logger.warn("Message was not accepted, will try again later"); return; } String serial = String.valueOf(System.currentTimeMillis()); File origCopy = new File(outdir, orig.getName() + "." + serial); File respDrop = new File(outdir, orig.getName() + "." + serial + ".resp"); FileOutputStream respos = null; try { respos = new FileOutputStream(respDrop); serializeDocument(respos, response); } catch (IOException e) { logger.warn("Failed to dump response"); return; } finally { try { respos.close(); } catch (IOException ignored) { } } FileInputStream in = null; FileOutputStream out = null; byte[] buffer = new byte[2048]; try { in = new FileInputStream(orig); out = new FileOutputStream(origCopy); int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy original"); return; } finally { try { in.close(); out.close(); } catch (IOException ignored) { } } orig.delete(); logger.info("File processed: " + orig.getName()); }
900,703
0
@Override public void run() { HttpGet httpGet = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); DataModel model = DataModel.getInstance(); for (City city : citiesToBeUpdated) { String preferredUnitType = PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(R.string.settings_units_key), context.getString(R.string.settings_units_default_value)); String codePrefix = city.getCountryName().startsWith("United States") ? GET_PARAM_ZIP_PREFIX : GET_PARAM_CITY_CODE_PREFIX; String requestUri = new String(GET_URL + "?" + GET_PARAM_ACODE_PREFIX + "=" + GET_PARAM_ACODE + "&" + codePrefix + "=" + city.getId() + "&" + GET_PARAM_UNIT_PREFIX + "=" + preferredUnitType); httpGet = new HttpGet(requestUri); HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { processXML(response.getEntity().getContent()); for (ForecastedDay day : forecast) { int pos = day.getImageURL().lastIndexOf('/'); if (pos < 0 || pos + 1 == day.getImageURL().length()) throw new Exception("Invalid image URL"); final String imageFilename = day.getImageURL().substring(pos + 1); File downloadDir = context.getDir(ForecastedDay.DOWNLOAD_DIR, Context.MODE_PRIVATE); File[] imagesFilteredByName = downloadDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename.equals(imageFilename)) return true; else return false; } }); if (imagesFilteredByName.length == 0) { httpGet = new HttpGet(day.getImageURL()); response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedOutputStream bus = null; try { bus = new BufferedOutputStream(new FileOutputStream(downloadDir.getAbsolutePath() + "/" + imageFilename)); response.getEntity().writeTo(bus); } finally { bus.close(); } } } } city.setDays(forecast); city.setLastUpdated(Calendar.getInstance().getTime()); model.saveCity(city); } } } catch (Exception e) { httpGet.abort(); e.printStackTrace(); } finally { handler.sendEmptyMessage(1); } }
public StringBuffer get(URL url) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer page = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { String utf = new String(line.getBytes("UTF-8"), "UTF-8"); page.append(utf); } bufferedReader.close(); return page; }
900,704
0
public static void invokeServlet(String op, String user) throws Exception { boolean isSayHi = true; try { if (!"sayHi".equals(op)) { isSayHi = false; } URL url = new URL("http://localhost:9080/helloworld/*.do"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); out.write("Operation=" + op); if (!isSayHi) { out.write("&User=" + user); } out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); boolean correctReturn = false; String response; if (isSayHi) { while ((response = in.readLine()) != null) { if (response.contains("Bonjour")) { System.out.println(" sayHi server return: Bonjour"); correctReturn = true; break; } } } else { while ((response = in.readLine()) != null) { if (response.contains("Hello CXF")) { System.out.println(" greetMe server return: Hello CXF"); correctReturn = true; break; } } } if (!correctReturn) { System.out.println("Can't got correct return from server."); } in.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
private void readFromObjectInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); ObjectInput input = new ObjectInputStream(stream); fDrawing.release(); fDrawing = (Drawing) input.readObject(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error: " + e); } catch (ClassNotFoundException e) { initDrawing(); showStatus("Class not found: " + e); } }
900,705
1
public void write(PDDocument doc) throws COSVisitorException { document = doc; SecurityHandler securityHandler = document.getSecurityHandler(); if (securityHandler != null) { try { securityHandler.prepareDocumentForEncryption(document); this.willEncrypt = true; } catch (IOException e) { throw new COSVisitorException(e); } catch (CryptographyException e) { throw new COSVisitorException(e); } } else { this.willEncrypt = false; } COSDocument cosDoc = document.getDocument(); COSDictionary trailer = cosDoc.getTrailer(); COSArray idArray = (COSArray) trailer.getDictionaryObject("ID"); if (idArray == null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(Long.toString(System.currentTimeMillis()).getBytes()); COSDictionary info = (COSDictionary) trailer.getDictionaryObject("Info"); if (info != null) { Iterator values = info.getValues().iterator(); while (values.hasNext()) { md.update(values.next().toString().getBytes()); } } idArray = new COSArray(); COSString id = new COSString(md.digest()); idArray.add(id); idArray.add(id); trailer.setItem("ID", idArray); } catch (NoSuchAlgorithmException e) { throw new COSVisitorException(e); } } cosDoc.accept(this); }
public String hash(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { log.info("No sha-256 available"); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.fatal("sha-1 is not available", e); throw new RuntimeException("Couldn't get a hash algorithm from Java"); } } try { digest.reset(); digest.update((salt + password).getBytes("UTF-8")); byte hash[] = digest.digest(); return new String(Base64.encodeBase64(hash, false)); } catch (Throwable t) { throw new RuntimeException("Couldn't hash password"); } }
900,706
1
public void display(WebPage page, HttpServletRequest req, HttpServletResponse resp) throws DisplayException { page.getDisplayInitialiser().initDisplay(new HttpRequestDisplayContext(req), req); StreamProvider is = (StreamProvider) req.getAttribute(INPUTSTREAM_KEY); if (is == null) { throw new IllegalStateException("No OutputStreamDisplayHandlerXML.InputStream found in request attribute" + " OutputStreamDisplayHandlerXML.INPUTSTREAM_KEY"); } resp.setContentType(is.getMimeType()); resp.setHeader("Content-Disposition", "attachment;filename=" + is.getName()); try { InputStream in = is.getInputStream(); OutputStream out = resp.getOutputStream(); if (in != null) { IOUtils.copy(in, out); } is.write(resp.getOutputStream()); resp.flushBuffer(); } catch (IOException e) { throw new DisplayException("Error writing input stream to response", e); } }
private void createWikiPages(WikiContext context) throws PluginException { OntologyWikiPageName owpn = new OntologyWikiPageName(omemo.getFormDataAlias().toUpperCase(), omemo.getFormDataVersionDate()); String wikiPageFullFileName = WikiPageName2FullFileName(context, owpn.toString()); String rdfFileNameWithPath = getWorkDir(context) + File.separator + owpn.toFileName(); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(wikiPageFullFileName); fis = new FileInputStream(rdfFileNameWithPath); InfoExtractor infoe = new InfoExtractor(fis, omemo.getFormDataNS(), omemo.getFormDataOntLang()); infoe.writePage(getWorkDir(context), owpn, Omemo.checksWikiPageName); fis.close(); fos.close(); } catch (Exception e) { log.error("Can not read local rdf file or can not write wiki page"); throw new PluginException("Error creating wiki pages. See logs"); } }
900,707
1
private void calculateCoverageAndSpecificity(String mainCat) throws IOException, JSONException { for (String cat : Rules.categoryTree.get(mainCat)) { for (String queryString : Rules.queries.get(cat)) { String urlEncodedQueryString = URLEncoder.encode(queryString, "UTF-8"); URL url = new URL("http://boss.yahooapis.com/ysearch/web/v1/" + urlEncodedQueryString + "?appid=" + yahoo_ap_id + "&count=4&format=json&sites=" + site); URLConnection con = url.openConnection(); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } String response = builder.toString(); JSONObject json = new JSONObject(response); JSONObject jsonObject = json.getJSONObject("ysearchresponse"); String totalhits = jsonObject.getString("totalhits"); long totalhitsLong = Long.parseLong(totalhits); QueryInfo qinfo = new QueryInfo(queryString, totalhitsLong); queryInfoMap.put(queryString, qinfo); cov.put(cat, cov.get(cat) + totalhitsLong); if (totalhitsLong == 0) { continue; } ja = jsonObject.getJSONArray("resultset_web"); for (int j = 0; j < ja.length(); j++) { JSONObject k = ja.getJSONObject(j); String dispurl = filterBold(k.getString("url")); qinfo.addUrl(dispurl); } } } calculateSpecificity(mainCat); }
public static String translate(String s, String type) { try { String result = null; URL url = new URL("http://www.excite.co.jp/world/english/"); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("before=" + URLEncoder.encode(s, "SJIS") + "&wb_lp="); out.print(type); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "SJIS")); String inputLine; while ((inputLine = in.readLine()) != null) { int textPos = inputLine.indexOf("name=\"after\""); if (textPos >= 0) { int ltrPos = inputLine.indexOf(">", textPos + 11); if (ltrPos >= 0) { int closePos = inputLine.indexOf("<", ltrPos + 1); if (closePos >= 0) { result = inputLine.substring(ltrPos + 1, closePos); break; } else { result = inputLine.substring(ltrPos + 1); break; } } } } in.close(); return result; } catch (Exception e) { e.printStackTrace(); } return null; }
900,708
1
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
private String readHtmlFile(String htmlFileName) { StringBuffer buffer = new StringBuffer(); java.net.URL url = getClass().getClassLoader().getResource("freestyleLearning/homeCore/help/" + htmlFileName); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String string = " "; while (string != null) { string = reader.readLine(); if (string != null) buffer.append(string); } } catch (Exception exc) { System.out.println(exc); } return new String(buffer); }
900,709
0
private String digest(String message) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(message.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String hpassword = hash.toString(16); return hpassword; } catch (Exception e) { } return null; }
private void getServiceReponse(String service, NameSpaceDefinition nsDefinition) throws Exception { Pattern pattern = Pattern.compile("(?i)(?:.*(xmlns(?:\\:\\w+)?=\\\"http\\:\\/\\/www\\.ivoa\\.net\\/.*" + service + "[^\\\"]*\\\").*)"); pattern = Pattern.compile(".*xmlns(?::\\w+)?=(\"[^\"]*(?i)(?:" + service + ")[^\"]*\").*"); logger.debug("read " + this.url + service); BufferedReader in = new BufferedReader(new InputStreamReader((new URL(this.url + service)).openStream())); String inputLine; BufferedWriter bfw = new BufferedWriter(new FileWriter(this.baseDirectory + service + ".xml")); boolean found = false; while ((inputLine = in.readLine()) != null) { if (!found) { Matcher m = pattern.matcher(inputLine); if (m.matches()) { nsDefinition.init("xmlns:vosi=" + m.group(1)); found = true; } } bfw.write(inputLine + "\n"); } in.close(); bfw.close(); }
900,710
0
private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } }
public String uploadZtree(ArrayList c) { try { String id = generateRandomId(); Iterator iter = c.iterator(); URL url = new URL(ZorobotSystem.props.getProperty("zoro.url") + "auplo1.jsp"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("id=" + id + "&"); StringBuffer sb = new StringBuffer(); int gg = 0; while (iter.hasNext()) { if (gg++ >= 500) break; String st = (String) iter.next(); sb.append("a="); sb.append(URLEncoder.encode(st, "UTF-8")); if (iter.hasNext() && gg < 500) sb.append("&"); } out.println(sb.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; if ((inputLine = in.readLine()) != null) { if (!inputLine.equals("OK!") && inputLine.length() > 3) { System.out.println("Not OK: " + inputLine); return "xxxxxxxxxx"; } } in.close(); return id; } catch (Exception e) { e.printStackTrace(); } return null; }
900,711
1
public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); }
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
900,712
1
public synchronized boolean copyTmpDataFile(String fpath) throws IOException { if (tmpDataOutput != null) tmpDataOutput.close(); tmpDataOutput = null; if (tmpDataFile == null) return false; File nfp = new File(fpath); if (nfp.exists()) nfp.delete(); FileInputStream src = new FileInputStream(tmpDataFile); FileOutputStream dst = new FileOutputStream(nfp); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = src.read(buffer)) != -1) dst.write(buffer, 0, bytesRead); src.close(); dst.close(); return true; }
private void processStylesheetFile() { InputStream in = null; OutputStream out = null; try { String filename; if (line.hasOption("stylesheetfile")) { filename = line.getOptionValue("stylesheetfile"); in = new FileInputStream(filename); filename = filename.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf('/') + 1); } else { ClassLoader cl = this.getClass().getClassLoader(); filename = "stylesheet.css"; in = cl.getResourceAsStream(RESOURCE_PKG + "/stylesheet.css"); } baseProperties.setProperty("stylesheetfilename", filename); File outFile = new File(outputDir, filename); if (LOG.isInfoEnabled()) { LOG.info("Processing generated file " + outFile.getAbsolutePath()); } out = new FileOutputStream(outFile); IOUtils.copy(in, out); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } }
900,713
1
public static void main(String[] args) throws Exception { String codecClassname = args[0]; Class<?> codecClass = Class.forName(codecClassname); Configuration conf = new Configuration(); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); CompressionOutputStream out = codec.createOutputStream(System.out); IOUtils.copyBytes(System.in, out, 4096, false); out.finish(); }
@Test public void testTrainingQuickprop() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
900,714
1
public void copyFile(String source_file_path, String destination_file_path) { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(source_file_path); fw = new FileWriter(destination_file_path); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(source_file_path); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { System.out.println(source_file_path + " does not exist!"); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } }
public static void copyFile(File src, File dst) throws ResourceNotFoundException, ParseErrorException, Exception { if (src.getAbsolutePath().endsWith(".vm")) { copyVMFile(src, dst.getAbsolutePath().substring(0, dst.getAbsolutePath().lastIndexOf(".vm"))); } else { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dst); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); } }
900,715
0
PathElement(String path) throws MaxError { this.path = path; if (path.startsWith("http:")) { try { url = new URL(path); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("HEAD"); valid = (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { valid = false; } } else { if (path.startsWith("jmax:")) file = new File(Registry.resolveJMaxURI(path)); else file = new File(path); valid = file.exists(); } }
public final Matrix3D<E> read(final URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("url must not be null"); } InputStream inputStream = null; try { inputStream = url.openStream(); return read(inputStream); } catch (IOException e) { throw e; } finally { MatrixIOUtils.closeQuietly(inputStream); } }
900,716
0
public String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
private void writeFile(String name, URL url) throws IOException { Location location = resourcesHome.resolve(name); InputStream input = url.openStream(); OutputStream output = location.getOutputStream(); try { byte buf[] = new byte[1024]; int read; while (true) { read = input.read(buf); if (read == -1) break; output.write(buf, 0, read); } } finally { try { input.close(); } finally { output.close(); } } }
900,717
0
public static boolean copyFile(File from, File to, byte[] buf) { if (buf == null) buf = new byte[BUFFER_SIZE]; FileInputStream from_s = null; FileOutputStream to_s = null; try { from_s = new FileInputStream(from); to_s = new FileOutputStream(to); for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf)) to_s.write(buf, 0, bytesRead); from_s.close(); from_s = null; to_s.getFD().sync(); to_s.close(); to_s = null; } catch (IOException ioe) { return false; } finally { if (from_s != null) { try { from_s.close(); } catch (IOException ioe) { } } if (to_s != null) { try { to_s.close(); } catch (IOException ioe) { } } } return true; }
private static String md5(String digest, String data) throws IOException { MessageDigest messagedigest; try { messagedigest = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } messagedigest.update(data.getBytes("ISO-8859-1")); byte[] bytes = messagedigest.digest(); StringBuilder stringbuffer = new StringBuilder(bytes.length * 2); for (int j = 0; j < bytes.length; j++) { int k = bytes[j] >>> 4 & 0x0f; stringbuffer.append(hexChars[k]); k = bytes[j] & 0x0f; stringbuffer.append(hexChars[k]); } return stringbuffer.toString(); }
900,718
1
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
public void createZip(File zipFileName, Vector<File> selected) { try { byte[] buffer = new byte[4096]; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName), 8096)); out.setLevel(Deflater.BEST_COMPRESSION); out.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < selected.size(); i++) { FileInputStream in = new FileInputStream(selected.get(i)); String file = selected.get(i).getPath(); if (file.indexOf("\\") != -1) file = file.substring(file.lastIndexOf(fs) + 1, file.length()); ZipEntry ze = new ZipEntry(file); out.putNextEntry(ze); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); selected.get(i).delete(); } out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
900,719
0
private static FacesBean.Type _createType() { try { ClassLoader cl = _getClassLoader(); URL url = cl.getResource("META-INF/faces-bean-type.properties"); if (url != null) { Properties properties = new Properties(); InputStream is = url.openStream(); try { properties.load(is); String className = (String) properties.get(UIXComponentBase.class.getName()); return (FacesBean.Type) cl.loadClass(className).newInstance(); } finally { is.close(); } } } catch (Exception e) { _LOG.severe("CANNOT_LOAD_TYPE_PROPERTIES", e); } return new FacesBean.Type(); }
public SpreadSheetFrame(FileManager owner, File file, Delimiter delim) { super(owner, file.getPath()); JPanel pane = new JPanel(new BorderLayout()); super.contentPane.add(pane); this.tableModel = new BigTableModel(file, delim); this.table = new JTable(tableModel); this.table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); this.tableModel.setTable(this.table); pane.add(new JScrollPane(this.table)); addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosed(InternalFrameEvent e) { tableModel.close(); } }); JMenu menu = new JMenu("Tools"); getJMenuBar().add(menu); menu.add(new AbstractAction("NCBI") { @Override public void actionPerformed(ActionEvent e) { try { Pattern delim = Pattern.compile("[ ]"); BufferedReader r = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("/home/lindenb/jeter.txt.gz")))); String line = null; URL url = new URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write("db=snp&retmode=xml"); while ((line = r.readLine()) != null) { String tokens[] = delim.split(line, 2); if (!tokens[0].startsWith("rs")) continue; wr.write("&id=" + tokens[0].substring(2).trim()); } wr.flush(); r.close(); InputStream in = conn.getInputStream(); IOUtils.copyTo(in, System.err); in.close(); wr.close(); } catch (IOException err) { err.printStackTrace(); } } }); }
900,720
1
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } }
public static void main(String[] argv) throws IOException { int i; for (i = 0; i < argv.length; i++) { if (argv[i].charAt(0) != '-') break; ++i; switch(argv[i - 1].charAt(1)) { case 'b': try { flag_predict_probability = (atoi(argv[i]) != 0); } catch (NumberFormatException e) { exit_with_help(); } break; default: System.err.printf("unknown option: -%d%n", argv[i - 1].charAt(1)); exit_with_help(); break; } } if (i >= argv.length || argv.length <= i + 2) { exit_with_help(); } BufferedReader reader = null; Writer writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(argv[i]), Linear.FILE_CHARSET)); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(argv[i + 2]), Linear.FILE_CHARSET)); Model model = Linear.loadModel(new File(argv[i + 1])); doPredict(reader, writer, model); } finally { closeQuietly(reader); closeQuietly(writer); } }
900,721
0
public static byte[] readResource(Class owningClass, String resourceName) { final URL url = getResourceUrl(owningClass, resourceName); if (null == url) { throw new MissingResourceException(owningClass.toString() + " key '" + resourceName + "'", owningClass.toString(), resourceName); } LOG.info("Loading resource '" + url.toExternalForm() + "' " + "from " + owningClass); final InputStream inputStream; try { inputStream = url.openStream(); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } return outputStream.toByteArray(); }
private void request() { try { connection = (HttpURLConnection) new URL(url).openConnection(); if (isCometConnection) { connection.setReadTimeout(0); } else { connection.setReadTimeout(30000); } connection.setInstanceFollowRedirects(false); connection.setDoInput(true); connection.setRequestMethod(method); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 GTB5"); if ("post".equalsIgnoreCase(method)) { connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } if (user != null) { String auth = user + ":" + (password != null ? password : ""); String base64Auth = HttpRequest.Base64.byteArrayToBase64(auth.getBytes()); connection.setRequestProperty("Authorization", "Basic " + base64Auth); } for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); connection.setRequestProperty(key, (String) headers.get(key)); } connection.setUseCaches(false); if (checkAbort()) return; if ("post".equalsIgnoreCase(method)) { DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); activeOS = dos; if (content != null) { dos.writeBytes(content); } if (checkAbort()) return; dos.flush(); dos.close(); activeOS = null; } if (checkAbort()) return; InputStream is = null; try { is = connection.getInputStream(); } catch (IOException e) { if (checkAbort()) return; readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection = null; readyState = 0; return; } activeIS = is; if (readyState < 2) { readyState = 2; status = connection.getResponseCode(); statusText = connection.getResponseMessage(); if (onreadystatechange != null) { onreadystatechange.onSent(); } } receiving = initializeReceivingMonitor(); ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); byte[] buffer = new byte[10240]; int read; while (!toAbort && (read = is.read(buffer)) != -1) { if (checkAbort()) return; if (readyState != 3) { readyState = 3; if (onreadystatechange != null) { onreadystatechange.onReceiving(); } } boolean received = false; if (receiving != null) { received = receiving.receiving(baos, buffer, 0, read); } if (!received) { baos.write(buffer, 0, read); } } if (checkAbort()) return; is.close(); activeIS = null; responseText = null; String type = connection.getHeaderField("Content-Type"); if (type != null) { String charset = null; String lowerType = type.toLowerCase(); int idx = lowerType.indexOf("charset="); if (idx != -1) { charset = type.substring(idx + 8); } else { idx = lowerType.indexOf("/xml"); if (idx != -1) { String tmp = baos.toString(); Matcher matcher = Pattern.compile("<\\?.*encoding\\s*=\\s*[\'\"]([^'\"]*)[\'\"].*\\?>", Pattern.MULTILINE).matcher(tmp); if (matcher.find()) { charset = matcher.group(1); } else { responseText = tmp; } } else { idx = lowerType.indexOf("html"); if (idx != -1) { String tmp = baos.toString(); Matcher matcher = Pattern.compile("<meta.*content\\s*=\\s*[\'\"][^'\"]*charset\\s*=\\s*([^'\"]*)\\s*[\'\"].*>", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE).matcher(tmp); if (matcher.find()) { charset = matcher.group(1); } else { responseText = tmp; } } } } if (charset != null) { try { responseText = baos.toString(charset); } catch (UnsupportedEncodingException e) { } } } if (responseText == null) { try { responseText = baos.toString("iso-8859-1"); } catch (UnsupportedEncodingException e) { responseText = baos.toString(); } } readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection.disconnect(); readyState = 0; } catch (Exception e) { if (checkAbort()) return; e.printStackTrace(); readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection = null; readyState = 0; } }
900,722
1
public void test3() throws FileNotFoundException, IOException { Decoder decoder1 = new MP3Decoder(new FileInputStream("/home/marc/tmp/test1.mp3")); Decoder decoder2 = new OggDecoder(new FileInputStream("/home/marc/tmp/test1.ogg")); FileOutputStream out = new FileOutputStream("/home/marc/tmp/test.pipe"); IOUtils.copy(decoder1, out); IOUtils.copy(decoder2, out); }
public void invoke() throws IOException { String[] command = new String[files.length + options.length + 2]; command[0] = chmod; System.arraycopy(options, 0, command, 1, options.length); command[1 + options.length] = perms; for (int i = 0; i < files.length; i++) { File file = files[i]; command[2 + options.length + i] = file.getAbsolutePath(); } Process p = Runtime.getRuntime().exec(command); try { p.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (p.exitValue() != 0) { StringWriter writer = new StringWriter(); IOUtils.copy(p.getErrorStream(), writer); throw new IOException("Unable to chmod files: " + writer.toString()); } }
900,723
0
public void load(String filename) throws VisbardException { String defaultFilename = VisbardMain.getSettingsDir() + File.separator + DEFAULT_SETTINGS_FILE; File defaultFile = new File(defaultFilename); InputStream settingsInStreamFromFile = null; try { sLogger.info("Loading settings from : " + defaultFilename); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (FileNotFoundException fnf) { sLogger.info("Unable to load custom settings from user's settings directory (" + fnf.getMessage() + "); reverting to default settings"); try { InputStream settingsInStreamFromJar = VisbardMain.class.getClassLoader().getResourceAsStream(filename); FileOutputStream settingsOutStream = new FileOutputStream(defaultFile); int c; while ((c = settingsInStreamFromJar.read()) != -1) settingsOutStream.write(c); settingsInStreamFromJar.close(); settingsOutStream.close(); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (IOException ioe) { sLogger.warn("Unable to copy default settings to user's settings directory (" + ioe.getMessage() + "); using default settings from ViSBARD distribution package"); settingsInStreamFromFile = VisbardMain.class.getClassLoader().getResourceAsStream(filename); } } this.processSettingsFile(settingsInStreamFromFile, filename); }
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
900,724
1
public static boolean filecopy(final File source, final File target) { boolean out = false; if (source.isDirectory() || !source.exists() || target.isDirectory() || source.equals(target)) return false; try { target.getParentFile().mkdirs(); target.createNewFile(); FileChannel sourceChannel = new FileInputStream(source).getChannel(); try { FileChannel targetChannel = new FileOutputStream(target).getChannel(); try { targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); out = true; } finally { targetChannel.close(); } } finally { sourceChannel.close(); } } catch (IOException e) { out = false; } return out; }
public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); }
900,725
1
public static void reset() throws Exception { Session session = DataStaticService.getHibernateSessionFactory().openSession(); try { Connection connection = session.connection(); try { Statement statement = connection.createStatement(); try { statement.executeUpdate("delete from Post"); connection.commit(); } finally { statement.close(); } } catch (HibernateException e) { connection.rollback(); throw new Exception(e); } catch (SQLException e) { connection.rollback(); throw new Exception(e); } } catch (SQLException e) { throw new Exception(e); } finally { session.close(); } }
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente = '" + id + "'"; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
900,726
1
public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
900,727
1
public void testCryptHash() { Log.v("Test", "[*] testCryptHash()"); String testStr = "Hash me"; byte messageDigest[]; MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest.digest(testStr.getBytes()); digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest = null; digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(imei.getBytes()); messageDigest = digest.digest(); hashedImei = this.toHex(messageDigest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
public static String encrypt(String message) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(message.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return null; } }
900,728
1
protected InputStream callApiGet(String apiUrl, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.connect(); if (request.getResponseCode() != expected) { throw new BingMapsException(convertStreamToString(request.getErrorStream())); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingMapsException(e); } }
public static String getTextFileFromURL(String urlName) { try { StringBuffer textFile = new StringBuffer(""); String line = null; URL url = new URL(urlName); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) textFile = textFile.append(line + "\n"); reader.close(); return textFile.toString(); } catch (Exception e) { Debug.signal(Debug.ERROR, null, "Failed to open " + urlName + ", exception " + e); return null; } }
900,729
0
private URLConnection openConnection(final URL url) throws IOException { try { return (URLConnection) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return url.openConnection(); } }); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } }
public static String encryptePassword(String md5key, String passwordAccount, String encryptedPassword, int passwdenc) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(Constants.ALGORITHM); switch(passwdenc) { case 1: md.update((md5key + encryptedPassword).getBytes("8859_1")); break; case 2: md.update((encryptedPassword + md5key).getBytes("8859_1")); break; default: return null; } return new String(md.digest()); }
900,730
0
public static void main(String[] args) throws IOException { MSPack pack = new MSPack(new FileInputStream(args[0])); String[] files = pack.getFileNames(); for (int i = 0; i < files.length; i++) System.out.println(i + ": " + files[i] + ": " + pack.getLengths()[i]); System.out.println("Writing " + files[files.length - 1]); InputStream is = pack.getInputStream(files.length - 1); OutputStream os = new FileOutputStream(files[files.length - 1]); int n; byte[] buf = new byte[4096]; while ((n = is.read(buf)) != -1) os.write(buf, 0, n); os.close(); is.close(); }
public Usuario insertUsuario(IUsuario usuario) throws SQLException { Connection conn = null; String insert = "insert into Usuario (idusuario, nome, email, telefone, cpf, login, senha) " + "values " + "(nextval('seq_usuario'), '" + usuario.getNome() + "', '" + usuario.getEmail() + "', " + "'" + usuario.getTelefone() + "', '" + usuario.getCpf() + "', '" + usuario.getLogin() + "', '" + usuario.getSenha() + "')"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_usuario"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { usuario.setIdUsuario(rs.getInt("last_value")); } if (usuario instanceof Requerente) { RequerenteDAO requerenteDAO = new RequerenteDAO(); requerenteDAO.insertRequerente((Requerente) usuario, conn); } else if (usuario instanceof RecursoHumano) { RecursoHumanoDAO recursoHumanoDAO = new RecursoHumanoDAO(); recursoHumanoDAO.insertRecursoHumano((RecursoHumano) usuario, conn); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; }
900,731
1
public static void importDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = output + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); createTablesDB(); } else G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); long tiempoInicio = System.currentTimeMillis(); String directoryPath = input + File.separator; File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(input + File.separator + G.imagesName); if (!fileXML.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero XML", "Error", JOptionPane.ERROR_MESSAGE); } else { SAXBuilder builder = new SAXBuilder(false); Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); List<Element> globalLanguages = root.getChild("languages").getChildren("language"); Iterator<Element> langsI = globalLanguages.iterator(); HashMap<String, Integer> languageIDs = new HashMap<String, Integer>(); HashMap<String, Integer> typeIDs = new HashMap<String, Integer>(); Element e; int i = 0; int contTypes = 0; int contImages = 0; while (langsI.hasNext()) { e = langsI.next(); languageIDs.put(e.getText(), i); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO language (id,name) VALUES (?,?)"); stmt.setInt(1, i); stmt.setString(2, e.getText()); stmt.executeUpdate(); stmt.close(); i++; } G.conn.setAutoCommit(false); while (j.hasNext()) { Element image = (Element) j.next(); String id = image.getAttributeValue("id"); List languages = image.getChildren("language"); Iterator k = languages.iterator(); if (exists(list, id)) { String pathSrc = directoryPath.concat(id); String pathDst = output + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = output + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.toString()); } while (k.hasNext()) { Element languageElement = (Element) k.next(); String language = languageElement.getAttributeValue("id"); List words = languageElement.getChildren("word"); Iterator l = words.iterator(); while (l.hasNext()) { Element wordElement = (Element) l.next(); String type = wordElement.getAttributeValue("type"); if (!typeIDs.containsKey(type)) { typeIDs.put(type, contTypes); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO type (id,name) VALUES (?,?)"); stmt.setInt(1, contTypes); stmt.setString(2, type); stmt.executeUpdate(); stmt.close(); contTypes++; } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, wordElement.getText().toLowerCase()); stmt.setInt(2, languageIDs.get(language)); stmt.setInt(3, typeIDs.get(type)); stmt.setString(4, id); stmt.setString(5, id); stmt.executeUpdate(); stmt.close(); if (contImages == 5000) { G.conn.commit(); contImages = 0; } else contImages++; } } } else { } } G.conn.setAutoCommit(true); G.conn.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } }
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
900,732
1
protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } }
public static long checksum(IFile file) throws IOException { InputStream contents; try { contents = file.getContents(); } catch (CoreException e) { throw new CausedIOException("Failed to calculate checksum.", e); } CheckedInputStream in = new CheckedInputStream(contents, new Adler32()); try { IOUtils.copy(in, new NullOutputStream()); } catch (IOException e) { throw new CausedIOException("Failed to calculate checksum.", e); } finally { IOUtils.closeQuietly(in); } return in.getChecksum().getValue(); }
900,733
1
public DialogSongList(JFrame frame) { super(frame, "Menu_SongList", "songList"); setMinimumSize(new Dimension(400, 200)); JPanel panel, spanel; Container contentPane; (contentPane = getContentPane()).add(songSelector = new SongSelector(configKey, null, true)); songSelector.setSelectionAction(new Runnable() { public void run() { final Item<URL, MidiFileInfo> item = songSelector.getSelectedInfo(); if (item != null) { try { selection = new File(item.getKey().toURI()); author.setEnabled(true); title.setEnabled(true); difficulty.setEnabled(true); save.setEnabled(true); final MidiFileInfo info = item.getValue(); author.setText(info.getAuthor()); title.setText(info.getTitle()); Util.selectKey(difficulty, info.getDifficulty()); return; } catch (Exception e) { } } selection = null; author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); } }); contentPane.add(panel = new JPanel(), BorderLayout.SOUTH); panel.setLayout(new BorderLayout()); JScrollPane scrollPane; panel.add(scrollPane = new JScrollPane(spanel = new JPanel()), BorderLayout.NORTH); scrollPane.setPreferredSize(new Dimension(0, 60)); Util.addLabeledComponent(spanel, "Lbl_Author", author = new JTextField(10)); Util.addLabeledComponent(spanel, "Lbl_Title", title = new JTextField(14)); Util.addLabeledComponent(spanel, "Lbl_Difficulty", difficulty = new JComboBox()); difficulty.addItem(new Item<Byte, String>((byte) -1, "")); for (Map.Entry<Byte, String> entry : SongSelector.DIFFICULTIES.entrySet()) { final String value = entry.getValue(); difficulty.addItem(new Item<Byte, String>(entry.getKey(), Util.getMsg(value, value), value)); } spanel.add(save = new JButton()); Util.updateButtonText(save, "Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File selected = MidiSong.setMidiFileInfo(selection, author.getText(), title.getText(), getAsByte(difficulty)); SongSelector.refresh(); try { songSelector.setSelected(selected == null ? null : selected.toURI().toURL()); } catch (MalformedURLException ex) { } } }); author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); JButton button; panel.add(spanel = new JPanel(), BorderLayout.WEST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Import"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Delete"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (KeyboardHero.confirm(Util.getMsg("Que_SureToDelete"))) { try { new File(songSelector.getSelectedFile().toURI()).delete(); } catch (Exception ex) { Util.error(Util.getMsg("Err_CouldntDeleteFile"), ex.toString()); } SongSelector.refresh(); } } }); panel.add(spanel = new JPanel(), BorderLayout.CENTER); spanel.setLayout(new FlowLayout()); spanel.add(button = new JButton()); Util.updateButtonText(button, "Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { close(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Play"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.newGame(songSelector.getSelectedFile()); close(); } }); panel.add(spanel = new JPanel(), BorderLayout.EAST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Refresh"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SongSelector.refresh(); } }); getRootPane().setDefaultButton(button); instance = this; }
public void putFile(CompoundName file, FileInputStream fileInput) throws IOException { File fullDir = new File(REMOTE_BASE_DIR.getCanonicalPath()); for (int i = 0; i < file.size() - 1; i++) fullDir = new File(fullDir, file.get(i)); fullDir.mkdirs(); File outputFile = new File(fullDir, file.get(file.size() - 1)); FileOutputStream outStream = new FileOutputStream(outputFile); for (int byteIn = fileInput.read(); byteIn != -1; byteIn = fileInput.read()) outStream.write(byteIn); fileInput.close(); outStream.close(); }
900,734
0
private void checkUrl(URL url) throws IOException { File urlFile = new File(url.getFile()); assertEquals(file.getCanonicalPath(), urlFile.getCanonicalPath()); System.out.println("Using url " + url); InputStream openStream = url.openStream(); assertNotNull(openStream); }
public RobotList<Location> sort_incr_Location(RobotList<Location> list, String field) { int length = list.size(); Index_value[] enemy_dist = new Index_value[length]; Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, distance(cur_loc, list.get(i))); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (enemy_dist[i].value > enemy_dist[i + 1].value) { Index_value a = enemy_dist[i]; enemy_dist[i] = enemy_dist[i + 1]; enemy_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Location> new_location_list = new RobotList<Location>(Location.class); for (int i = 0; i < length; i++) { new_location_list.addLast(list.get(enemy_dist[i].index)); } return new_location_list; }
900,735
0
public static void uploadAsync(final ArrayList<RecordedGeoPoint> recordedGeoPoints) { new Thread(new Runnable() { @Override public void run() { try { if (!Util.isSufficienDataForUpload(recordedGeoPoints)) return; final InputStream gpxInputStream = new ByteArrayInputStream(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes()); final HttpClient httpClient = new DefaultHttpClient(); final HttpPost request = new HttpPost(UPLOADSCRIPT_URL); final MultipartEntity requestEntity = new MultipartEntity(); requestEntity.addPart("gpxfile", new InputStreamBody(gpxInputStream, "" + System.currentTimeMillis() + ".gpx")); httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false); request.setEntity(requestEntity); final HttpResponse response = httpClient.execute(request); final int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { logger.error("GPXUploader", "status != HttpStatus.SC_OK"); } else { final Reader r = new InputStreamReader(new BufferedInputStream(response.getEntity().getContent())); final char[] buf = new char[8 * 1024]; int read; final StringBuilder sb = new StringBuilder(); while ((read = r.read(buf)) != -1) sb.append(buf, 0, read); logger.debug("GPXUploader", "Response: " + sb.toString()); } } catch (final Exception e) { } } }).start(); }
private static boolean genCustomerLocationsFileAndCustomerIndexFile(String completePath, String masterFile, String CustLocationsFileName, String CustIndexFileName) { try { TIntObjectHashMap CustInfoHash = new TIntObjectHashMap(480189, 1); File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC = new FileInputStream(inFile).getChannel(); File outFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel outC1 = new FileOutputStream(outFile1, true).getChannel(); File outFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel outC2 = new FileOutputStream(outFile2, true).getChannel(); int fileSize = (int) inC.size(); int totalNoDataRows = fileSize / 7; for (int i = 1; i <= totalNoDataRows; i++) { ByteBuffer mappedBuffer = ByteBuffer.allocate(7); inC.read(mappedBuffer); mappedBuffer.position(0); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); mappedBuffer.clear(); if (CustInfoHash.containsKey(customer)) { TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); locations.add(i); CustInfoHash.put(customer, locations); } else { TIntArrayList locations = new TIntArrayList(); locations.add(i); CustInfoHash.put(customer, locations); } } int[] customers = CustInfoHash.keys(); Arrays.sort(customers); int count = 1; for (int i = 0; i < customers.length; i++) { int customer = customers[i]; TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); int noRatingsForCust = locations.size(); ByteBuffer outBuf1 = ByteBuffer.allocate(12); outBuf1.putInt(customer); outBuf1.putInt(count); outBuf1.putInt(count + noRatingsForCust - 1); outBuf1.flip(); outC1.write(outBuf1); count += noRatingsForCust; for (int j = 0; j < locations.size(); j++) { ByteBuffer outBuf2 = ByteBuffer.allocate(4); outBuf2.putInt(locations.get(j)); outBuf2.flip(); outC2.write(outBuf2); } } inC.close(); outC1.close(); outC2.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
900,736
0
public void copyHashAllFilesToDirectory(String baseDirStr, Hashtable newNamesTable, String destDirStr) throws Exception { if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(baseDirStr); if (null == newNamesTable) { newNamesTable = new Hashtable(); } BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if ((baseDir.exists()) && (baseDir.isDirectory())) { if (!newNamesTable.isEmpty()) { Enumeration enumFiles = newNamesTable.keys(); while (enumFiles.hasMoreElements()) { String newName = (String) enumFiles.nextElement(); String oldPathName = (String) newNamesTable.get(newName); if ((newName != null) && (!"".equals(newName)) && (oldPathName != null) && (!"".equals(oldPathName))) { String newPathFileName = destDirStr + sep + newName; String oldPathFileName = baseDirStr + sep + oldPathName; if (oldPathName.startsWith(sep)) { oldPathFileName = baseDirStr + oldPathName; } File f = new File(oldPathFileName); if ((f.exists()) && (f.isFile())) { in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); } out.flush(); in.close(); out.close(); } else { } } } } else { } } else { throw new Exception("Base (baseDirStr) dir not exist !"); } }
public static boolean downloadFile(String url, String destination) throws Exception { BufferedInputStream bi = null; BufferedOutputStream bo = null; File destfile; java.net.URL fileurl; fileurl = new java.net.URL(url); bi = new BufferedInputStream(fileurl.openStream()); destfile = new File(destination); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); int readedbyte; while ((readedbyte = bi.read()) != -1) { bo.write(readedbyte); } bi.close(); bo.close(); return true; }
900,737
0
public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new MyException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; }
900,738
1
public static void copyFile(String original, String destination) throws Exception { File original_file = new File(original); File destination_file = new File(destination); if (!original_file.exists()) throw new Exception("File with path " + original + " does not exist."); if (destination_file.exists()) throw new Exception("File with path " + destination + " already exists."); FileReader in = new FileReader(original_file); FileWriter out = new FileWriter(destination_file); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
private void sendBinaryFile(File file) throws IOException, CVSException { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); if (m_bCompressFiles) { GZIPOutputStream gzipOut = null; InputStream gzipIn = null; File gzipFile = null; try { gzipFile = File.createTempFile("javacvs", "tmp"); gzipOut = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gzipFile))); int b; while ((b = in.read()) != -1) gzipOut.write((byte) b); gzipOut.close(); long gzipLength = gzipFile.length(); sendLine("z" + Long.toString(gzipLength)); gzipIn = new BufferedInputStream(new FileInputStream(gzipFile)); for (long i = 0; i < gzipLength; i++) { b = gzipIn.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } finally { if (gzipOut != null) gzipOut.close(); if (gzipIn != null) gzipIn.close(); if (gzipFile != null) gzipFile.delete(); } } else { long nLength = file.length(); sendLine(Long.toString(nLength)); for (long i = 0; i < nLength; i++) { int b = in.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
900,739
1
private static void recurseFiles(File root, File file, TarArchiveOutputStream taos, boolean absolute) throws IOException { if (file.isDirectory()) { File[] files = file.listFiles(); for (File file2 : files) { recurseFiles(root, file2, taos, absolute); } } else if ((!file.getName().endsWith(".tar")) && (!file.getName().endsWith(".TAR"))) { String filename = null; if (absolute) { filename = file.getAbsolutePath().substring(root.getAbsolutePath().length()); } else { filename = file.getName(); } TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } }
protected void zipDirectory(File dir, File zipfile) throws IOException, IllegalArgumentException { if (!dir.isDirectory()) throw new IllegalArgumentException("Compress: not a directory: " + dir); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytes_read; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); } out.close(); }
900,740
0
private String signMethod() { String str = API.SHARED_SECRET; Vector<String> v = new Vector<String>(parameters.keySet()); Collections.sort(v); for (String key : v) { str += key + parameters.get(key); } MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); m.update(str.getBytes(), 0, str.length()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException e) { return null; } }
public static boolean processUrl(String urlPath, UrlLineHandler handler) { boolean ret = true; URL url; InputStream in = null; BufferedReader bin = null; try { url = new URL(urlPath); in = url.openStream(); bin = new BufferedReader(new InputStreamReader(in)); String line; while ((line = bin.readLine()) != null) { if (!handler.process(line)) break; } } catch (IOException e) { ret = false; } finally { safelyClose(bin, in); } return ret; }
900,741
0
private HashMap<String, GCVote> getVotes(ArrayList<String> waypoints, boolean blnSleepBeforeDownload) { if (blnSleepBeforeDownload) { try { Thread.sleep(PACKET_SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } final String strWaypoints = this.join(waypoints, ","); try { String strParameters = URLEncoder.encode("waypoints", "UTF-8") + "=" + URLEncoder.encode(strWaypoints, "UTF-8"); if (this.mstrUsername.length() > 0) { strParameters += "&" + URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(this.mstrUsername, "UTF-8"); if (this.mstrPassword.length() > 0) { strParameters += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(this.mstrPassword, "UTF-8"); } } final URL url = new URL(BASE_URL_GET_VOTE); URLConnection conn = url.openConnection(); conn.setDoOutput(true); final OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream()); osw.write(strParameters); osw.flush(); final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(false); saxParserFactory.setNamespaceAware(true); final SAXParser saxParser = saxParserFactory.newSAXParser(); final XMLReader xmlReader = saxParser.getXMLReader(); final GCVoteHandler gcVoteHandler = new GCVoteHandler(); xmlReader.setContentHandler(gcVoteHandler); xmlReader.parse(new InputSource(new InputStreamReader(conn.getInputStream()))); return gcVoteHandler.getVotes(); } catch (Exception e) { e.printStackTrace(); return null; } }
public static void main(String[] args) { try { { byte[] bytes1 = { (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; byte[] bytes2 = { (byte) 99, (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; System.out.println("Bytes 2,2,3,0,9 as Base64: " + encodeBytes(bytes1)); System.out.println("Bytes 2,2,3,0,9 w/ offset: " + encodeBytes(bytes2, 1, bytes2.length - 1)); byte[] dbytes = decode(encodeBytes(bytes1)); System.out.print(encodeBytes(bytes1) + " decoded: "); for (int i = 0; i < dbytes.length; i++) System.out.print(dbytes[i] + (i < dbytes.length - 1 ? "," : "\n")); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif.b64"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); byte[] bytes = new byte[0]; int b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[bytes.length + 1]; System.arraycopy(bytes, 0, temp, 0, bytes.length); temp[bytes.length] = (byte) b; bytes = temp; } b64is.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon(bytes); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif.b64", iicon, 0); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif_out"); fos.write(bytes); fos.close(); fis = new java.io.FileInputStream("test.gif_out"); b64is = new Base64.InputStream(fis, ENCODE); byte[] ebytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[ebytes.length + 1]; System.arraycopy(ebytes, 0, temp, 0, ebytes.length); temp[ebytes.length] = (byte) b; ebytes = temp; } b64is.close(); String s = new String(ebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif_out"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.setVisible(true); fos = new java.io.FileOutputStream("test.gif.b64_out"); fos.write(ebytes); fis = new java.io.FileInputStream("test.gif.b64_out"); b64is = new Base64.InputStream(fis, DECODE); byte[] edbytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[edbytes.length + 1]; System.arraycopy(edbytes, 0, temp, 0, edbytes.length); temp[edbytes.length] = (byte) b; edbytes = temp; } b64is.close(); iicon = new javax.swing.ImageIcon(edbytes); jlabel = new javax.swing.JLabel("Read from test.gif.b64_out", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif_out"); byte[] rbytes = new byte[0]; int b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rbytes.length + 1]; System.arraycopy(rbytes, 0, temp, 0, rbytes.length); temp[rbytes.length] = (byte) b; rbytes = temp; } fis.close(); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif.b64_out2"); Base64.OutputStream b64os = new Base64.OutputStream(fos, ENCODE); b64os.write(rbytes); b64os.close(); fis = new java.io.FileInputStream("test.gif.b64_out2"); byte[] rebytes = new byte[0]; b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rebytes.length + 1]; System.arraycopy(rebytes, 0, temp, 0, rebytes.length); temp[rebytes.length] = (byte) b; rebytes = temp; } fis.close(); String s = new String(rebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif.b64_out2"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.setVisible(true); fos = new java.io.FileOutputStream("test.gif_out2"); b64os = new Base64.OutputStream(fos, DECODE); b64os.write(rebytes); b64os.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon("test.gif_out2"); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif_out2", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); } { java.io.FileInputStream fis = new java.io.FileInputStream("D:\\temp\\testencoding.txt"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); java.io.FileOutputStream fos = new java.io.FileOutputStream("D:\\temp\\file.zip"); int b; while ((b = b64is.read()) >= 0) fos.write(b); fos.close(); b64is.close(); } } catch (Exception e) { e.printStackTrace(); } }
900,742
0
private ByteBuffer readProgram(URL url) throws IOException { StringBuilder program = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { program.append(line).append("\n"); } } finally { if (in != null) in.close(); } ByteBuffer buffer = BufferUtils.createByteBuffer(program.length()); for (int i = 0; i < program.length(); i++) { buffer.put((byte) (program.charAt(i) & 0xFF)); } buffer.flip(); return buffer; }
public void init() { this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); try { if (memeId < 0) { } else { conurl = new URL(ServerURL + "?meme_id=" + memeId); java.io.InputStream xmlstr = conurl.openStream(); this.removeAllWorkSheets(); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_EXPLICIT); this.setStringEncodingMode(WorkBookHandle.STRING_ENCODING_UNICODE); this.setDupeStringMode(WorkBookHandle.SHAREDUPES); ExtenXLS.parseNBind(this, xmlstr); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); } } catch (Exception ex) { throw new WorkBookException("Error while connecting to: " + ServerURL + ":" + ex.toString(), WorkBookException.RUNTIME_ERROR); } }
900,743
0
public static void copy(String srcFileName, String destFileName) throws IOException { if (srcFileName == null) { throw new IllegalArgumentException("srcFileName is null"); } if (destFileName == null) { throw new IllegalArgumentException("destFileName is null"); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFileName).getChannel(); dest = new FileOutputStream(destFileName).getChannel(); long n = src.size(); MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n); dest.write(buf); } finally { if (dest != null) { try { dest.close(); } catch (IOException e1) { } } if (src != null) { try { src.close(); } catch (IOException e1) { } } } }
public String parseInOneLine() throws Exception { BufferedReader br = null; InputStream httpStream = null; if (url.startsWith("http")) { URL fileURL = new URL(url); URLConnection urlConnection = fileURL.openConnection(); httpStream = urlConnection.getInputStream(); br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); } else { br = new BufferedReader(new FileReader(url)); } StringBuffer sb = new StringBuffer(); StringBuffer sbAllDoc = new StringBuffer(); String ligne = null; boolean get = false; while ((ligne = br.readLine()) != null) { log.debug(ligne); sbAllDoc.append(ligne + " "); if (ligne.indexOf("<table") != -1) { get = true; } if (get) { sb.append(ligne + " "); } if (ligne.indexOf("</table") != -1 || ligne.indexOf("</tr></font><center><a href='affichaire.php") != -1 || ligne.indexOf("</font><center><a href='afficheregion.php") != -1) { get = false; break; } } oneLine = sb.toString(); allDocInOneLine = sbAllDoc.toString(); if (oneLine.indexOf("</table") != -1) { tableTab = new TableTag(oneLine.substring(oneLine.indexOf(">") + 1, oneLine.indexOf("</table"))); } else if (oneLine.indexOf("</font><center><a href='affichaire") != -1) { tableTab = new TableTag(oneLine.substring(oneLine.indexOf(">") + 1, oneLine.indexOf("</font><center><a href='affichaire"))); } else if (oneLine.indexOf("</font><center><a href='afficheregion.php") != -1) { tableTab = new TableTag(oneLine.substring(oneLine.indexOf(">") + 1, oneLine.indexOf("</font><center><a href='afficheregion.php"))); } else { log.error("La fin du fichier HTML n'a pas ete trouvee, ca va merder..."); } br.close(); if (httpStream != null) { httpStream.close(); } return allDocInOneLine; }
900,744
1
protected static boolean copyFile(File src, File dest) { try { if (!dest.exists()) { dest.createNewFile(); } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); byte[] temp = new byte[1024 * 8]; int readSize = 0; do { readSize = fis.read(temp); fos.write(temp, 0, readSize); } while (readSize == temp.length); temp = null; fis.close(); fos.flush(); fos.close(); } catch (Exception e) { return false; } return true; }
public static void main(String[] args) throws Exception { String uri = args[0]; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); FSDataInputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 4096, false); in.seek(0); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } }
900,745
1
public static void translateTableAttributes(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table_att", nsDefinition); String filename = baseDir + "table_att.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + "_att.xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + "_att.json", baseDir + tableName + "_att.xsl"); }
@Override public LispObject execute(LispObject first, LispObject second) throws ConditionThrowable { Pathname zipfilePathname = coerceToPathname(first); byte[] buffer = new byte[4096]; try { String zipfileNamestring = zipfilePathname.getNamestring(); if (zipfileNamestring == null) return error(new SimpleError("Pathname has no namestring: " + zipfilePathname.writeToString())); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfileNamestring)); LispObject list = second; while (list != NIL) { Pathname pathname = coerceToPathname(list.CAR()); String namestring = pathname.getNamestring(); if (namestring == null) { out.close(); File zipfile = new File(zipfileNamestring); zipfile.delete(); return error(new SimpleError("Pathname has no namestring: " + pathname.writeToString())); } File file = new File(namestring); FileInputStream in = new FileInputStream(file); ZipEntry entry = new ZipEntry(file.getName()); out.putNextEntry(entry); int n; while ((n = in.read(buffer)) > 0) out.write(buffer, 0, n); out.closeEntry(); in.close(); list = list.CDR(); } out.close(); } catch (IOException e) { return error(new LispError(e.getMessage())); } return zipfilePathname; }
900,746
0
public static void connectServer() { if (ftpClient == null) { int reply; try { setArg(configFile); ftpClient = new FTPClient(); ftpClient.setDefaultPort(port); ftpClient.configure(getFtpConfig()); ftpClient.connect(ip); ftpClient.login(username, password); ftpClient.setDefaultPort(port); System.out.print(ftpClient.getReplyString()); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); } } catch (Exception e) { System.err.println("��¼ftp��������" + ip + "��ʧ��"); e.printStackTrace(); } } }
public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { sourceChannel.close(); destinationChannel.close(); } }
900,747
1
public static void concatenateOutput(File[] inputFiles, File outputFile) { int numberOfInputFiles = inputFiles.length; byte lf = (byte) '\n'; try { FileOutputStream fos = new FileOutputStream(outputFile); FileChannel outfc = fos.getChannel(); System.out.println("Processing " + inputFiles[0].getPath()); FileInputStream fis = new FileInputStream(inputFiles[0]); FileChannel infc = fis.getChannel(); int bufferCapacity = 100000; ByteBuffer bb = ByteBuffer.allocate(bufferCapacity); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); for (int f = 1; f < numberOfInputFiles; f++) { System.out.println("Processing " + inputFiles[f].getPath()); fis = new FileInputStream(inputFiles[f]); infc = fis.getChannel(); bb.clear(); int bytesread = infc.read(bb); bb.flip(); byte b = bb.get(); while (b != lf) { b = bb.get(); } outfc.write(bb); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); } outfc.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } }
@Override protected ActionForward executeAction(ActionMapping mapping, ActionForm form, User user, HttpServletRequest request, HttpServletResponse response) throws Exception { long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L); String attributeIdentifier = request.getParameter("identifier"); if (resourceId != 0L && StringUtils.hasText(attributeIdentifier)) { try { BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, attributeIdentifier, user); response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"'); String contentType = binaryAttribute.getContentType(); if (contentType != null) { if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } } else { response.setContentType("application/octet-stream"); } IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream()); return null; } catch (DataRetrievalFailureException e) { addGlobalError(request, "errors.notFound"); } catch (Exception e) { addGlobalError(request, e); } } return mapping.getInputForward(); }
900,748
1
protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; }
public static String getWebpage(String url) { String content = ""; if (!url.trim().toLowerCase().startsWith("http://")) { url = "http://" + url; } try { BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line; while ((line = reader.readLine()) != null) { content += line + "\n"; } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e2) { e2.printStackTrace(); } return content; }
900,749
1
public static boolean update(ItemNotaFiscal objINF) { final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; int result; CelulaFinanceira objCF = null; if (c == null) { return false; } if (objINF == null) { return false; } try { c.setAutoCommit(false); String sql = ""; sql = "update item_nota_fiscal " + "set id_item_pedido = ? " + "where id_item_nota_fiscal = ?"; pst = c.prepareStatement(sql); pst.setInt(1, objINF.getItemPedido().getCodigo()); pst.setInt(2, objINF.getCodigo()); result = pst.executeUpdate(); if (result > 0) { if (objINF.getItemPedido().getCelulaFinanceira() != null) { objCF = objINF.getItemPedido().getCelulaFinanceira(); objCF.atualizaGastoReal(objINF.getSubtotal()); if (CelulaFinanceiraDAO.update(objCF)) { } } } c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final Exception e1) { System.out.println("[ItemNotaFiscalDAO.update.rollback] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[ItemNotaFiscalDAO.update.insert] Erro ao inserir -> " + e.getMessage()); result = 0; } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
public boolean ReadFile() { boolean ret = false; FilenameFilter FileFilter = null; File dir = new File(fDir); String[] FeeFiles; int Lines = 0; BufferedReader FeeFile = null; PreparedStatement DelSt = null, InsSt = null; String Line = null, Term = null, CurTerm = null, TermType = null, Code = null; double[] Fee = new double[US_D + 1]; double FeeAm = 0; String UpdateSt = "INSERT INTO reporter.term_fee (TERM, TERM_TYPE, THEM_VC, THEM_VE, THEM_EC, THEM_EE, THEM_D," + "BA_VC, BA_VE, BA_EC, BA_EE, BA_D," + "US_VC, US_VE, US_EC, US_EE, US_D)" + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; try { FileFilter = new FilenameFilter() { public boolean accept(File dir, String name) { if ((new File(dir, name)).isDirectory()) return false; else return (name.matches(fFileMask)); } }; FeeFiles = dir.list(FileFilter); java.util.Arrays.sort(FeeFiles); System.out.println(FeeFiles[FeeFiles.length - 1] + " " + (new SimpleDateFormat("dd.MM.yy HH:mm:ss")).format(new Date())); Log.info(String.format("Load = %1s", fDir + FeeFiles[FeeFiles.length - 1])); FeeFile = new BufferedReader(new FileReader(fDir + FeeFiles[FeeFiles.length - 1])); FeeZero(Fee); DelSt = cnProd.prepareStatement("delete from reporter.term_fee"); DelSt.executeUpdate(); InsSt = cnProd.prepareStatement(UpdateSt); WriteTerm(FeeFiles[FeeFiles.length - 1] + " " + (new SimpleDateFormat("dd.MM.yy HH:mm:ss")).format(new Date()), "XXX", Fee, InsSt); while ((Line = FeeFile.readLine()) != null) { Lines++; if (!Line.matches("\\d{15}\\s+��������.+")) continue; Term = Line.substring(7, 15); if ((CurTerm == null) || !Term.equals(CurTerm)) { if (CurTerm != null) { WriteTerm(CurTerm, TermType, Fee, InsSt); } CurTerm = Term; if (Line.indexOf("���") > 0) TermType = "���"; else TermType = "���"; FeeZero(Fee); } Code = Line.substring(64, 68).trim().toUpperCase(); if (Code.equals("ST") || Code.equals("AC") || Code.equals("8110") || Code.equals("8160")) continue; FeeAm = new Double(Line.substring(140, 160)).doubleValue(); if (Line.indexOf("�� ����� ������") > 0) SetFee(Fee, CARD_THEM, Code, FeeAm); else if (Line.indexOf("�� ������ �����") > 0) SetFee(Fee, CARD_BA, Code, FeeAm); else if (Line.indexOf("�� ������ ��") > 0) SetFee(Fee, CARD_US, Code, FeeAm); else throw new Exception("������ ���� ����.:" + Line); } WriteTerm(CurTerm, TermType, Fee, InsSt); cnProd.commit(); ret = true; } catch (Exception e) { System.out.printf("Err = %1s\r\n", e.getMessage()); Log.error(String.format("Err = %1s", e.getMessage())); Log.error(String.format("Line = %1s", Line)); try { cnProd.rollback(); } catch (Exception ee) { } ; } finally { try { if (FeeFile != null) FeeFile.close(); } catch (Exception ee) { } } try { if (DelSt != null) DelSt.close(); if (InsSt != null) InsSt.close(); cnProd.setAutoCommit(true); } catch (Exception ee) { } Log.info(String.format("Lines = %1d", Lines)); return (ret); }
900,750
1
@Override public void render(Output output) throws IOException { output.setStatus(statusCode, statusMessage); if (headersMap != null) { Iterator<Entry<String, String>> iterator = headersMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> header = iterator.next(); output.addHeader(header.getKey(), header.getValue()); } } if (file != null) { InputStream inputStream = new FileInputStream(file); try { output.open(); OutputStream out = output.getOutputStream(); IOUtils.copy(inputStream, out); } finally { inputStream.close(); output.close(); } } }
public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); }
900,751
1
public void write(OutputStream out, String className, InputStream classDefStream) throws IOException { ByteArrayOutputStream a = new ByteArrayOutputStream(); IOUtils.copy(classDefStream, a); a.close(); DataOutputStream da = new DataOutputStream(out); da.writeUTF(className); da.writeUTF(new String(base64.cipher(a.toByteArray()))); }
private File Gzip(File f) throws IOException { if (f == null || !f.exists()) return null; File dest_dir = f.getParentFile(); String dest_filename = f.getName() + ".gz"; File zipfile = new File(dest_dir, dest_filename); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(zipfile)); FileInputStream in = new FileInputStream(f); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.finish(); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { f.delete(); } catch (Exception e) { } return zipfile; }
900,752
1
private void copy(File from, File to) { if (from.isDirectory()) { File[] files = from.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { File newTo = new File(to.getPath() + File.separator + files[i].getName()); newTo.mkdirs(); copy(files[i], newTo); } else { copy(files[i], to); } } } else { try { to = new File(to.getPath() + File.separator + from.getName()); to.createNewFile(); FileChannel src = new FileInputStream(from).getChannel(); FileChannel dest = new FileOutputStream(to).getChannel(); dest.transferFrom(src, 0, src.size()); dest.close(); src.close(); } catch (FileNotFoundException e) { errorLog(e.toString()); e.printStackTrace(); } catch (IOException e) { errorLog(e.toString()); e.printStackTrace(); } } }
public static void main(String argv[]) { Matrix A, B, C, Z, O, I, R, S, X, SUB, M, T, SQ, DEF, SOL; int errorCount = 0; int warningCount = 0; double tmp, s; double[] columnwise = { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12. }; double[] rowwise = { 1., 4., 7., 10., 2., 5., 8., 11., 3., 6., 9., 12. }; double[][] avals = { { 1., 4., 7., 10. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] rankdef = avals; double[][] tvals = { { 1., 2., 3. }, { 4., 5., 6. }, { 7., 8., 9. }, { 10., 11., 12. } }; double[][] subavals = { { 5., 8., 11. }, { 6., 9., 12. } }; double[][] rvals = { { 1., 4., 7. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] pvals = { { 1., 1., 1. }, { 1., 2., 3. }, { 1., 3., 6. } }; double[][] ivals = { { 1., 0., 0., 0. }, { 0., 1., 0., 0. }, { 0., 0., 1., 0. } }; double[][] evals = { { 0., 1., 0., 0. }, { 1., 0., 2.e-7, 0. }, { 0., -2.e-7, 0., 1. }, { 0., 0., 1., 0. } }; double[][] square = { { 166., 188., 210. }, { 188., 214., 240. }, { 210., 240., 270. } }; double[][] sqSolution = { { 13. }, { 15. } }; double[][] condmat = { { 1., 3. }, { 7., 9. } }; int rows = 3, cols = 4; int invalidld = 5; int raggedr = 0; int raggedc = 4; int validld = 3; int nonconformld = 4; int ib = 1, ie = 2, jb = 1, je = 3; int[] rowindexset = { 1, 2 }; int[] badrowindexset = { 1, 3 }; int[] columnindexset = { 1, 2, 3 }; int[] badcolumnindexset = { 1, 2, 4 }; double columnsummax = 33.; double rowsummax = 30.; double sumofdiagonals = 15; double sumofsquares = 650; print("\nTesting constructors and constructor-like methods...\n"); try { A = new Matrix(columnwise, invalidld); errorCount = try_failure(errorCount, "Catch invalid length in packed constructor... ", "exception not thrown for invalid input"); } catch (IllegalArgumentException e) { try_success("Catch invalid length in packed constructor... ", e.getMessage()); } try { A = new Matrix(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to default constructor... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructor... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } try { A = Matrix.constructWithCopy(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to constructWithCopy... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructWithCopy... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } A = new Matrix(columnwise, validld); B = new Matrix(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; C = B.minus(A); avals[0][0] = tmp; B = Matrix.constructWithCopy(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; if ((tmp - B.get(0, 0)) != 0.0) { errorCount = try_failure(errorCount, "constructWithCopy... ", "copy not effected... data visible outside"); } else { try_success("constructWithCopy... ", ""); } avals[0][0] = columnwise[0]; I = new Matrix(ivals); try { check(I, Matrix.identity(3, 4)); try_success("identity... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "identity... ", "identity Matrix not successfully created"); } print("\nTesting access methods...\n"); B = new Matrix(avals); if (B.getRowDimension() != rows) { errorCount = try_failure(errorCount, "getRowDimension... ", ""); } else { try_success("getRowDimension... ", ""); } if (B.getColumnDimension() != cols) { errorCount = try_failure(errorCount, "getColumnDimension... ", ""); } else { try_success("getColumnDimension... ", ""); } B = new Matrix(avals); double[][] barray = B.getArray(); if (barray != avals) { errorCount = try_failure(errorCount, "getArray... ", ""); } else { try_success("getArray... ", ""); } barray = B.getArrayCopy(); if (barray == avals) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not (deep) copied"); } try { check(barray, avals); try_success("getArrayCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not successfully (deep) copied"); } double[] bpacked = B.getColumnPackedCopy(); try { check(bpacked, columnwise); try_success("getColumnPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getColumnPackedCopy... ", "data not successfully (deep) copied by columns"); } bpacked = B.getRowPackedCopy(); try { check(bpacked, rowwise); try_success("getRowPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getRowPackedCopy... ", "data not successfully (deep) copied by rows"); } try { tmp = B.get(B.getRowDimension(), B.getColumnDimension() - 1); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { tmp = B.get(B.getRowDimension() - 1, B.getColumnDimension()); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("get(int,int)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } try { if (B.get(B.getRowDimension() - 1, B.getColumnDimension() - 1) != avals[B.getRowDimension() - 1][B.getColumnDimension() - 1]) { errorCount = try_failure(errorCount, "get(int,int)... ", "Matrix entry (i,j) not successfully retreived"); } else { try_success("get(int,int)... ", ""); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "get(int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } SUB = new Matrix(subavals); try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, jb, je); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, jb, je); try { check(SUB, M); try_success("getMatrix(int,int,int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(ib, ie, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, columnindexset); try { check(SUB, M); try_success("getMatrix(int,int,int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, jb, je); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, jb, je); try { check(SUB, M); try_success("getMatrix(int[],int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, columnindexset); try { check(SUB, M); try_success("getMatrix(int[],int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.set(B.getRowDimension(), B.getColumnDimension() - 1, 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.set(B.getRowDimension() - 1, B.getColumnDimension(), 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("set(int,int,double)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } try { B.set(ib, jb, 0.); tmp = B.get(ib, jb); try { check(tmp, 0.); try_success("set(int,int,double)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Matrix element not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Unexpected ArrayIndexOutOfBoundsException"); } M = new Matrix(2, 3, 0.); try { B.setMatrix(ib, ie + B.getRowDimension() + 1, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, jb, je, M); try { check(M.minus(B.getMatrix(ib, ie, jb, je)), M); try_success("setMatrix(int,int,int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(ib, ie + B.getRowDimension() + 1, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, columnindexset, M); try { check(M.minus(B.getMatrix(ib, ie, columnindexset)), M); try_success("setMatrix(int,int,int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, jb, je, M); try { check(M.minus(B.getMatrix(rowindexset, jb, je)), M); try_success("setMatrix(int[],int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, columnindexset, M); try { check(M.minus(B.getMatrix(rowindexset, columnindexset)), M); try_success("setMatrix(int[],int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "submatrix not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } print("\nTesting array-like methods...\n"); S = new Matrix(columnwise, nonconformld); R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); A = R; try { S = A.minus(S); errorCount = try_failure(errorCount, "minus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minus conformance check... ", ""); } if (A.minus(R).norm1() != 0.) { errorCount = try_failure(errorCount, "minus... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minus... ", ""); } A = R.copy(); A.minusEquals(R); Z = new Matrix(A.getRowDimension(), A.getColumnDimension()); try { A.minusEquals(S); errorCount = try_failure(errorCount, "minusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minusEquals conformance check... ", ""); } if (A.minus(Z).norm1() != 0.) { errorCount = try_failure(errorCount, "minusEquals... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minusEquals... ", ""); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); C = A.minus(B); try { S = A.plus(S); errorCount = try_failure(errorCount, "plus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plus conformance check... ", ""); } try { check(C.plus(B), A); try_success("plus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plus... ", "(C = A - B, but C + B != A)"); } C = A.minus(B); C.plusEquals(B); try { A.plusEquals(S); errorCount = try_failure(errorCount, "plusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plusEquals conformance check... ", ""); } try { check(C, A); try_success("plusEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plusEquals... ", "(C = A - B, but C = C + B != A)"); } A = R.uminus(); try { check(A.plus(R), Z); try_success("uminus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "uminus... ", "(-A + A != zeros)"); } A = R.copy(); O = new Matrix(A.getRowDimension(), A.getColumnDimension(), 1.0); C = A.arrayLeftDivide(R); try { S = A.arrayLeftDivide(S); errorCount = try_failure(errorCount, "arrayLeftDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivide conformance check... ", ""); } try { check(C, O); try_success("arrayLeftDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivide... ", "(M.\\M != ones)"); } try { A.arrayLeftDivideEquals(S); errorCount = try_failure(errorCount, "arrayLeftDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivideEquals conformance check... ", ""); } A.arrayLeftDivideEquals(R); try { check(A, O); try_success("arrayLeftDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivideEquals... ", "(M.\\M != ones)"); } A = R.copy(); try { A.arrayRightDivide(S); errorCount = try_failure(errorCount, "arrayRightDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivide conformance check... ", ""); } C = A.arrayRightDivide(R); try { check(C, O); try_success("arrayRightDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivide... ", "(M./M != ones)"); } try { A.arrayRightDivideEquals(S); errorCount = try_failure(errorCount, "arrayRightDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivideEquals conformance check... ", ""); } A.arrayRightDivideEquals(R); try { check(A, O); try_success("arrayRightDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivideEquals... ", "(M./M != ones)"); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); try { S = A.arrayTimes(S); errorCount = try_failure(errorCount, "arrayTimes conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimes conformance check... ", ""); } C = A.arrayTimes(B); try { check(C.arrayRightDivideEquals(B), A); try_success("arrayTimes... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimes... ", "(A = R, C = A.*B, but C./B != A)"); } try { A.arrayTimesEquals(S); errorCount = try_failure(errorCount, "arrayTimesEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimesEquals conformance check... ", ""); } A.arrayTimesEquals(B); try { check(A.arrayRightDivideEquals(B), R); try_success("arrayTimesEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimesEquals... ", "(A = R, A = A.*B, but A./B != R)"); } print("\nTesting I/O methods...\n"); try { DecimalFormat fmt = new DecimalFormat("0.0000E00"); fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read()...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } catch (Exception e) { try { e.printStackTrace(System.out); warningCount = try_warning(warningCount, "print()/read()...", "Formatting error... will try JDK1.1 reformulation..."); DecimalFormat fmt = new DecimalFormat("0.0000"); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read() (2nd attempt) ...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } } R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); String tmpname = "TMPMATRIX.serial"; try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmpname)); out.writeObject(R); ObjectInputStream sin = new ObjectInputStream(new FileInputStream(tmpname)); A = (Matrix) sin.readObject(); try { check(A, R); try_success("writeObject(Matrix)/readObject(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "Matrix not serialized correctly"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "writeObject()/readObject()...", "unexpected I/O error, unable to run serialization test; check write permission in current directory and retry"); } catch (Exception e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "unexpected error in serialization test"); } print("\nTesting linear algebra methods...\n"); A = new Matrix(columnwise, 3); T = new Matrix(tvals); T = A.transpose(); try { check(A.transpose(), T); try_success("transpose...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "transpose()...", "transpose unsuccessful"); } A.transpose(); try { check(A.norm1(), columnsummax); try_success("norm1...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "norm1()...", "incorrect norm calculation"); } try { check(A.normInf(), rowsummax); try_success("normInf()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normInf()...", "incorrect norm calculation"); } try { check(A.normF(), Math.sqrt(sumofsquares)); try_success("normF...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normF()...", "incorrect norm calculation"); } try { check(A.trace(), sumofdiagonals); try_success("trace()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "trace()...", "incorrect trace calculation"); } try { check(A.getMatrix(0, A.getRowDimension() - 1, 0, A.getRowDimension() - 1).det(), 0.); try_success("det()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "det()...", "incorrect determinant calculation"); } SQ = new Matrix(square); try { check(A.times(A.transpose()), SQ); try_success("times(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(Matrix)...", "incorrect Matrix-Matrix product calculation"); } try { check(A.times(0.), Z); try_success("times(double)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(double)...", "incorrect Matrix-scalar product calculation"); } A = new Matrix(columnwise, 4); QRDecomposition QR = A.qr(); R = QR.getR(); try { check(A, QR.getQ().times(R)); try_success("QRDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "QRDecomposition...", "incorrect QR decomposition calculation"); } SingularValueDecomposition SVD = A.svd(); try { check(A, SVD.getU().times(SVD.getS().times(SVD.getV().transpose()))); try_success("SingularValueDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "SingularValueDecomposition...", "incorrect singular value decomposition calculation"); } DEF = new Matrix(rankdef); try { check(DEF.rank(), Math.min(DEF.getRowDimension(), DEF.getColumnDimension()) - 1); try_success("rank()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "rank()...", "incorrect rank calculation"); } B = new Matrix(condmat); SVD = B.svd(); double[] singularvalues = SVD.getSingularValues(); try { check(B.cond(), singularvalues[0] / singularvalues[Math.min(B.getRowDimension(), B.getColumnDimension()) - 1]); try_success("cond()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "cond()...", "incorrect condition number calculation"); } int n = A.getColumnDimension(); A = A.getMatrix(0, n - 1, 0, n - 1); A.set(0, 0, 0.); LUDecomposition LU = A.lu(); try { check(A.getMatrix(LU.getPivot(), 0, n - 1), LU.getL().times(LU.getU())); try_success("LUDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "LUDecomposition...", "incorrect LU decomposition calculation"); } X = A.inverse(); try { check(A.times(X), Matrix.identity(3, 3)); try_success("inverse()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "inverse()...", "incorrect inverse calculation"); } O = new Matrix(SUB.getRowDimension(), 1, 1.0); SOL = new Matrix(sqSolution); SQ = SUB.getMatrix(0, SUB.getRowDimension() - 1, 0, SUB.getRowDimension() - 1); try { check(SQ.solve(SOL), O); try_success("solve()...", ""); } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "solve()...", e1.getMessage()); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "solve()...", e.getMessage()); } A = new Matrix(pvals); CholeskyDecomposition Chol = A.chol(); Matrix L = Chol.getL(); try { check(A, L.times(L.transpose())); try_success("CholeskyDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition...", "incorrect Cholesky decomposition calculation"); } X = Chol.solve(Matrix.identity(3, 3)); try { check(A.times(X), Matrix.identity(3, 3)); try_success("CholeskyDecomposition solve()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition solve()...", "incorrect Choleskydecomposition solve calculation"); } EigenvalueDecomposition Eig = A.eig(); Matrix D = Eig.getD(); Matrix V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (symmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (symmetric)...", "incorrect symmetric Eigenvalue decomposition calculation"); } A = new Matrix(evals); Eig = A.eig(); D = Eig.getD(); V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (nonsymmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (nonsymmetric)...", "incorrect nonsymmetric Eigenvalue decomposition calculation"); } print("\nTestMatrix completed.\n"); print("Total errors reported: " + Integer.toString(errorCount) + "\n"); print("Total warnings reported: " + Integer.toString(warningCount) + "\n"); }
900,753
0
private int getRootNodeId(DataSource dataSource) throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; String query = null; try { conn = dataSource.getConnection(); st = conn.createStatement(); query = "select " + col.id + " from " + DB.Tbl.tree + " where " + col.parentId + " is null"; rs = st.executeQuery(query); while (rs.next()) { return rs.getInt(col.id); } query = "insert into " + DB.Tbl.tree + "(" + col.lKey + ", " + col.rKey + ", " + col.level + ") values(1,2,0)"; st.executeUpdate(query, new String[] { col.id }); rs = st.getGeneratedKeys(); while (rs.next()) { int genId = rs.getInt(1); rs.close(); conn.commit(); return genId; } throw new SQLException("Не удается создать корневой элемент для дерева."); } finally { try { rs.close(); } catch (Exception e) { } try { st.close(); } catch (Exception e) { } try { conn.rollback(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } } }
public synchronized String encrypt(String plaintext) { if (plaintext == null) plaintext = ""; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } byte raw[] = md.digest(); String hash = ""; try { hash = Base64Encoder.encode(raw); } catch (IOException e1) { System.err.println("Error encoding password using Jboss Base64Encoder"); e1.printStackTrace(); } return hash; }
900,754
0
public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
public static Map<String, List<String>> getResponseHeader(String address) { System.out.println(address); URLConnection conn = null; Map<String, List<String>> responseHeader = null; try { URL url = new URL(address); conn = url.openConnection(); responseHeader = conn.getHeaderFields(); } catch (Exception e) { e.printStackTrace(); } return responseHeader; }
900,755
0
private String[] read(String path) throws Exception { final String[] names = { "index.txt", "", "index.html", "index.htm" }; String[] list = null; for (int i = 0; i < names.length; i++) { URL url = new URL(path + names[i]); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer sb = new StringBuffer(); String s = null; while ((s = in.readLine()) != null) { s = s.trim(); if (s.length() > 0) { sb.append(s + "\n"); } } in.close(); if (sb.indexOf("<") != -1 && sb.indexOf(">") != -1) { List links = LinkExtractor.scan(url, sb.toString()); HashSet set = new HashSet(); int prefixLen = path.length(); for (Iterator it = links.iterator(); it.hasNext(); ) { String link = it.next().toString(); if (!link.startsWith(path)) { continue; } link = link.substring(prefixLen); int idx = link.indexOf("/"); int idxq = link.indexOf("?"); if (idx > 0 && (idxq == -1 || idx < idxq)) { set.add(link.substring(0, idx + 1)); } else { set.add(link); } } list = (String[]) set.toArray(new String[0]); } else { list = sb.toString().split("\n"); } return list; } catch (FileNotFoundException e) { e.printStackTrace(); continue; } } return new String[0]; }
private void insert(Connection c) throws SQLException { if (m_fromDb) throw new IllegalStateException("The record already exists in the database"); StringBuffer names = new StringBuffer("INSERT INTO ifServices (nodeID,ipAddr,serviceID"); StringBuffer values = new StringBuffer("?,?,?"); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) { values.append(",?"); names.append(",ifIndex"); } if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) { values.append(",?"); names.append(",status"); } if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { values.append(",?"); names.append(",lastGood"); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { values.append(",?"); names.append(",lastFail"); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) { values.append(",?"); names.append(",source"); } if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) { values.append(",?"); names.append(",notify"); } if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) { values.append(",?"); names.append(",qualifier"); } names.append(") VALUES (").append(values).append(')'); if (log().isDebugEnabled()) log().debug("DbIfServiceEntry.insert: SQL insert statment = " + names.toString()); PreparedStatement stmt = null; PreparedStatement delStmt = null; final DBUtils d = new DBUtils(getClass()); try { stmt = c.prepareStatement(names.toString()); d.watch(stmt); names = null; int ndx = 1; stmt.setInt(ndx++, m_nodeId); stmt.setString(ndx++, m_ipAddr.getHostAddress()); stmt.setInt(ndx++, m_serviceId); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) stmt.setInt(ndx++, m_ifIndex); if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) stmt.setString(ndx++, new String(new char[] { m_status })); if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { stmt.setTimestamp(ndx++, m_lastGood); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { stmt.setTimestamp(ndx++, m_lastFail); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) stmt.setString(ndx++, new String(new char[] { m_source })); if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) stmt.setString(ndx++, new String(new char[] { m_notify })); if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) stmt.setString(ndx++, m_qualifier); int rc; try { rc = stmt.executeUpdate(); } catch (SQLException e) { log().warn("ifServices DB insert got exception; will retry after " + "deletion of any existing records for this ifService " + "that are marked for deletion.", e); c.rollback(); String delCmd = "DELETE FROM ifServices WHERE status = 'D' " + "AND nodeid = ? AND ipAddr = ? AND serviceID = ?"; delStmt = c.prepareStatement(delCmd); d.watch(delStmt); delStmt.setInt(1, m_nodeId); delStmt.setString(2, m_ipAddr.getHostAddress()); delStmt.setInt(3, m_serviceId); rc = delStmt.executeUpdate(); rc = stmt.executeUpdate(); } log().debug("insert(): SQL update result = " + rc); } finally { d.cleanUp(); } m_fromDb = true; m_changed = 0; }
900,756
1
private void loadInitialDbState() throws IOException { InputStream in = SchemaAndDataPopulator.class.getClassLoader().getResourceAsStream(resourceName); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer); for (String statement : writer.toString().split(SQL_STATEMENT_DELIMITER)) { logger.info("Executing SQL Statement {}", statement); template.execute(statement); } }
public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } }
900,757
1
public void xtest1() throws Exception { InputStream input = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream tmp = new ITextManager().cut(input, 3, 8); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input.close(); tmp.close(); output.close(); }
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
900,758
0
public static void copyFile(final File in, final File out) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
public static SearchItem loadRecord(String id, boolean isContact) { String line = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(isContact ? URL_RECORD_CONTACT : URL_RECORD_COMPANY); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6); nameValuePairs.add(new BasicNameValuePair("format", "xml")); nameValuePairs.add(new BasicNameValuePair("token", Common.token)); nameValuePairs.add(new BasicNameValuePair("id", id)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); line = EntityUtils.toString(response.getEntity()); Document document = XMLfunctions.XMLfromString(line); NodeList nodes = document.getElementsByTagName("response"); Element e = (Element) nodes.item(0); String Name__Last__First_ = XMLfunctions.getValue(e, isContact ? "Name__Last__First_" : "Name"); String phone = ""; if (!isContact) phone = XMLfunctions.getValue(e, "Phone"); String Email1 = XMLfunctions.getValue(e, isContact ? "Personal_Email" : "Email"); String Home_Fax = XMLfunctions.getValue(e, isContact ? "Home_Fax" : "Fax1"); String Address1 = XMLfunctions.getValue(e, "Address1"); String Address2 = XMLfunctions.getValue(e, "Address2"); String City = XMLfunctions.getValue(e, "City"); String State = XMLfunctions.getValue(e, "State"); String Zip = XMLfunctions.getValue(e, "Zip"); String Country = XMLfunctions.getValue(e, "Country"); String Profile = XMLfunctions.getValue(e, "Profile"); String success = XMLfunctions.getValue(e, "success"); String error = XMLfunctions.getValue(e, "error"); SearchItem item = new SearchItem(); item.set(1, Name__Last__First_); item.set(2, phone); item.set(3, phone); item.set(4, Email1); item.set(5, Home_Fax); item.set(6, Address1); item.set(7, Address2); item.set(8, City); item.set(9, State); item.set(10, Zip); item.set(11, Profile); item.set(12, Country); item.set(13, success); item.set(14, error); return item; } catch (Exception e) { line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; line = null; } return null; }
900,759
1
public static String md5Encode16(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes("utf-8")); byte b[] = md.digest(); int i; StringBuilder buf = new StringBuilder(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString().substring(8, 24); } catch (Exception e) { throw new RuntimeException(e); } }
public static byte[] encrypt(String passphrase, byte[] data) throws Exception { byte[] dataTemp; try { Security.addProvider(new com.sun.crypto.provider.SunJCE()); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes()); DESKeySpec key = new DESKeySpec(md.digest()); SecretKeySpec DESKey = new SecretKeySpec(key.getKey(), "DES"); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, DESKey); dataTemp = cipher.doFinal(data); } catch (Exception e) { throw e; } return dataTemp; }
900,760
1
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
public Object read(InputStream inputStream, Map metadata) throws IOException, ClassNotFoundException { if (log.isTraceEnabled()) log.trace("Read input stream with metadata=" + metadata); Integer resCode = (Integer) metadata.get(HTTPMetadataConstants.RESPONSE_CODE); String resMessage = (String) metadata.get(HTTPMetadataConstants.RESPONSE_CODE_MESSAGE); if (resCode != null && validResponseCodes.contains(resCode) == false) throw new RuntimeException("Invalid HTTP server response [" + resCode + "] - " + resMessage); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); String soapMessage = new String(baos.toByteArray(), charsetEncoding); if (isTraceEnabled) { String prettySoapMessage = DOMWriter.printNode(DOMUtils.parse(soapMessage), true); log.trace("Incoming Response SOAPMessage\n" + prettySoapMessage); } return soapMessage; }
900,761
0
@Before public void BeforeTheTest() throws Exception { URL url = ProfileParserTest.class.getClassLoader().getResource("ca/uhn/hl7v2/conf/parser/tests/example_ack.xml"); URLConnection conn = url.openConnection(); InputStream instream = conn.getInputStream(); if (instream == null) throw new Exception("can't find the xml file"); BufferedReader in = new BufferedReader(new InputStreamReader(instream)); int tmp = 0; StringBuffer buf = new StringBuffer(); while ((tmp = in.read()) != -1) { buf.append((char) tmp); } profileString = buf.toString(); }
protected Source resolveRepositoryURI(String path) throws TransformerException { Source resolvedSource = null; try { if (path != null) { URL url = new URL(path); InputStream in = url.openStream(); if (in != null) { resolvedSource = new StreamSource(in); } } else { throw new TransformerException("Resource does not exist. \"" + path + "\" is not accessible."); } } catch (MalformedURLException mfue) { throw new TransformerException("Error accessing resource using servlet context: " + path, mfue); } catch (IOException ioe) { throw new TransformerException("Unable to access resource at: " + path, ioe); } return resolvedSource; }
900,762
0
private static byte[] Md5f(String plainText) { byte[] ab = new byte[16]; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); ab = b; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ab; }
static MenuListener openRecentHandler() { MenuListener handler = new MenuListener() { public void menuSelected(final MenuEvent event) { final JMenu menu = (JMenu) event.getSource(); menu.removeAll(); String[] recentURLSpecs = Application.getApp().getRecentURLSpecs(); for (int index = 0; index < recentURLSpecs.length; index++) { String urlSpec = recentURLSpecs[index]; JMenuItem menuItem = new JMenuItem(urlSpec); menu.add(menuItem); menuItem.setAction(openURLAction(urlSpec)); menuItem.setText(urlSpec); try { new java.net.URL(urlSpec).openStream(); } catch (java.io.IOException exception) { menuItem.setEnabled(false); } } menu.addSeparator(); final JMenuItem clearItem = new JMenuItem("Clear"); clearItem.setAction(new AbstractAction() { public void actionPerformed(final ActionEvent event) { Application.getApp().clearRecentItems(); } }); clearItem.setText("Clear"); menu.add(clearItem); } public void menuCanceled(final MenuEvent event) { } public void menuDeselected(final MenuEvent event) { } }; return handler; }
900,763
1
public CmsSetupTestResult execute(CmsSetupBean setupBean) { CmsSetupTestResult testResult = new CmsSetupTestResult(this); String basePath = setupBean.getWebAppRfsPath(); if (!basePath.endsWith(File.separator)) { basePath += File.separator; } File file1; Random rnd = new Random(); do { file1 = new File(basePath + "test" + rnd.nextInt(1000)); } while (file1.exists()); boolean success = false; try { file1.createNewFile(); FileWriter fw = new FileWriter(file1); fw.write("aA1"); fw.close(); success = true; FileReader fr = new FileReader(file1); success = success && (fr.read() == 'a'); success = success && (fr.read() == 'A'); success = success && (fr.read() == '1'); success = success && (fr.read() == -1); fr.close(); success = file1.delete(); success = !file1.exists(); } catch (Exception e) { success = false; } if (!success) { testResult.setRed(); testResult.setInfo("OpenCms cannot be installed without read and write privileges for path " + basePath + "! Please check you are running your servlet container with the right user and privileges."); testResult.setHelp("Not enough permissions to create/read/write a file"); testResult.setResult(RESULT_FAILED); } else { testResult.setGreen(); testResult.setResult(RESULT_PASSED); } return testResult; }
public void deploy(final File extension) { log.info("Deploying new extension from {}", extension.getPath()); RequestContextHolder.setRequestContext(new RequestContext(SZoneConfig.getDefaultZoneName(), SZoneConfig.getAdminUserName(SZoneConfig.getDefaultZoneName()), new BaseSessionContext())); RequestContextHolder.getRequestContext().resolve(); JarInputStream warIn; try { warIn = new JarInputStream(new FileInputStream(extension), true); } catch (IOException e) { log.warn("Unable to open extension WAR at " + extension.getPath(), e); return; } SAXReader reader = new SAXReader(false); reader.setIncludeExternalDTDDeclarations(false); String extensionPrefix = extension.getName().substring(0, extension.getName().lastIndexOf(".")); File extensionDir = new File(extensionBaseDir, extensionPrefix); extensionDir.mkdirs(); File extensionWebDir = new File(this.extensionWebDir, extensionPrefix); extensionWebDir.mkdirs(); try { for (JarEntry entry = warIn.getNextJarEntry(); entry != null; entry = warIn.getNextJarEntry()) { File inflated = new File(entry.getName().startsWith(infPrefix) ? extensionDir : extensionWebDir, entry.getName()); if (entry.isDirectory()) { log.debug("Creating directory at {}", inflated.getPath()); inflated.mkdirs(); continue; } inflated.getParentFile().mkdirs(); FileOutputStream entryOut = new FileOutputStream(inflated); if (!entry.getName().endsWith(configurationFileExtension)) { log.debug("Inflating file resource to {}", inflated.getPath()); IOUtils.copy(warIn, entryOut); entryOut.close(); continue; } try { final Document document = reader.read(new TeeInputStream(new CloseShieldInputStream(warIn), entryOut, true)); Attribute schema = document.getRootElement().attribute(schemaAttribute); if (schema == null || StringUtils.isBlank(schema.getText())) { log.debug("Inflating XML with unrecognized schema to {}", inflated.getPath()); continue; } if (schema.getText().contains(definitionsSchemaNamespace)) { log.debug("Inflating and registering definition from {}", inflated.getPath()); document.getRootElement().add(new AbstractAttribute() { private static final long serialVersionUID = -7880537136055718310L; public QName getQName() { return new QName(extensionAttr, document.getRootElement().getNamespace()); } public String getValue() { return extension.getName().substring(0, extension.getName().lastIndexOf(".")); } }); definitionModule.addDefinition(document, true); continue; } if (schema.getText().contains(templateSchemaNamespace)) { log.debug("Inflating and registering template from {}", inflated.getPath()); templateService.addTemplate(document, true, zoneModule.getDefaultZone()); continue; } } catch (DocumentException e) { log.warn("Malformed XML file in extension war at " + extension.getPath(), e); return; } } } catch (IOException e) { log.warn("Malformed extension war at " + extension.getPath(), e); return; } finally { try { warIn.close(); } catch (IOException e) { log.warn("Unable to close extension war at " + extension.getPath(), e); return; } RequestContextHolder.clear(); } log.info("Extension deployed successfully from {}", extension.getPath()); }
900,764
1
private void processBasicContent() { String[] packageNames = sourceCollector.getPackageNames(); for (int i = 0; i < packageNames.length; i++) { XdcSource[] sources = sourceCollector.getXdcSources(packageNames[i]); File dir = new File(outputDir, packageNames[i]); dir.mkdirs(); Set pkgDirs = new HashSet(); for (int j = 0; j < sources.length; j++) { XdcSource source = sources[j]; Properties patterns = source.getPatterns(); if (patterns != null) { tables.put("patterns", patterns); } pkgDirs.add(source.getFile().getParentFile()); DialectHandler dialectHandler = source.getDialectHandler(); Writer out = null; try { String sourceFilePath = source.getFile().getAbsolutePath(); source.setProcessingProperties(baseProperties, j > 0 ? sources[j - 1].getFileName() : null, j < sources.length - 1 ? sources[j + 1].getFileName() : null); String rootComment = XslUtils.transformToString(sourceFilePath, XSL_PKG + "/source-header.xsl", tables); source.setRootComment(rootComment); Document htmlDoc = XslUtils.transform(sourceFilePath, encoding, dialectHandler.getXslResourcePath(), tables); if (LOG.isInfoEnabled()) { LOG.info("Processing source file " + sourceFilePath); } out = IOUtils.getWriter(new File(dir, source.getFile().getName() + ".html"), docencoding); XmlUtils.printHtml(out, htmlDoc); if (sourceProcessor != null) { sourceProcessor.processSource(source, encoding, docencoding); } XdcSource.clearProcessingProperties(baseProperties); } catch (XmlException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } for (Iterator iter = pkgDirs.iterator(); iter.hasNext(); ) { File docFilesDir = new File((File) iter.next(), "xdc-doc-files"); if (docFilesDir.exists() && docFilesDir.isDirectory()) { File targetDir = new File(dir, "xdc-doc-files"); targetDir.mkdirs(); try { IOUtils.copyTree(docFilesDir, targetDir); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } }
void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
900,765
0
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("Copy: no such source file: " + fromFileName); if (!fromFile.canRead()) throw new IOException("Copy: source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("Copy: destination file is unwriteable: " + toFileName); if (JOptionPane.showConfirmDialog(null, "Overwrite File ?", "Overwrite File", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) return; } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("Copy: destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("Copy: destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("Copy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
public final void build() { if (!built_) { built_ = true; final boolean[] done = new boolean[] { false }; Runnable runnable = new Runnable() { public void run() { try { exists_ = true; URL url = getContentURL(); URLConnection cnx = url.openConnection(); cnx.connect(); lastModified_ = cnx.getLastModified(); length_ = cnx.getContentLength(); type_ = cnx.getContentType(); if (isDirectory()) { InputStream in = cnx.getInputStream(); BufferedReader nr = new BufferedReader(new InputStreamReader(in)); FuVectorString v = readList(nr); nr.close(); v.sort(); v.uniq(); list_ = v.toArray(); } } catch (Exception ex) { exists_ = false; } done[0] = true; } }; Thread t = new Thread(runnable, "VfsFileUrl connection " + getContentURL()); t.setPriority(Math.max(Thread.MIN_PRIORITY, t.getPriority() - 1)); t.start(); for (int i = 0; i < 100; i++) { if (done[0]) break; try { Thread.sleep(300L); } catch (InterruptedException ex) { } } if (!done[0]) { t.interrupt(); exists_ = false; canRead_ = false; FuLog.warning("VFS: fail to get " + url_); } } }
900,766
0
public DialogSongList(JFrame frame) { super(frame, "Menu_SongList", "songList"); setMinimumSize(new Dimension(400, 200)); JPanel panel, spanel; Container contentPane; (contentPane = getContentPane()).add(songSelector = new SongSelector(configKey, null, true)); songSelector.setSelectionAction(new Runnable() { public void run() { final Item<URL, MidiFileInfo> item = songSelector.getSelectedInfo(); if (item != null) { try { selection = new File(item.getKey().toURI()); author.setEnabled(true); title.setEnabled(true); difficulty.setEnabled(true); save.setEnabled(true); final MidiFileInfo info = item.getValue(); author.setText(info.getAuthor()); title.setText(info.getTitle()); Util.selectKey(difficulty, info.getDifficulty()); return; } catch (Exception e) { } } selection = null; author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); } }); contentPane.add(panel = new JPanel(), BorderLayout.SOUTH); panel.setLayout(new BorderLayout()); JScrollPane scrollPane; panel.add(scrollPane = new JScrollPane(spanel = new JPanel()), BorderLayout.NORTH); scrollPane.setPreferredSize(new Dimension(0, 60)); Util.addLabeledComponent(spanel, "Lbl_Author", author = new JTextField(10)); Util.addLabeledComponent(spanel, "Lbl_Title", title = new JTextField(14)); Util.addLabeledComponent(spanel, "Lbl_Difficulty", difficulty = new JComboBox()); difficulty.addItem(new Item<Byte, String>((byte) -1, "")); for (Map.Entry<Byte, String> entry : SongSelector.DIFFICULTIES.entrySet()) { final String value = entry.getValue(); difficulty.addItem(new Item<Byte, String>(entry.getKey(), Util.getMsg(value, value), value)); } spanel.add(save = new JButton()); Util.updateButtonText(save, "Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File selected = MidiSong.setMidiFileInfo(selection, author.getText(), title.getText(), getAsByte(difficulty)); SongSelector.refresh(); try { songSelector.setSelected(selected == null ? null : selected.toURI().toURL()); } catch (MalformedURLException ex) { } } }); author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); JButton button; panel.add(spanel = new JPanel(), BorderLayout.WEST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Import"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Delete"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (KeyboardHero.confirm(Util.getMsg("Que_SureToDelete"))) { try { new File(songSelector.getSelectedFile().toURI()).delete(); } catch (Exception ex) { Util.error(Util.getMsg("Err_CouldntDeleteFile"), ex.toString()); } SongSelector.refresh(); } } }); panel.add(spanel = new JPanel(), BorderLayout.CENTER); spanel.setLayout(new FlowLayout()); spanel.add(button = new JButton()); Util.updateButtonText(button, "Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { close(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Play"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.newGame(songSelector.getSelectedFile()); close(); } }); panel.add(spanel = new JPanel(), BorderLayout.EAST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Refresh"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SongSelector.refresh(); } }); getRootPane().setDefaultButton(button); instance = this; }
void loadImage(Frame frame, URL url) throws Exception { URLConnection conn = url.openConnection(); String mimeType = conn.getContentType(); long length = conn.getContentLength(); InputStream is = conn.getInputStream(); loadImage(frame, is, length, mimeType); }
900,767
0
protected void find(final String pckgname, final boolean recursive) { URL url; String name = pckgname; name = name.replace('.', '/'); url = ResourceLocatorTool.getClassPathResource(ExampleRunner.class, name); File directory; try { directory = new File(URLDecoder.decode(url.getFile(), "UTF-8")); } catch (final UnsupportedEncodingException e) { throw new RuntimeException(e); } if (directory.exists()) { logger.info("Searching for examples in \"" + directory.getPath() + "\"."); addAllFilesInDirectory(directory, pckgname, recursive); } else { try { logger.info("Searching for Demo classes in \"" + url + "\"."); final URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof JarURLConnection) { final JarURLConnection conn = (JarURLConnection) urlConnection; final JarFile jfile = conn.getJarFile(); final Enumeration<JarEntry> e = jfile.entries(); while (e.hasMoreElements()) { final ZipEntry entry = e.nextElement(); final Class<?> result = load(entry.getName()); if (result != null) { addClassForPackage(result); } } } } catch (final IOException e) { logger.logp(Level.SEVERE, this.getClass().toString(), "find(pckgname, recursive, classes)", "Exception", e); } catch (final Exception e) { logger.logp(Level.SEVERE, this.getClass().toString(), "find(pckgname, recursive, classes)", "Exception", e); } } }
public List<PathObject> fetchPath(BoardObject board) throws NetworkException { if (boardPathMap.containsKey(board.getId())) { return boardPathMap.get(board.getId()).getChildren(); } HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_0AN_BOARD + board.getId()); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); Document doc = XmlOperator.readDocument(entity.getContent()); PathObject parent = new PathObject(); BBSBodyParseHelper.parsePathList(doc, parent); parent = searchAndCreatePathFromRoot(parent); boardPathMap.put(board.getId(), parent); return parent.getChildren(); } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } }
900,768
0
public boolean downloadFTP(String ipFTP, String loginFTP, String senhaFTP, String diretorioFTP, String diretorioAndroid, String arquivoFTP) throws SocketException, IOException { boolean retorno = false; FileOutputStream arqReceber = null; try { ftp.connect(ipFTP); Log.i("DownloadFTP", "Connected: " + ipFTP); ftp.login(loginFTP, senhaFTP); Log.i("DownloadFTP", "Logged on"); ftp.enterLocalPassiveMode(); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); arqReceber = new FileOutputStream(file.toString()); ftp.retrieveFile("/tablet_ftp/Novo/socialAlimenta.xml", arqReceber); retorno = true; ftp.disconnect(); Log.i("DownloadFTP", "retorno:" + retorno); } catch (Exception e) { ftp.disconnect(); Log.e("DownloadFTP", "Erro:" + e.getMessage()); } finally { Log.e("DownloadFTP", "Finally"); } return retorno; }
public void initialize(IProgressMonitor monitor) throws JETException { IProgressMonitor progressMonitor = monitor; progressMonitor.beginTask("", 10); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_GeneratingJETEmitterFor_message", new Object[] { getTemplateURI() })); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); try { final JETCompiler jetCompiler = getTemplateURIPath() == null ? new MyBaseJETCompiler(getTemplateURI(), getEncoding(), getClassLoader()) : new MyBaseJETCompiler(getTemplateURIPath(), getTemplateURI(), getEncoding(), getClassLoader()); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETParsing_message", new Object[] { jetCompiler.getResolvedTemplateURI() })); jetCompiler.parse(); progressMonitor.worked(1); String packageName = jetCompiler.getSkeleton().getPackageName(); if (getTemplateURIPath() != null) { URI templateURI = URI.createURI(getTemplateURIPath()[0]); URLClassLoader theClassLoader = null; if (templateURI.isPlatformResource()) { IProject project = workspace.getRoot().getProject(templateURI.segment(1)); if (JETNature.getRuntime(project) != null) { List<URL> urls = new ArrayList<URL>(); IJavaProject javaProject = JavaCore.create(project); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); for (IClasspathEntry classpathEntry : javaProject.getResolvedClasspath(true)) { if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath projectPath = classpathEntry.getPath(); IProject otherProject = workspace.getRoot().getProject(projectPath.segment(0)); IJavaProject otherJavaProject = JavaCore.create(otherProject); urls.add(new File(otherProject.getLocation() + "/" + otherJavaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); } } theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderSuperAction(urls)); } } else if (templateURI.isPlatformPlugin()) { final Bundle bundle = Platform.getBundle(templateURI.segment(1)); if (bundle != null) { theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderBundleAction(bundle)); } } if (theClassLoader != null) { String className = (packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName(); if (className.endsWith("_")) { className = className.substring(0, className.length() - 1); } try { Class<?> theClass = theClassLoader.loadClass(className); Class<?> theOtherClass = null; try { theOtherClass = getClassLoader().loadClass(className); } catch (ClassNotFoundException exception) { } if (theClass != theOtherClass) { String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } return; } } catch (ClassNotFoundException exception) { } } } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); jetCompiler.generate(outputStream); final InputStream contents = new ByteArrayInputStream(outputStream.toByteArray()); if (!javaModel.isOpen()) { javaModel.open(new SubProgressMonitor(progressMonitor, 1)); } else { progressMonitor.worked(1); } final IProject project = workspace.getRoot().getProject(jetEmitter.getProjectName()); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETPreparingProject_message", new Object[] { project.getName() })); IJavaProject javaProject; if (!project.exists()) { progressMonitor.subTask("JET creating project " + project.getName()); project.create(new SubProgressMonitor(progressMonitor, 1)); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreatingProject_message", new Object[] { project.getName() })); IProjectDescription description = workspace.newProjectDescription(project.getName()); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); description.setLocation(null); project.open(new SubProgressMonitor(progressMonitor, 1)); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); } else { project.open(new SubProgressMonitor(progressMonitor, 5)); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); } javaProject = JavaCore.create(project); List<IClasspathEntry> classpath = new UniqueEList<IClasspathEntry>(Arrays.asList(javaProject.getRawClasspath())); for (int i = 0, len = classpath.size(); i < len; i++) { IClasspathEntry entry = classpath.get(i); if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && ("/" + project.getName()).equals(entry.getPath().toString())) { classpath.remove(i); } } progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETInitializingProject_message", new Object[] { project.getName() })); IClasspathEntry classpathEntry = JavaCore.newSourceEntry(new Path("/" + project.getName() + "/src")); IClasspathEntry jreClasspathEntry = JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")); classpath.add(classpathEntry); classpath.add(jreClasspathEntry); classpath.addAll(getClassPathEntries()); IFolder sourceFolder = project.getFolder(new Path("src")); if (!sourceFolder.exists()) { sourceFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } IFolder runtimeFolder = project.getFolder(new Path("bin")); if (!runtimeFolder.exists()) { runtimeFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), new SubProgressMonitor(progressMonitor, 1)); javaProject.setOutputLocation(new Path("/" + project.getName() + "/bin"), new SubProgressMonitor(progressMonitor, 1)); javaProject.close(); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETOpeningJavaProject_message", new Object[] { project.getName() })); javaProject.open(new SubProgressMonitor(progressMonitor, 1)); IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots(); IPackageFragmentRoot sourcePackageFragmentRoot = null; for (int j = 0; j < packageFragmentRoots.length; ++j) { IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[j]; if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) { sourcePackageFragmentRoot = packageFragmentRoot; break; } } StringTokenizer stringTokenizer = new StringTokenizer(packageName, "."); IProgressMonitor subProgressMonitor = new SubProgressMonitor(progressMonitor, 1); subProgressMonitor.beginTask("", stringTokenizer.countTokens() + 4); subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_CreateTargetFile_message")); IContainer sourceContainer = sourcePackageFragmentRoot == null ? project : (IContainer) sourcePackageFragmentRoot.getCorrespondingResource(); while (stringTokenizer.hasMoreElements()) { String folderName = stringTokenizer.nextToken(); sourceContainer = sourceContainer.getFolder(new Path(folderName)); if (!sourceContainer.exists()) { ((IFolder) sourceContainer).create(false, true, new SubProgressMonitor(subProgressMonitor, 1)); } } IFile targetFile = sourceContainer.getFile(new Path(jetCompiler.getSkeleton().getClassName() + ".java")); if (!targetFile.exists()) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreating_message", new Object[] { targetFile.getFullPath() })); targetFile.create(contents, true, new SubProgressMonitor(subProgressMonitor, 1)); } else { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETUpdating_message", new Object[] { targetFile.getFullPath() })); targetFile.setContents(contents, true, true, new SubProgressMonitor(subProgressMonitor, 1)); } subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETBuilding_message", new Object[] { project.getName() })); project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, new SubProgressMonitor(subProgressMonitor, 1)); boolean errors = hasErrors(subProgressMonitor, targetFile); if (!errors) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETLoadingClass_message", new Object[] { jetCompiler.getSkeleton().getClassName() + ".class" })); List<URL> urls = new ArrayList<URL>(); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); final Set<Bundle> bundles = new HashSet<Bundle>(); LOOP: for (IClasspathEntry jetEmitterClasspathEntry : jetEmitter.getClasspathEntries()) { IClasspathAttribute[] classpathAttributes = jetEmitterClasspathEntry.getExtraAttributes(); if (classpathAttributes != null) { for (IClasspathAttribute classpathAttribute : classpathAttributes) { if (classpathAttribute.getName().equals(CodeGenUtil.EclipseUtil.PLUGIN_ID_CLASSPATH_ATTRIBUTE_NAME)) { Bundle bundle = Platform.getBundle(classpathAttribute.getValue()); if (bundle != null) { bundles.add(bundle); continue LOOP; } } } } urls.add(new URL("platform:/resource" + jetEmitterClasspathEntry.getPath() + "/")); } URLClassLoader theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderSuperBundlesAction(bundles, urls)); Class<?> theClass = theClassLoader.loadClass((packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName()); String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } } subProgressMonitor.done(); } catch (CoreException exception) { throw new JETException(exception); } catch (Exception exception) { throw new JETException(exception); } finally { progressMonitor.done(); } }
900,769
1
private void doPOST(HttpURLConnection connection, InputStream inputXML) throws MessageServiceException { try { OutputStream requestStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.copyAndClose(inputXML, requestStream); connection.connect(); } catch (IOException e) { throw new MessageServiceException(e.getMessage(), e); } }
@Test public void testCopy_inputStreamToWriter_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer); fail(); } catch (NullPointerException ex) { } }
900,770
0
private Collection<Class<? extends Plugin>> loadFromResource(ClassLoader classLoader, String resource) throws IOException { Collection<Class<? extends Plugin>> pluginClasses = new HashSet<Class<? extends Plugin>>(); Enumeration providerFiles = classLoader.getResources(resource); if (!providerFiles.hasMoreElements()) { logger.warning("Can't find the resource: " + resource); return pluginClasses; } do { URL url = (URL) providerFiles.nextElement(); InputStream stream = url.openStream(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); } catch (IOException e) { continue; } String line; while ((line = reader.readLine()) != null) { int index = line.indexOf('#'); if (index != -1) { line = line.substring(0, index); } line = line.trim(); if (line.length() > 0) { Class pluginClass; try { pluginClass = classLoader.loadClass(line); } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Can't use the Pluginclass with the name " + line + ".", e); continue; } if (Plugin.class.isAssignableFrom(pluginClass)) { pluginClasses.add((Class<? extends Plugin>) pluginClass); } else { logger.warning("The Pluginclass with the name " + line + " isn't a subclass of Plugin."); } } } reader.close(); stream.close(); } while (providerFiles.hasMoreElements()); return pluginClasses; }
public String preProcessHTML(String uri) { final StringBuffer buf = new StringBuffer(); try { HTMLDocument doc = new HTMLDocument() { public HTMLEditorKit.ParserCallback getReader(int pos) { return new HTMLEditorKit.ParserCallback() { public void handleText(char[] data, int pos) { buf.append(data); buf.append('\n'); } }; } }; URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); Reader rd = new InputStreamReader(conn.getInputStream()); new ParserDelegator().parse(rd, doc.getReader(0), Boolean.TRUE); } catch (MalformedURLException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (URISyntaxException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } return buf.toString(); }
900,771
0
public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(QZ.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(QZ.PHRASES.getPhrase("26") + " " + QZ.PHRASES.getPhrase("27") + ": " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(QZ.PHRASES.getPhrase("19") + dest_name + QZ.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(QZ.PHRASES.getPhrase("31")); } else throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(QZ.PHRASES.getPhrase("28") + " " + QZ.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) try { source.close(); } catch (IOException e) { ; } if (destination != null) try { destination.close(); } catch (IOException e) { ; } } }
public static String[] check() throws Exception { if (currentVersion == null) throw new Exception(); URL url = new URL(versionURL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); String str = ""; BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); while (br.ready()) { str = str + br.readLine(); } br.close(); Document document = DocumentHelper.parseText(str); Node node = document.selectSingleNode("//root/version"); String latestVersion = node.valueOf("@id"); Double latest = Double.parseDouble(latestVersion); Double current = Double.parseDouble(currentVersion.substring(0, currentVersion.indexOf("-"))); if (latest > current) { String[] a = { latestVersion, node.valueOf("@url"), node.valueOf("@description") }; return a; } return null; }
900,772
0
public static void s_copy(FileInputStream fis, FileOutputStream fos) throws Exception { FileChannel in = fis.getChannel(); FileChannel out = fos.getChannel(); in.transferTo(0, in.size(), out); if (in != null) in.close(); if (out != null) out.close(); }
static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; }
900,773
0
private String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } }
public boolean downloadFile(String webdir, String fileName, String localdir) { boolean result = false; checkDownLoadDirectory(localdir); FTPClient ftp = new FTPClient(); try { ftp.connect(url); ftp.login(username, password); if (!"".equals(webdir.trim())) ftp.changeDirectory(webdir); ftp.download(fileName, new File(localdir + "//" + fileName)); result = true; ftp.disconnect(true); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (FTPIllegalReplyException e) { e.printStackTrace(); } catch (FTPException e) { e.printStackTrace(); } catch (FTPDataTransferException e) { e.printStackTrace(); } catch (FTPAbortedException e) { e.printStackTrace(); } return result; }
900,774
1
public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); }
public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
900,775
0
public void adicionaCliente(ClienteBean cliente) { PreparedStatement pstmt = null; ResultSet rs = null; String sql = "insert into cliente(nome,cpf,telefone,cursoCargo,bloqueado,ativo,tipo) values(?,?,?,?,?,?,?)"; try { pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, cliente.getNome()); pstmt.setString(2, cliente.getCPF()); pstmt.setString(3, cliente.getTelefone()); pstmt.setString(4, cliente.getCursoCargo()); pstmt.setString(5, cliente.getBloqueado()); pstmt.setString(6, cliente.getAtivo()); pstmt.setString(7, cliente.getTipo()); pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); if (rs.next()) { cliente.setIdCliente(rs.getLong(1)); } connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao inserir cliente.", ex1); } throw new RuntimeException("Erro ao inserir cliente.", ex); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); } catch (SQLException ex) { throw new RuntimeException("Ocorreu um erro no banco de dados.", ex); } } }
public static void copyAll(URL url, StringBuilder ret) { Reader in = null; try { in = new InputStreamReader(new BufferedInputStream(url.openStream())); copyAll(in, ret); } catch (IOException e) { throw new RuntimeException(e); } finally { close(in); } }
900,776
0
public static Shader loadShader(String vspath, String fspath, int textureUnits, boolean separateCam, boolean fog) throws ShaderProgramProcessException { if (vspath == "" || fspath == "") return null; BufferedReader in; String vert = "", frag = ""; try { URL v_url = Graphics.class.getClass().getResource("/eu/cherrytree/paj/graphics/shaders/" + vspath); String v_path = AppDefinition.getDefaultDataPackagePath() + "/shaders/" + vspath; if (v_url != null) in = new BufferedReader(new InputStreamReader(v_url.openStream())); else in = new BufferedReader(new InputStreamReader(new FileReader(v_path).getInputStream())); boolean run = true; String str; while (run) { str = in.readLine(); if (str != null) vert += str + "\n"; else run = false; } in.close(); } catch (Exception e) { System.err.println("Couldn't read in vertex shader \"" + vspath + "\"."); throw new ShaderNotLoadedException(vspath, fspath); } try { URL f_url = Graphics.class.getClass().getResource("/eu/cherrytree/paj/graphics/shaders/" + fspath); String f_path = AppDefinition.getDefaultDataPackagePath() + "/shaders/" + fspath; if (f_url != null) in = new BufferedReader(new InputStreamReader(f_url.openStream())); else in = new BufferedReader(new InputStreamReader(new FileReader(f_path).getInputStream())); boolean run = true; String str; while (run) { str = in.readLine(); if (str != null) frag += str + "\n"; else run = false; } in.close(); } catch (Exception e) { System.err.println("Couldn't read in fragment shader \"" + fspath + "\"."); throw new ShaderNotLoadedException(vspath, fspath); } return loadShaderFromSource(vert, frag, textureUnits, separateCam, fog); }
public void openAndClose(ZKEntry zke, LinkedList toOpen, LinkedList toRemove) throws SQLException { conn.setAutoCommit(false); try { Statement stm = conn.createStatement(); ResultSet rset = stm.executeQuery("SELECT now();"); rset.next(); Timestamp now = rset.getTimestamp("now()"); for (int i = 0; i < toRemove.size(); i++) { Workitem wi = (Workitem) toRemove.get(i); rset = stm.executeQuery("SELECT intime, part FROM stampzk WHERE stampzkid = '" + wi.getStampZkId() + "';"); rset.next(); long diff = now.getTime() - rset.getLong("intime"); float diffp = diff * rset.getFloat("part"); stm.executeUpdate("UPDATE stampzk SET outtime='" + now.getTime() + "', diff='" + diff + "', diffp='" + diffp + "' WHERE stampzkid='" + wi.getStampZkId() + "';"); } rset = stm.executeQuery("SELECT COUNT(*) FROM stampzk WHERE personalid='" + zke.getWorker().getPersonalId() + "' AND outtime='0';"); rset.next(); int count = rset.getInt("COUNT(*)") + toOpen.size(); rset = stm.executeQuery("SELECT * FROM stampzk WHERE personalid='" + zke.getWorker().getPersonalId() + "' AND outtime='0';"); while (rset.next()) { long diff = now.getTime() - rset.getLong("intime"); float diffp = diff * rset.getFloat("part"); int firstId = rset.getInt("firstid"); if (firstId == 0) firstId = rset.getInt("stampzkid"); Statement ust = conn.createStatement(); ust.executeUpdate("UPDATE stampzk SET outtime='" + now.getTime() + "', diff='" + diff + "', diffp='" + diffp + "' WHERE stampzkid='" + rset.getInt("stampzkid") + "';"); ust.executeUpdate("INSERT INTO stampzk SET zeitkid='" + rset.getInt("zeitkid") + "', personalid='" + zke.getWorker().getPersonalId() + "', funcsid='" + rset.getInt("funcsid") + "', part='" + (float) 1f / count + "', intime='" + now.getTime() + "', firstid='" + firstId + "';"); } for (int i = 0; i < toOpen.size(); i++) { stm.executeUpdate("INSERT INTO stampzk SET zeitkid='" + zke.getZeitKId() + "', personalid='" + zke.getWorker().getPersonalId() + "', intime='" + now.getTime() + "', funcsid='" + ((Workitem) toOpen.get(i)).getWorkType() + "', part='" + (float) 1f / count + "';"); } } catch (SQLException sqle) { conn.rollback(); conn.setAutoCommit(true); throw sqle; } conn.commit(); conn.setAutoCommit(true); }
900,777
1
private String calculatePassword(String string) { try { MessageDigest md5 = MessageDigest.getInstance("md5"); md5.update(nonce.getBytes()); md5.update(string.getBytes()); return toHexString(md5.digest()); } catch (NoSuchAlgorithmException e) { error("MD5 digest is no supported !!!", "ERROR"); return null; } }
private static String md5(String input) { String res = ""; try { MessageDigest cript = MessageDigest.getInstance("MD5"); cript.reset(); cript.update(input.getBytes()); byte[] md5 = cript.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { Log4k.error(pdfPrinter.class.getName(), ex.getMessage()); } return res; }
900,778
0
public InputStream doRemoteCall(NamedList<String> params) throws IOException { String protocol = "http"; String host = getHost(); int port = Integer.parseInt(getPort()); StringBuilder sb = new StringBuilder(); for (Map.Entry entry : params) { Object key = entry.getKey(); Object value = entry.getValue(); sb.append(key).append("=").append(value).append("&"); } sb.setLength(sb.length() - 1); String file = "/" + getUrl() + "/?" + sb.toString(); URL url = new URL(protocol, host, port, file); logger.debug(url.toString()); InputStream stream; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { stream = conn.getInputStream(); } catch (IOException ioe) { InputStream is = conn.getErrorStream(); if (is != null) { String msg = getStringFromInputStream(conn.getErrorStream()); throw new IOException(msg); } else { throw ioe; } } return stream; }
public boolean actualizarEstadoDivision(division div) { int intResult = 0; String sql = "UPDATE divisionxTorneo " + " SET terminado = '1' " + " WHERE idDivisionxTorneo = " + div.getidDivision(); try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); }
900,779
1
private void copyFromStdin(Path dst, FileSystem dstFs) throws IOException { if (dstFs.isDirectory(dst)) { throw new IOException("When source is stdin, destination must be a file."); } if (dstFs.exists(dst)) { throw new IOException("Target " + dst.toString() + " already exists."); } FSDataOutputStream out = dstFs.create(dst); try { IOUtils.copyBytes(System.in, out, getConf(), false); } finally { out.close(); } }
public static void copyFile(String oldPath, String newPath) throws IOException { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); } }
900,780
0
public RobotList<Location> sort_incr_Location(RobotList<Location> list, String field) { int length = list.size(); Index_value[] enemy_dist = new Index_value[length]; Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, distance(cur_loc, list.get(i))); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (enemy_dist[i].value > enemy_dist[i + 1].value) { Index_value a = enemy_dist[i]; enemy_dist[i] = enemy_dist[i + 1]; enemy_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Location> new_location_list = new RobotList<Location>(Location.class); for (int i = 0; i < length; i++) { new_location_list.addLast(list.get(enemy_dist[i].index)); } return new_location_list; }
public boolean crear() { int result = 0; String sql = "insert into ronda" + "(divisionxTorneo_idDivisionxTorneo, fechaRonda, nRonda, estado ) " + "values (?, ?, ?, ?)"; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(unaRonda); result = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (result > 0); }
900,781
1
private void post(String title, Document content, Set<String> tags) throws HttpException, IOException, TransformerException { PostMethod method = null; try { method = new PostMethod("http://www.blogger.com/feeds/" + this.blogId + "/posts/default"); method.addRequestHeader("GData-Version", String.valueOf(GDataVersion)); method.addRequestHeader("Authorization", "GoogleLogin auth=" + this.AuthToken); Document dom = this.domBuilder.newDocument(); Element entry = dom.createElementNS(Atom.NS, "entry"); dom.appendChild(entry); entry.setAttribute("xmlns", Atom.NS); Element titleNode = dom.createElementNS(Atom.NS, "title"); entry.appendChild(titleNode); titleNode.setAttribute("type", "text"); titleNode.appendChild(dom.createTextNode(title)); Element contentNode = dom.createElementNS(Atom.NS, "content"); entry.appendChild(contentNode); contentNode.setAttribute("type", "xhtml"); contentNode.appendChild(dom.importNode(content.getDocumentElement(), true)); for (String tag : tags) { Element category = dom.createElementNS(Atom.NS, "category"); category.setAttribute("scheme", "http://www.blogger.com/atom/ns#"); category.setAttribute("term", tag); entry.appendChild(category); } StringWriter out = new StringWriter(); this.xml2ascii.transform(new DOMSource(dom), new StreamResult(out)); method.setRequestEntity(new StringRequestEntity(out.toString(), "application/atom+xml", "UTF-8")); int status = getHttpClient().executeMethod(method); if (status == 201) { IOUtils.copyTo(method.getResponseBodyAsStream(), System.out); } else { throw new HttpException("post returned http-code=" + status + " expected 201 (CREATE)"); } } catch (TransformerException err) { throw err; } catch (HttpException err) { throw err; } catch (IOException err) { throw err; } finally { if (method != null) method.releaseConnection(); } }
private boolean writeResource(PluginProxy eclipseInstallPlugin, ResourceProxy translation, LocaleProxy locale) throws Exception { String translationResourceName = determineTranslatedResourceName(translation, locale); String pluginNameInDirFormat = eclipseInstallPlugin.getName().replace(Messages.getString("Characters_period"), File.separator); if (translation.getRelativePath().contains(pluginNameInDirFormat)) { return writeResourceToBundleClasspath(translation, locale); } else if (translationResourceName.contains(File.separator)) { String resourcePath = translationResourceName.substring(0, translationResourceName.lastIndexOf(File.separatorChar)); File resourcePathDirectory = new File(directory.getPath() + File.separatorChar + resourcePath); resourcePathDirectory.mkdirs(); } File fragmentResource = new File(directory.getPath() + File.separatorChar + translationResourceName); File translatedResource = new File(translation.getFileResource().getAbsolutePath()); FileChannel inputChannel = new FileInputStream(translatedResource).getChannel(); FileChannel outputChannel = new FileOutputStream(fragmentResource).getChannel(); inputChannel.transferTo(0, inputChannel.size(), outputChannel); inputChannel.close(); outputChannel.close(); return true; }
900,782
1
public static synchronized BaseFont getL2BaseFont() { if (l2baseFont == null) { final ConfigProvider conf = ConfigProvider.getInstance(); try { final ByteArrayOutputStream tmpBaos = new ByteArrayOutputStream(); String fontPath = conf.getNotEmptyProperty("font.path", null); String fontName; String fontEncoding; InputStream tmpIs; if (fontPath != null) { fontName = conf.getNotEmptyProperty("font.name", null); if (fontName == null) { fontName = new File(fontPath).getName(); } fontEncoding = conf.getNotEmptyProperty("font.encoding", null); if (fontEncoding == null) { fontEncoding = BaseFont.WINANSI; } tmpIs = new FileInputStream(fontPath); } else { fontName = Constants.L2TEXT_FONT_NAME; fontEncoding = BaseFont.IDENTITY_H; tmpIs = FontUtils.class.getResourceAsStream(Constants.L2TEXT_FONT_PATH); } IOUtils.copy(tmpIs, tmpBaos); tmpIs.close(); tmpBaos.close(); l2baseFont = BaseFont.createFont(fontName, fontEncoding, BaseFont.EMBEDDED, BaseFont.CACHED, tmpBaos.toByteArray(), null); } catch (Exception e) { e.printStackTrace(); try { l2baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); } catch (Exception ex) { } } } return l2baseFont; }
public void run() { LogPrinter.log(Level.FINEST, "Started Download at : {0, date, long}", new Date()); if (!PipeConnected) { throw new IllegalStateException("You should connect the pipe before with getInputStream()"); } InputStream ins = null; if (IsAlreadyDownloaded) { LogPrinter.log(Level.FINEST, "The file already Exists open and foward the byte"); try { ContentLength = (int) TheAskedFile.length(); ContentType = URLConnection.getFileNameMap().getContentTypeFor(TheAskedFile.getName()); ins = new FileInputStream(TheAskedFile); byte[] buffer = new byte[BUFFER_SIZE]; int read = ins.read(buffer); while (read >= 0) { Pipe.write(buffer, 0, read); read = ins.read(buffer); } } catch (IOException e) { e.printStackTrace(); } finally { if (ins != null) { try { ins.close(); } catch (IOException e) { } } } } else { LogPrinter.log(Level.FINEST, "the file does not exist locally so we try to download the thing"); File theDir = TheAskedFile.getParentFile(); if (!theDir.exists()) { theDir.mkdirs(); } for (URL url : ListFastest) { FileOutputStream fout = null; boolean OnError = false; long timestart = System.currentTimeMillis(); long bytecount = 0; try { URL newUrl = new URL(url.toString() + RequestedFile); LogPrinter.log(Level.FINEST, "the download URL = {0}", newUrl); URLConnection conn = newUrl.openConnection(); ContentType = conn.getContentType(); ContentLength = conn.getContentLength(); ins = conn.getInputStream(); fout = new FileOutputStream(TheAskedFile); byte[] buffer = new byte[BUFFER_SIZE]; int read = ins.read(buffer); while (read >= 0) { fout.write(buffer, 0, read); Pipe.write(buffer, 0, read); read = ins.read(buffer); bytecount += read; } Pipe.flush(); } catch (IOException e) { OnError = true; } finally { if (ins != null) { try { ins.close(); } catch (IOException e) { } } if (fout != null) { try { fout.close(); } catch (IOException e) { } } } long timeend = System.currentTimeMillis(); if (OnError) { continue; } else { long timetook = timeend - timestart; BigDecimal speed = new BigDecimal(bytecount).multiply(new BigDecimal(1000)).divide(new BigDecimal(timetook), MathContext.DECIMAL32); for (ReportCalculatedStatistique report : Listener) { report.reportUrlStat(url, speed, timetook); } break; } } } LogPrinter.log(Level.FINEST, "download finished at {0,date,long}", new Date()); if (Pipe != null) { try { Pipe.close(); } catch (IOException e) { e.printStackTrace(); } } }
900,783
0
public static InputSource getInputSource(URL url) throws IOException { String proto = url.getProtocol().toLowerCase(); if (!("http".equals(proto) || "https".equals(proto))) throw new IllegalArgumentException("OAI-PMH only allows HTTP(S) as network protocol!"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); StringBuilder ua = new StringBuilder("Java/"); ua.append(System.getProperty("java.version")); ua.append(" ("); ua.append(OAIHarvester.class.getName()); ua.append(')'); conn.setRequestProperty("User-Agent", ua.toString()); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, identity;q=0.3, *;q=0"); conn.setRequestProperty("Accept-Charset", "utf-8, *;q=0.1"); conn.setRequestProperty("Accept", "text/xml, application/xml, *;q=0.1"); conn.setUseCaches(false); conn.setFollowRedirects(true); log.debug("Opening connection..."); InputStream in = null; try { conn.connect(); in = conn.getInputStream(); } catch (IOException ioe) { int after, code; try { after = conn.getHeaderFieldInt("Retry-After", -1); code = conn.getResponseCode(); } catch (IOException ioe2) { after = -1; code = -1; } if (code == HttpURLConnection.HTTP_UNAVAILABLE && after > 0) throw new RetryAfterIOException(after, ioe); throw ioe; } String encoding = conn.getContentEncoding(); if (encoding == null) encoding = "identity"; encoding = encoding.toLowerCase(); log.debug("HTTP server uses " + encoding + " content encoding."); if ("gzip".equals(encoding)) in = new GZIPInputStream(in); else if ("deflate".equals(encoding)) in = new InflaterInputStream(in); else if (!"identity".equals(encoding)) throw new IOException("Server uses an invalid content encoding: " + encoding); String contentType = conn.getContentType(); String charset = null; if (contentType != null) { contentType = contentType.toLowerCase(); int charsetStart = contentType.indexOf("charset="); if (charsetStart >= 0) { int charsetEnd = contentType.indexOf(";", charsetStart); if (charsetEnd == -1) charsetEnd = contentType.length(); charsetStart += "charset=".length(); charset = contentType.substring(charsetStart, charsetEnd).trim(); } } log.debug("Charset from Content-Type: '" + charset + "'"); InputSource src = new InputSource(in); src.setSystemId(url.toString()); src.setEncoding(charset); return src; }
@Override public void run() { File dir = new File(loggingDir); if (!dir.isDirectory()) { logger.error("Logging directory \"" + dir.getAbsolutePath() + "\" does not exist."); return; } File file = new File(dir, new Date().toString().replaceAll("[ ,:]", "") + "LoadBalancerLog.txt"); FileWriter writer; try { writer = new FileWriter(file); } catch (IOException e) { e.printStackTrace(); return; } int counter = 0; while (!isInterrupted() && counter < numProbes) { try { writer.write(System.currentTimeMillis() + "," + currentPending + "," + currentThreads + "," + droppedTasks + "," + executionExceptions + "," + currentWeight + "," + averageWaitTime + "," + averageExecutionTime + "#"); writer.flush(); } catch (IOException e) { e.printStackTrace(); break; } counter++; try { sleep(probeTime); } catch (InterruptedException e) { e.printStackTrace(); break; } } try { writer.close(); } catch (IOException e) { e.printStackTrace(); return; } FileReader reader; try { reader = new FileReader(file); } catch (FileNotFoundException e2) { e2.printStackTrace(); return; } Vector<StatStorage> dataV = new Vector<StatStorage>(); int c; try { c = reader.read(); } catch (IOException e1) { e1.printStackTrace(); c = -1; } String entry = ""; Date startTime = null; Date stopTime = null; while (c != -1) { if (c == 35) { String parts[] = entry.split(","); if (startTime == null) startTime = new Date(Long.parseLong(parts[0])); if (parts.length > 0) dataV.add(parse(parts)); stopTime = new Date(Long.parseLong(parts[0])); entry = ""; } else { entry += (char) c; } try { c = reader.read(); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); } catch (IOException e) { e.printStackTrace(); } if (dataV.size() > 0) { int[] dataPending = new int[dataV.size()]; int[] dataOccupied = new int[dataV.size()]; long[] dataDropped = new long[dataV.size()]; long[] dataException = new long[dataV.size()]; int[] dataWeight = new int[dataV.size()]; long[] dataExecution = new long[dataV.size()]; long[] dataWait = new long[dataV.size()]; for (int i = 0; i < dataV.size(); i++) { dataPending[i] = dataV.get(i).pending; dataOccupied[i] = dataV.get(i).occupied; dataDropped[i] = dataV.get(i).dropped; dataException[i] = dataV.get(i).exceptions; dataWeight[i] = dataV.get(i).currentWeight; dataExecution[i] = (long) dataV.get(i).executionTime; dataWait[i] = (long) dataV.get(i).waitTime; } String startName = startTime.toString(); startName = startName.replaceAll("[ ,:]", ""); file = new File(dir, startName + "pending.gif"); SimpleChart.drawChart(file, 640, 480, dataPending, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "occupied.gif"); SimpleChart.drawChart(file, 640, 480, dataOccupied, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "dropped.gif"); SimpleChart.drawChart(file, 640, 480, dataDropped, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "exceptions.gif"); SimpleChart.drawChart(file, 640, 480, dataException, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "weight.gif"); SimpleChart.drawChart(file, 640, 480, dataWeight, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "execution.gif"); SimpleChart.drawChart(file, 640, 480, dataExecution, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "wait.gif"); SimpleChart.drawChart(file, 640, 480, dataWait, startTime, stopTime, new Color(0, 0, 0)); } recordedExecutionThreads = 0; recordedWaitingThreads = 0; averageExecutionTime = 0; averageWaitTime = 0; if (!isLocked) { debugThread = new DebugThread(); debugThread.start(); } }
900,784
1
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
900,785
0
@TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getServerCertificates", args = { }) public final void test_getServerCertificates() throws Exception { try { URL url = new URL("https://localhost:55555"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); try { connection.getServerCertificates(); fail("IllegalStateException wasn't thrown"); } catch (IllegalStateException ise) { } } catch (Exception e) { fail("Unexpected exception " + e + " for exception case"); } HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); try { Certificate[] cert = con.getServerCertificates(); fail("SSLPeerUnverifiedException wasn't thrown"); } catch (SSLPeerUnverifiedException e) { } con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); try { Certificate[] cert = con.getServerCertificates(); assertNotNull(cert); assertEquals(1, cert.length); } catch (Exception e) { fail("Unexpected exception " + e); } }
@Override public long insertStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); long result = statement.executeUpdate(sql.toString()); if (result == 0) log.warn(sql + " result row count is 0"); getConnection().commit(); return getInsertId(statement); } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); throw new RuntimeException(); } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
900,786
1
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { closeQuietly(in); closeQuietly(out); } return success; }
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
900,787
0
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
private String getRandomGUID(final boolean secure) { MessageDigest md5 = null; final StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } try { final long time = System.currentTimeMillis(); final long rand; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { final int bufferIndex = array[j] & SHIFT_SPACE; if (ZERO_TEST > bufferIndex) sb.append(CHAR_ZERO); sb.append(Integer.toHexString(bufferIndex)); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
900,788
0
private static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(frase.getBytes()); return md.digest(); } catch (Exception e) { return null; } }
public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_BILL")); pst.setDate(1, new java.sql.Date(bill.getDate().getTime())); pst.setInt(2, bill.getIdAccount()); insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from bill"); rs.next(); id = rs.getInt(1); connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return id; }
900,789
0
public final void saveAsCopy(String current_image, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; String source = temp_dir + key + current_image; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } }
public void run() { BufferedInputStream bis = null; URLConnection url = null; String textType = null; StringBuffer sb = new StringBuffer(); try { if (!location.startsWith("http://")) { location = "http://" + location; } url = (new URL(location)).openConnection(); size = url.getContentLength(); textType = url.getContentType(); lastModified = url.getIfModifiedSince(); InputStream is = url.getInputStream(); bis = new BufferedInputStream(is); if (textType.startsWith("text/plain")) { int i; i = bis.read(); ++position; status = " Reading From URL..."; this.setChanged(); this.notifyObservers(); while (i != END_OF_STREAM) { sb.append((char) i); i = bis.read(); ++position; if (position % (size / 25) == 0) { this.setChanged(); this.notifyObservers(); } if (abortLoading) { break; } } status = " Finished reading URL..."; } else if (textType.startsWith("text/html")) { int i; i = bis.read(); char c = (char) i; ++position; status = " Reading From URL..."; this.setChanged(); this.notifyObservers(); boolean enclosed = false; if (c == '<') { enclosed = true; } while (i != END_OF_STREAM) { if (enclosed) { if (c == '>') { enclosed = false; } } else { if (c == '<') { enclosed = true; } else { sb.append((char) i); } } i = bis.read(); c = (char) i; ++position; if (size == 0) { if (position % (size / 25) == 0) { this.setChanged(); this.notifyObservers(); } } if (abortLoading) { break; } } status = " Finished reading URL..."; } else { status = " Unable to read document type: " + textType + "..."; } bis.close(); try { document.insertString(0, sb.toString(), SimpleAttributeSet.EMPTY); } catch (BadLocationException ble) { ble.printStackTrace(); } finished = true; this.setChanged(); this.notifyObservers(); } catch (IOException ioe) { try { document.insertString(0, sb.toString(), SimpleAttributeSet.EMPTY); } catch (BadLocationException ble) { ble.printStackTrace(); } status = " IO Error Reading From URL..."; finished = true; this.setChanged(); this.notifyObservers(); } }
900,790
0
private byte[] getMD5(String string) throws IMException { byte[] buffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(string.getBytes("utf-8")); buffer = md.digest(); buffer = getHexString(buffer); } catch (NoSuchAlgorithmException e) { throw new IMException(e); } catch (UnsupportedEncodingException ue) { throw new IMException(ue); } return buffer; }
public static JSONObject delete(String uid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(DELETE_URI + "?uid=" + uid); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); return new JSONObject(res); } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
900,791
1
public synchronized void write() throws IOException { ZipOutputStream jar = new ZipOutputStream(new FileOutputStream(jarPath)); int index = className.lastIndexOf('.'); String packageName = className.substring(0, index); String clazz = className.substring(index + 1); String directory = packageName.replace('.', '/'); ZipEntry dummyClass = new ZipEntry(directory + "/" + clazz + ".class"); jar.putNextEntry(dummyClass); ClassGen classgen = new ClassGen(getClassName(), "java.lang.Object", "<generated>", Constants.ACC_PUBLIC | Constants.ACC_SUPER, null); byte[] bytes = classgen.getJavaClass().getBytes(); jar.write(bytes); jar.closeEntry(); ZipEntry synthFile = new ZipEntry(directory + "/synth.xml"); jar.putNextEntry(synthFile); Comment comment = new Comment("Generated by SynthBuilder from L2FProd.com"); Element root = new Element("synth"); root.addAttribute(new Attribute("version", "1")); root.appendChild(comment); Element defaultStyle = new Element("style"); defaultStyle.addAttribute(new Attribute("id", "default")); Element defaultFont = new Element("font"); defaultFont.addAttribute(new Attribute("name", "SansSerif")); defaultFont.addAttribute(new Attribute("size", "12")); defaultStyle.appendChild(defaultFont); Element defaultState = new Element("state"); defaultStyle.appendChild(defaultState); root.appendChild(defaultStyle); Element bind = new Element("bind"); bind.addAttribute(new Attribute("style", "default")); bind.addAttribute(new Attribute("type", "region")); bind.addAttribute(new Attribute("key", ".*")); root.appendChild(bind); doc = new Document(root); imagesToCopy = new HashMap(); ComponentStyle[] styles = config.getStyles(); for (ComponentStyle element : styles) { write(element); } Serializer writer = new Serializer(jar); writer.setIndent(2); writer.write(doc); writer.flush(); jar.closeEntry(); for (Iterator iter = imagesToCopy.keySet().iterator(); iter.hasNext(); ) { String element = (String) iter.next(); File pathToImage = (File) imagesToCopy.get(element); ZipEntry image = new ZipEntry(directory + "/" + element); jar.putNextEntry(image); FileInputStream input = new FileInputStream(pathToImage); int read = -1; while ((read = input.read()) != -1) { jar.write(read); } input.close(); jar.flush(); jar.closeEntry(); } jar.flush(); jar.close(); }
private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
900,792
0
@Override public void save(String arxivId, InputStream inputStream, String encoding) { String filename = StringUtil.arxivid2filename(arxivId, "tex"); try { Writer writer = new OutputStreamWriter(new FileOutputStream(String.format("%s/%s", LATEX_DOCUMENT_DIR, filename)), encoding); IOUtils.copy(inputStream, writer, encoding); writer.flush(); writer.close(); inputStream.close(); } catch (IOException e) { logger.error("Failed to save the Latex source with id='{}'", arxivId, e); throw new RuntimeException(e); } }
public static void setFinishedFlag(String ip, String port, String user, String dbname, String password, int flag) throws Exception { String sql = "update flag set flag = " + flag; Connection conn = CubridDBCenter.getConnection(ip, port, dbname, user, password); System.out.println("====:::===" + ip); Statement stmt = null; try { conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate(sql); conn.commit(); } catch (Exception ex) { ex.printStackTrace(); conn.rollback(); throw ex; } finally { stmt.close(); conn.close(); } }
900,793
1
public void unzip(String resource) { File f = new File(resource); if (!f.exists()) throw new RuntimeException("The specified resources does not exist (" + resource + ")"); String parent = f.getParent().toString(); try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(resource); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { log.info("Extracting archive entry: " + entry); String entryPath = new StringBuilder(parent).append(System.getProperty("file.separator")).append(entry.getName()).toString(); if (entry.isDirectory()) { log.info("Creating directory: " + entryPath); (new File(entryPath)).mkdir(); continue; } int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(entryPath); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); } zis.close(); } catch (Exception e) { e.printStackTrace(); } }
public void run() { try { File inf = new File(dest); if (!inf.exists()) { inf.getParentFile().mkdirs(); } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); out.transferFrom(in, 0, in.size()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.err.println("Error copying file \n" + src + "\n" + dest); } }
900,794
1
public static String createHash(String seed) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Can't happen!", e); } try { md.update(seed.getBytes(CHARSET)); md.update(String.valueOf(System.currentTimeMillis()).getBytes(CHARSET)); return toHexString(md.digest()); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Can't happen!", e); } }
public static String getDigest(String seed, byte[] code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } }
900,795
1
public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); }
public void test() throws Exception { File temp = File.createTempFile("test", ".test"); temp.deleteOnExit(); StorageFile s = new StorageFile(temp, "UTF-8"); s.addText("Test"); s.getOutputStream().write("ing is important".getBytes("UTF-8")); s.getWriter().write(" but overrated"); assertEquals("Testing is important but overrated", s.getText()); s.close(ResponseStateOk.getInstance()); assertEquals("Testing is important but overrated", s.getText()); InputStream input = s.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer, "UTF-8"); assertEquals("Testing is important but overrated", writer.toString()); try { s.getOutputStream(); fail("Should thow an IOException as it is closed."); } catch (IOException e) { } }
900,796
0
private ChangeCapsule fetchServer(OWLOntology ontologyURI, Long sequenceNumber) throws IOException { String requestString = "http://" + InetAddress.getLocalHost().getHostName() + ":8080/ChangeServer"; requestString += "?fetch=" + URLEncoder.encode(ontologyURI.getURI().toString(), "UTF-8"); requestString += "&number" + sequenceNumber; URL url = new URL(requestString); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer returned = new StringBuffer(); String str; while (null != ((str = input.readLine()))) { returned.append(str); } input.close(); ChangeCapsule cp = new ChangeCapsule(returned.toString()); return cp; }
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
900,797
0
public void connect(final URLConnectAdapter urlAdapter) { if (this.connectSettings == null) { throw new IllegalStateException("Invalid Connect Settings (is null)"); } final HttpURLConnection httpConnection = (HttpURLConnection) urlAdapter.openConnection(); BufferedReader in; try { in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); final StringBuilder buf = new StringBuilder(200); String str; while ((str = in.readLine()) != null) { buf.append(str); buf.append('\n'); } final ConnectResult result = new ConnectResult(httpConnection.getResponseCode(), buf.toString()); final Map<String, List<String>> headerFields = httpConnection.getHeaderFields(); for (Map.Entry<String, List<String>> entry : headerFields.entrySet()) { final String key = entry.getKey(); final List<String> val = entry.getValue(); if ((val != null) && (val.size() > 1)) { System.out.println("WARN: Invalid header value : " + key + " url=" + this.connectSettings.getUrl()); } if (key != null) { result.addHeader(key, val.get(0), val); } else { result.addHeader("Status", val.get(0), val); } } this.lastResult = result; } catch (IOException e) { throw new ConnectException(e); } }
private RatingServiceSelectionResponseType contactService(String xmlInputString) throws Exception { OutputStream outputStream = null; RatingServiceSelectionResponseType rType = null; try { URL url = new URL(ENDPOINT_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); outputStream = connection.getOutputStream(); outputStream.write(xmlInputString.getBytes()); outputStream.flush(); outputStream.close(); rType = readURLConnection(connection); connection.disconnect(); } catch (Exception e) { throw e; } finally { if (outputStream != null) { outputStream.close(); outputStream = null; } } return rType; }
900,798
1
private static void readIzvestiyaArticles() throws IOException { CsvReader reader = new CsvReader(new InputStreamReader(IzvestiyaUtil.class.getClassLoader().getResourceAsStream("mathnet_izvestiya.csv")), ';'); reader.setTrimWhitespace(true); try { while (reader.readRecord()) { String id = reader.get(0); String filename = reader.get(1); StringTokenizer st = new StringTokenizer(filename, "-."); String name = st.nextToken(); String volume = st.nextToken(); String year = st.nextToken(); String extension = st.nextToken(); String filepath = String.format("%s/%s/%s-%s.%s", year, volume.length() == 1 ? "0" + volume : volume, name, volume, extension); id2filename.put(id, filepath); } } finally { reader.close(); } for (Map.Entry<String, String> entry : id2filename.entrySet()) { String filepath = String.format("%s/%s", INPUT_DIR, entry.getValue()); filepath = new File(filepath).exists() ? filepath : filepath.replace(".tex", ".TEX"); if (new File(filepath).exists()) { InputStream in = new FileInputStream(filepath); FileOutputStream out = new FileOutputStream(String.format("%s/%s.tex", OUTPUT_DIR, entry.getKey()), false); try { org.apache.commons.io.IOUtils.copy(in, out); } catch (Exception e) { org.apache.commons.io.IOUtils.closeQuietly(in); org.apache.commons.io.IOUtils.closeQuietly(out); } } else { logger.log(Level.INFO, "File with the path=" + filepath + " doesn't exist"); } } }
public static void main(String[] args) throws IOException { System.out.println("Start filtering zgps..."); final Config config = ConfigUtils.loadConfig(args[0]); final String CONFIG_MODULE = "GPSFilterZGPS"; File sourceFileSelectedStages = new File(config.findParam(CONFIG_MODULE, "sourceFileSelectedStages")); File sourceFileZGPS = new File(config.findParam(CONFIG_MODULE, "sourceFileZGPS")); File targetFile = new File(config.findParam(CONFIG_MODULE, "targetFile")); System.out.println("Start reading selected stages..."); FilterZGPSSelectedStages selectedStages = new FilterZGPSSelectedStages(); selectedStages.createSelectedStages(sourceFileSelectedStages); System.out.println("Done. " + selectedStages.getSelectedStages().size() + " stages were stored"); System.out.println("Start reading and writing zgps..."); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFileZGPS))); BufferedWriter out = new BufferedWriter(new FileWriter(targetFile)); out.write(in.readLine()); out.newLine(); String lineFromInputFile; while ((lineFromInputFile = in.readLine()) != null) { String[] entries = lineFromInputFile.split("\t"); if (selectedStages.containsStage(Integer.parseInt(entries[0]), Integer.parseInt(entries[1]), Integer.parseInt(entries[2]))) { out.write(lineFromInputFile); out.newLine(); out.flush(); } } in.close(); out.close(); } catch (FileNotFoundException e) { System.out.println("Could not find source file for selected stages."); e.printStackTrace(); } catch (IOException e) { System.out.println("IO Exception while reading or writing zgps."); e.printStackTrace(); } System.out.println("Done."); }
900,799