label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String requestURI = req.getRequestURI(); logger.info("The requested URI: {}", requestURI); String parameter = requestURI.substring(requestURI.lastIndexOf(ARXIVID_ENTRY) + ARXIVID_ENTRY_LENGTH); int signIndex = parameter.indexOf(StringUtil.ARXIVID_SEGMENTID_DELIMITER); String arxivId = signIndex != -1 ? parameter.substring(0, signIndex) : parameter; String segmentId = signIndex != -1 ? parameter.substring(signIndex + 1) : null; if (arxivId == null) { logger.error("The request with an empty arxiv id parameter"); return; } String filePath = segmentId == null ? format("/opt/mocassin/aux-pdf/%s" + StringUtil.arxivid2filename(arxivId, "pdf")) : "/opt/mocassin/pdf/" + StringUtil.segmentid2filename(arxivId, Integer.parseInt(segmentId), "pdf"); if (!new File(filePath).exists()) { filePath = format("/opt/mocassin/aux-pdf/%s", StringUtil.arxivid2filename(arxivId, "pdf")); } try { FileInputStream fileInputStream = new FileInputStream(filePath); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(fileInputStream, byteArrayOutputStream); resp.setContentType("application/pdf"); resp.setHeader("Content-disposition", String.format("attachment; filename=%s", StringUtil.arxivid2filename(arxivId, "pdf"))); ServletOutputStream outputStream = resp.getOutputStream(); outputStream.write(byteArrayOutputStream.toByteArray()); outputStream.close(); } catch (FileNotFoundException e) { logger.error("Error while downloading: PDF file= '{}' not found", filePath); } catch (IOException e) { logger.error("Error while downloading the PDF file", e); } } Code Sample 2: private String loadStatusResult() { try { URL url = new URL(getServerUrl()); InputStream input = url.openStream(); InputStreamReader is = new InputStreamReader(input, "utf-8"); BufferedReader reader = new BufferedReader(is); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (MalformedURLException e1) { e1.printStackTrace(); return null; } catch (IOException e2) { e2.printStackTrace(); return null; } }
11
Code Sample 1: public static void copy(final File src, final File dst) throws IOException, IllegalArgumentException { long fileSize = src.length(); final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } src.delete(); } } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (destination == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fic, foc; try { fis = new FileInputStream(source); fic = fis.getChannel(); fos = new FileOutputStream(destination); foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); fos.flush(); fis.close(); fos.close(); } finally { WWIO.closeStream(fis, source.getPath()); WWIO.closeStream(fos, destination.getPath()); } }
00
Code Sample 1: public InputStream sendGetMessage(Properties args) throws IOException { String argString = ""; if (args != null) { argString = "?" + toEncodedString(args); } URL url = new URL(servlet.toExternalForm() + argString); URLConnection con = url.openConnection(); con.setUseCaches(false); sendHeaders(con); return con.getInputStream(); } Code Sample 2: public void parseFile(String filespec, URL documentBase) { DataInputStream in = null; if (filespec == null || filespec.length() == 0) { in = new DataInputStream(System.in); } else { try { URL url = null; if (documentBase == null && _documentBase != null) { documentBase = _documentBase; } if (documentBase == null) { url = new URL(filespec); } else { try { url = new URL(documentBase, filespec); } catch (NullPointerException e) { url = new URL(filespec); } } in = new DataInputStream(url.openStream()); } catch (MalformedURLException e) { try { in = new DataInputStream(new FileInputStream(filespec)); } catch (FileNotFoundException me) { _errorMsg = new String[2]; _errorMsg[0] = "File not found: " + filespec; _errorMsg[1] = me.getMessage(); return; } catch (SecurityException me) { _errorMsg = new String[2]; _errorMsg[0] = "Security Exception: " + filespec; _errorMsg[1] = me.getMessage(); return; } } catch (IOException ioe) { _errorMsg = new String[3]; _errorMsg[0] = "Failure opening URL: "; _errorMsg[1] = " " + filespec; _errorMsg[2] = ioe.getMessage(); return; } } try { BufferedReader din = new BufferedReader(new InputStreamReader(in)); String line = din.readLine(); while (line != null) { _parseLine(line); line = din.readLine(); } } catch (MalformedURLException e) { _errorMsg = new String[2]; _errorMsg[0] = "Malformed URL: " + filespec; _errorMsg[1] = e.getMessage(); return; } catch (IOException e) { _errorMsg = new String[2]; _errorMsg[0] = "Failure reading data: " + filespec; _errorMsg[1] = e.getMessage(); _errorMsg[1] = e.getMessage(); } finally { try { in.close(); } catch (IOException me) { } } }
11
Code Sample 1: private void internalTransferComplete(File tmpfile) { System.out.println("transferComplete : " + tmpfile); try { File old = new File(m_destination.toString() + ".old"); old.delete(); File current = m_destination; current.renameTo(old); FileInputStream fis = new FileInputStream(tmpfile); FileOutputStream fos = new FileOutputStream(m_destination); BufferedInputStream in = new BufferedInputStream(fis); BufferedOutputStream out = new BufferedOutputStream(fos); for (int read = in.read(); read != -1; read = in.read()) { out.write(read); } out.flush(); in.close(); out.close(); fis.close(); fos.close(); tmpfile.delete(); setVisible(false); transferComplete(); } catch (Exception exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(this, "An error occurred while downloading!", "ACLocator Error", JOptionPane.ERROR_MESSAGE); } } Code Sample 2: public static void copy(String source, String destination) { FileReader in = null; FileWriter out = null; try { File inputFile = new File(source); File outputFile = new File(destination); in = new FileReader(inputFile); out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } }
00
Code Sample 1: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { URL url = new URL(upgradeURL); InputStream in = url.openStream(); BufferedInputStream buffIn = new BufferedInputStream(in); FileOutputStream out = new FileOutputStream(""); String bytes = ""; int data = buffIn.read(); int downloadedByteCount = 1; while (data != -1) { out.write(data); bytes.concat(Character.toString((char) data)); buffIn.read(); downloadedByteCount++; updateProgressBar(downloadedByteCount); } out.close(); buffIn.close(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(bytes.getBytes()); String hash = m.digest().toString(); if (hash.length() == 31) { hash = "0" + hash; } if (!hash.equalsIgnoreCase(md5Hash)) { } } catch (MalformedURLException e) { } catch (IOException io) { } catch (NoSuchAlgorithmException a) { } } Code Sample 2: @Override public synchronized File download_dictionary(Dictionary dict, String localfpath) { abort = false; try { URL dictionary_location = new URL(dict.getLocation()); InputStream in = dictionary_location.openStream(); FileOutputStream w = new FileOutputStream(local_cache, false); int b = 0; while ((b = in.read()) != -1) { w.write(b); if (abort) throw new Exception("Download Aborted"); } in.close(); w.close(); File lf = new File(localfpath); FileInputStream r = new FileInputStream(local_cache); FileOutputStream fw = new FileOutputStream(lf); int c; while ((c = r.read()) != -1) fw.write(c); r.close(); fw.close(); clearCache(); return lf; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidTupleOperationException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } clearCache(); return null; }
11
Code Sample 1: public void setPage(String url) { System.out.println("SetPage(" + url + ")"); if (url != null) { if (!url.startsWith("http://")) { url = "http://" + url; } boolean exists = false; for (int i = 0; i < urlComboBox.getItemCount(); i++) { if (((String) urlComboBox.getItemAt(i)).equals(url)) { exists = true; urlComboBox.setSelectedItem(url); } } if (!exists) { int i = urlComboBox.getSelectedIndex(); if (i == -1 || urlComboBox.getItemCount() == 0) { i = 0; } else { i++; } urlComboBox.insertItemAt(url, i); urlComboBox.setSelectedItem(url); } boolean image = false; for (final String element : imageExtensions) { if (url.endsWith(element)) { image = true; } } try { if (image) { final String html = "<html><img src=\"" + url + "\"></html>"; } else { final String furl = url; Runnable loadPage = new Runnable() { public void run() { try { System.out.println("Setting page on Cobra"); SimpleHtmlRendererContext rendererContext = new SimpleHtmlRendererContext(htmlPanel, new SimpleUserAgentContext()); int nodeBaseEnd = furl.indexOf("/", 10); if (nodeBaseEnd == -1) nodeBaseEnd = furl.length(); String nodeBase = furl.substring(0, nodeBaseEnd); InputStream pageStream = new URL(furl).openStream(); BufferedReader pageStreamReader = new BufferedReader(new InputStreamReader(pageStream)); String pageContent = ""; String line; while ((line = pageStreamReader.readLine()) != null) pageContent += line; pageContent = borderImages(pageContent, nodeBase); htmlPanel.setHtml(pageContent, furl, rendererContext); } catch (Exception e) { System.out.println("Error loading page " + furl + " : " + e); } } }; new Thread(loadPage).start(); } } catch (final Throwable exception) { System.out.println("Error in Browser.setPage(): " + exception); } } } Code Sample 2: public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
11
Code Sample 1: public void copy(File from, String to) throws SystemException { assert from != null; File dst = new File(folder, to); dst.getParentFile().mkdirs(); FileChannel in = null; FileChannel out = null; try { if (!dst.exists()) dst.createNewFile(); in = new FileInputStream(from).getChannel(); out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { throw new SystemException(e); } finally { try { if (in != null) in.close(); } catch (Exception e1) { } try { if (out != null) out.close(); } catch (Exception e1) { } } } Code Sample 2: 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; }
00
Code Sample 1: private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; } Code Sample 2: public void update() { if (!updatable) { Main.fenetre().erreur(Fenetre.OLD_VERSION); return; } try { Main.fenetre().update(); Element remoteRoot = new SAXBuilder().build(xml).getRootElement(); addPackages = new HashMap<Integer, PackageVersion>(); Iterator<?> iterElem = remoteRoot.getChildren().iterator(); while (iterElem.hasNext()) { PackageVersion pack = new PackageVersion((Element) iterElem.next()); addPackages.put(pack.id(), pack); } removePackages = new HashMap<Integer, PackageVersion>(); iterElem = root.getChildren("package").iterator(); while (iterElem.hasNext()) { PackageVersion pack = new PackageVersion((Element) iterElem.next()); int id = pack.id(); if (!addPackages.containsKey(id)) { removePackages.put(id, pack); } else if (addPackages.get(id).version().equals(pack.version())) { addPackages.remove(id); } else { addPackages.get(id).ecrase(); } } Iterator<PackageVersion> iterPack = addPackages.values().iterator(); while (iterPack.hasNext()) { install(iterPack.next()); } iterPack = removePackages.values().iterator(); while (iterPack.hasNext()) { remove(iterPack.next()); } if (offline) { Runtime.getRuntime().addShutdownHook(new AddPackage(xml, "versions.xml")); Main.fenetre().erreur(Fenetre.UPDATE_TERMINE_RESTART); } else { File oldXML = new File("versions.xml"); oldXML.delete(); oldXML.createNewFile(); FileChannel out = new FileOutputStream(oldXML).getChannel(); FileChannel in = new FileInputStream(xml).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); xml.delete(); if (restart) { Main.fenetre().erreur(Fenetre.UPDATE_TERMINE_RESTART); } else { Main.updateVersion(); } } } catch (Exception e) { Main.fenetre().erreur(Fenetre.ERREUR_UPDATE, e); } }
11
Code Sample 1: public void testReaderWriterUC2() throws Exception { String inFile = "test_data/mri.png"; String outFile = "test_output/mri__smooth_testReaderWriter.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); } Code Sample 2: public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
00
Code Sample 1: private static String getData(String myurl) throws Exception { System.out.println("getdata"); URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { System.out.println(temp); k += temp; } br.close(); return k; } Code Sample 2: public void downloadFtpFile(SynchrnServerVO synchrnServerVO, String fileNm) throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("euc-kr"); if (!EgovWebUtil.isIPAddress(synchrnServerVO.getServerIp())) { throw new RuntimeException("IP is needed. (" + synchrnServerVO.getServerIp() + ")"); } InetAddress host = InetAddress.getByName(synchrnServerVO.getServerIp()); ftpClient.connect(host, Integer.parseInt(synchrnServerVO.getServerPort())); ftpClient.login(synchrnServerVO.getFtpId(), synchrnServerVO.getFtpPassword()); ftpClient.changeWorkingDirectory(synchrnServerVO.getSynchrnLc()); File downFile = new File(EgovWebUtil.filePathBlackList(synchrnServerVO.getFilePath() + fileNm)); OutputStream outputStream = null; try { outputStream = new FileOutputStream(downFile); ftpClient.retrieveFile(fileNm, outputStream); } catch (Exception e) { System.out.println(e); } finally { if (outputStream != null) outputStream.close(); } ftpClient.logout(); }
00
Code Sample 1: public boolean createUser(String username, String password, String name) throws Exception { boolean user_created = false; try { statement = connect.prepareStatement("SELECT COUNT(*) from toepen.users WHERE username = ? LIMIT 1"); statement.setString(1, username); resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); long ctime = System.currentTimeMillis() / 1000; statement = connect.prepareStatement("INSERT INTO toepen.users " + "(username, password, name, ctime) " + "VALUES (?, ?, ?, ?)"); statement.setString(1, username); statement.setString(2, password_hash); statement.setString(3, name); statement.setLong(4, ctime); if (statement.executeUpdate() > 0) { user_created = true; } } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_created; } } Code Sample 2: 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(); }
00
Code Sample 1: public void storeModule(OWLModuleManager manager, Module module, URI physicalURI, OWLModuleFormat moduleFormat) throws ModuleStorageException, UnknownModuleException { try { OutputStream os; if (!physicalURI.isAbsolute()) { throw new ModuleStorageException("Physical URI must be absolute: " + physicalURI); } if (physicalURI.getScheme().equals("file")) { File file = new File(physicalURI); file.getParentFile().mkdirs(); os = new FileOutputStream(file); } else { URL url = physicalURI.toURL(); URLConnection conn = url.openConnection(); os = conn.getOutputStream(); } Writer w = new BufferedWriter(new OutputStreamWriter(os)); storeModule(manager, module, w, moduleFormat); } catch (IOException e) { throw new ModuleStorageException(e); } } Code Sample 2: int doOne(int bid, int tid, int aid, int delta) { int aBalance = 0; if (Conn == null) { incrementFailedTransactionCount(); return 0; } try { if (prepared_stmt) { pstmt1.setInt(1, delta); pstmt1.setInt(2, aid); pstmt1.executeUpdate(); pstmt1.clearWarnings(); pstmt2.setInt(1, aid); ResultSet RS = pstmt2.executeQuery(); pstmt2.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } pstmt3.setInt(1, delta); pstmt3.setInt(2, tid); pstmt3.executeUpdate(); pstmt3.clearWarnings(); pstmt4.setInt(1, delta); pstmt4.setInt(2, bid); pstmt4.executeUpdate(); pstmt4.clearWarnings(); pstmt5.setInt(1, tid); pstmt5.setInt(2, bid); pstmt5.setInt(3, aid); pstmt5.setInt(4, delta); pstmt5.executeUpdate(); pstmt5.clearWarnings(); } else { Statement Stmt = Conn.createStatement(); String Query = "UPDATE accounts "; Query += "SET Abalance = Abalance + " + delta + " "; Query += "WHERE Aid = " + aid; int res = Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "SELECT Abalance "; Query += "FROM accounts "; Query += "WHERE Aid = " + aid; ResultSet RS = Stmt.executeQuery(Query); Stmt.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } Query = "UPDATE tellers "; Query += "SET Tbalance = Tbalance + " + delta + " "; Query += "WHERE Tid = " + tid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "UPDATE branches "; Query += "SET Bbalance = Bbalance + " + delta + " "; Query += "WHERE Bid = " + bid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "INSERT INTO history(Tid, Bid, Aid, delta) "; Query += "VALUES ("; Query += tid + ","; Query += bid + ","; Query += aid + ","; Query += delta + ")"; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Stmt.close(); } if (transactions) { Conn.commit(); } return aBalance; } catch (Exception E) { if (verbose) { System.out.println("Transaction failed: " + E.getMessage()); E.printStackTrace(); } incrementFailedTransactionCount(); if (transactions) { try { Conn.rollback(); } catch (SQLException E1) { } } } return 0; }
00
Code Sample 1: public static void main(String[] args) throws IOException { InputStream stream = null; FileOutputStream fos = null; File in = new File("in.txt"); try { URL url = new URL(args[0]); stream = url.openStream(); fos = new FileOutputStream(in); int i; while ((i = stream.read()) != -1) { fos.write(i); } fos.flush(); fos.close(); new FileRunner(in, new File("out.txt")).run(); FileReader reader = new FileReader("out.txt"); System.out.println(reader.toString()); } finally { if (stream != null) stream.close(); } } Code Sample 2: public static void copyFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: protected void zipFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(to)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } Code Sample 2: @Override public void parse() throws DocumentException, IOException { URL url = new URL(this.XMLAddress); URLConnection con = url.openConnection(); BufferedReader bStream = new BufferedReader(new InputStreamReader(con.getInputStream())); String str; bStream.readLine(); while ((str = bStream.readLine()) != null) { String[] tokens = str.split("(\\s+)"); String charCode = tokens[0].replaceAll("([0-9+])", ""); Float value = Float.parseFloat(tokens[2].trim().replace(",", ".")); ResultUnit unit = new ResultUnit(charCode, value, DEFAULT_MULTIPLIER); this.set.add(unit); } }
00
Code Sample 1: @Override public void run() { handle.start(); handle.switchToIndeterminate(); FacebookJsonRestClient client = new FacebookJsonRestClient(API_KEY, SECRET); client.setIsDesktop(true); HttpURLConnection connection; List<String> cookies; try { String token = client.auth_createToken(); String post_url = "http://www.facebook.com/login.php"; String get_url = "http://www.facebook.com/login.php" + "?api_key=" + API_KEY + "&v=1.0" + "&auth_token=" + token; HttpURLConnection.setFollowRedirects(true); connection = (HttpURLConnection) new URL(get_url).openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); connection.connect(); cookies = connection.getHeaderFields().get("Set-Cookie"); connection = (HttpURLConnection) new URL(post_url).openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); connection.setRequestProperty("Host", "www.facebook.com"); connection.setRequestProperty("Accept-Charset", "UFT-8"); if (cookies != null) { for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } } String params = "api_key=" + API_KEY + "&auth_token=" + token + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pass=" + URLEncoder.encode(pass, "UTF-8") + "&v=1.0"; connection.setRequestProperty("Content-Length", Integer.toString(params.length())); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); connection.connect(); connection.getOutputStream().write(params.toString().getBytes("UTF-8")); connection.getOutputStream().close(); cookies = connection.getHeaderFields().get("Set-Cookie"); if (cookies == null) { ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String url = "http://www.chartsy.org/facebook/"; DesktopUtil.browseAndWarn(url, null); } }; NotifyUtil.show("Application Permission", "You need to grant permission first.", MessageType.WARNING, listener, false); connection.disconnect(); loggedIn = false; } else { sessionKey = client.auth_getSession(token); sessionSecret = client.getSessionSecret(); loggedIn = true; } connection.disconnect(); handle.finish(); } catch (FacebookException fex) { handle.finish(); NotifyUtil.error("Login Error", fex.getMessage(), fex, false); } catch (IOException ioex) { handle.finish(); NotifyUtil.error("Login Error", ioex.getMessage(), ioex, false); } } Code Sample 2: public void deleteScript(Integer id) { InputStream is = null; try { URL url = new URL(strServlet + getSessionIDSuffix() + "?deleteScript=" + id); System.out.println("requesting: " + url); is = url.openStream(); while (is.read() != -1) ; } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); } catch (Exception e) { } } }
11
Code Sample 1: public void transport(File file) throws TransportException { if (file.exists()) { if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { transport(file); } } else if (file.isFile()) { try { FileChannel inChannel = new FileInputStream(file).getChannel(); FileChannel outChannel = new FileOutputStream(getOption("destination")).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { log.error("File transfer failed", e); } } } } Code Sample 2: public static void copy(File _from, File _to) throws IOException { if (_from == null || !_from.exists()) return; FileOutputStream out = null; FileInputStream in = null; try { out = new FileOutputStream(_to); in = new FileInputStream(_from); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } } catch (IOException _e) { throw _e; } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: private static void checkForUpgrade() { try { Log.out("Checking for updates..."); URL u = ClassLoader.getSystemResource(Settings.readme); if (u == null) { u = HImage.class.getResource("/" + Settings.readme); } DataInputStream i = new DataInputStream(u.openStream()); String tmp = i.readLine(); tmp = tmp.substring(tmp.lastIndexOf(">")); tmp = tmp.substring(tmp.indexOf(".") + 1); tmp = tmp.substring(0, tmp.indexOf("<")); int x = Integer.parseInt(tmp) + 1; String nextVersion = "jftp-1."; if (x < 10) { nextVersion = nextVersion + "0"; } nextVersion = nextVersion + x + ".tar.gz"; File dl = new File(nextVersion); if (!dl.exists() || (dl.length() <= 0)) { URL url = new URL("http://osdn.dl.sourceforge.net/sourceforge/j-ftp/" + nextVersion); BufferedOutputStream f = new BufferedOutputStream(new FileOutputStream(dl)); BufferedInputStream in = new BufferedInputStream(url.openStream()); byte[] buf = new byte[4096]; int stat = 1; Log.out("\ndownloading update: " + dl.getAbsolutePath() + "\n\n"); while (stat > 0) { stat = in.read(buf); if (stat == -1) { break; } f.write(buf, 0, stat); System.out.print("."); } f.flush(); f.close(); in.close(); } Log.out("\n\n\na newer version was found!\nplease install the File " + dl.getAbsolutePath() + " or even better visit the homepage to download the latest version...\n" + "you can turn this feature off if you don't like it (view readme for details)\n\nStarting anyway...\n\n"); } catch (Exception ex) { } Log.out("finished check..."); } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
11
Code Sample 1: private void sendMessages() { Configuration conf = Configuration.getInstance(); for (int i = 0; i < errors.size(); i++) { String msg = null; synchronized (this) { msg = errors.get(i); if (DEBUG) System.out.println(msg); errors.remove(i); } if (!conf.getCustomerFeedback()) continue; if (conf.getApproveCustomerFeedback()) { ConfirmCustomerFeedback dialog = new ConfirmCustomerFeedback(JOptionPane.getFrameForComponent(SqlTablet.getInstance()), msg); if (dialog.getResult() == ConfirmCustomerFeedback.Result.NO) continue; } try { URL url = new URL("http://www.sqltablet.com/beta/bug.php"); URLConnection urlc = url.openConnection(); urlc.setDoOutput(true); urlc.setDoOutput(true); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(urlc.getOutputStream()); String lines[] = msg.split("\n"); for (int l = 0; l < lines.length; l++) { String line = (l > 0 ? "&line" : "line") + l + "="; line += URLEncoder.encode(lines[l], "UTF-8"); out.write(line.getBytes()); } out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String line; while ((line = in.readLine()) != null) { if (DEBUG) System.out.println("RemoteLogger : " + line + "\n"); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: private static void updateLeapSeconds() throws IOException, MalformedURLException, NumberFormatException { URL url = new URL("http://cdf.gsfc.nasa.gov/html/CDFLeapSeconds.txt"); InputStream in; try { in = url.openStream(); } catch (IOException ex) { url = LeapSecondsConverter.class.getResource("CDFLeapSeconds.txt"); in = url.openStream(); System.err.println("Using local copy of leap seconds!!!"); } BufferedReader r = new BufferedReader(new InputStreamReader(in)); String s = ""; leapSeconds = new ArrayList(50); withoutLeapSeconds = new ArrayList(50); String lastLine = s; while (s != null) { s = r.readLine(); if (s == null) { System.err.println("Last leap second read from " + url + " " + lastLine); continue; } if (s.startsWith(";")) { continue; } String[] ss = s.trim().split("\\s+", -2); if (ss[0].compareTo("1972") < 0) { continue; } int iyear = Integer.parseInt(ss[0]); int imonth = Integer.parseInt(ss[1]); int iday = Integer.parseInt(ss[2]); int ileap = (int) (Double.parseDouble(ss[3])); double us2000 = TimeUtil.createTimeDatum(iyear, imonth, iday, 0, 0, 0, 0).doubleValue(Units.us2000); leapSeconds.add(Long.valueOf(((long) us2000) * 1000L - 43200000000000L + (long) (ileap - 32) * 1000000000)); withoutLeapSeconds.add(us2000); } leapSeconds.add(Long.MAX_VALUE); withoutLeapSeconds.add(Double.MAX_VALUE); lastUpdateMillis = System.currentTimeMillis(); }
11
Code Sample 1: public static String getDigest(String user, String realm, String password, String method, String uri, String nonce, String nc, String cnonce, String qop) { String digest1 = user + ":" + realm + ":" + password; String digest2 = method + ":" + uri; try { MessageDigest digestOne = MessageDigest.getInstance("md5"); digestOne.update(digest1.getBytes()); String hexDigestOne = getHexString(digestOne.digest()); MessageDigest digestTwo = MessageDigest.getInstance("md5"); digestTwo.update(digest2.getBytes()); String hexDigestTwo = getHexString(digestTwo.digest()); String digest3 = hexDigestOne + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + hexDigestTwo; MessageDigest digestThree = MessageDigest.getInstance("md5"); digestThree.update(digest3.getBytes()); String hexDigestThree = getHexString(digestThree.digest()); return hexDigestThree; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: @Override protected AuthenticationHandlerResponse authenticateInternal(final Connection c, final AuthenticationCriteria criteria) throws LdapException { byte[] hash; try { final MessageDigest md = MessageDigest.getInstance(passwordScheme); md.update(criteria.getCredential().getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new LdapException(e); } final LdapAttribute la = new LdapAttribute("userPassword", String.format("{%s}%s", passwordScheme, LdapUtils.base64Encode(hash)).getBytes()); final CompareOperation compare = new CompareOperation(c); final CompareRequest request = new CompareRequest(criteria.getDn(), la); request.setControls(getAuthenticationControls()); final Response<Boolean> compareResponse = compare.execute(request); return new AuthenticationHandlerResponse(compareResponse.getResult(), compareResponse.getResultCode(), c, compareResponse.getMessage(), compareResponse.getControls()); }
00
Code Sample 1: public static void find(String pckgname, Class tosubclass) { String name = new String(pckgname); if (!name.startsWith("/")) { name = "/" + name; } name = name.replace('.', '/'); URL url = RTSI.class.getResource(name); System.out.println(name + "->" + url); if (url == null) return; File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Object o = Class.forName(pckgname + "." + classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); String starts = conn.getEntryName(); JarFile jfile = conn.getJarFile(); Enumeration e = jfile.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { Object o = Class.forName(classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname.substring(classname.lastIndexOf('.') + 1)); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } catch (IOException ioex) { System.err.println(ioex); } } } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
00
Code Sample 1: public static void unzipAndRemove(final String file) { String destination = file.substring(0, file.length() - 3); InputStream is = null; OutputStream os = null; try { is = new GZIPInputStream(new FileInputStream(file)); os = new FileOutputStream(destination); byte[] buffer = new byte[8192]; for (int length; (length = is.read(buffer)) != -1; ) os.write(buffer, 0, length); } catch (IOException e) { System.err.println("Fehler: Kann nicht entpacken " + file); } finally { if (os != null) try { os.close(); } catch (IOException e) { } if (is != null) try { is.close(); } catch (IOException e) { } } deleteFile(file); } Code Sample 2: public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; }
11
Code Sample 1: public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } Code Sample 2: 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()); }
00
Code Sample 1: private static String loadUrlToString(String a_url) throws IOException { URL l_url1 = new URL(a_url); BufferedReader br = new BufferedReader(new InputStreamReader(l_url1.openStream())); String l_content = ""; String l_ligne = null; l_content = br.readLine(); while ((l_ligne = br.readLine()) != null) { l_content += AA.SL + l_ligne; } return l_content; } Code Sample 2: PasswordTableWindow(String login) { super(login + ", tecle a senha de uso �nico"); this.login = login; Error.log(4001, "Autentica��o etapa 3 iniciada."); Container container = getContentPane(); container.setLayout(new FlowLayout()); btnNumber = new JButton[10]; btnOK = new JButton("OK"); btnClear = new JButton("Limpar"); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(2, 10)); ResultSet rs; Statement stmt; String sql; Vector<Integer> result = new Vector<Integer>(); sql = "select key from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result.add(rs.getInt("key")); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r = rn.nextInt(); if (result.size() == 0) { rn = new Random(); Vector<Integer> passwordVector = new Vector<Integer>(); Vector<String> hashVector = new Vector<String>(); for (int i = 0; i < 10; i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < 10; i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < 10; i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } JOptionPane.showMessageDialog(null, "nova tabela de senhas criada para o usu�rio " + login + "."); Error.log(1002, "Sistema encerrado"); System.exit(0); } if (r < 0) r = r * (-1); int index = r % result.size(); if (index > result.size()) index = 0; key = result.get(index); labelKey = new JLabel("Chave n�mero " + key + " "); passwordField = new JPasswordField(12); ButtonHandler handler = new ButtonHandler(); for (int i = 0; i < 10; i++) { btnNumber[i] = new JButton("" + i); buttonPanel.add(btnNumber[i]); btnNumber[i].addActionListener(handler); } btnOK.addActionListener(handler); btnClear.addActionListener(handler); container.add(buttonPanel); container.add(passwordField); container.add(labelKey); container.add(btnOK); container.add(btnClear); setSize(325, 200); setVisible(true); }
11
Code Sample 1: public void testLocalUserAccountLocalRemoteRoles() throws SQLException { Statement st = null; Connection authedCon = null; try { saSt.executeUpdate("CREATE USER tlualrr PASSWORD 'wontuse'"); saSt.executeUpdate("GRANT role3 TO tlualrr"); saSt.executeUpdate("GRANT role4 TO tlualrr"); saSt.executeUpdate("SET DATABASE AUTHENTICATION FUNCTION EXTERNAL NAME " + "'CLASSPATH:" + getClass().getName() + ".twoRolesFn'"); try { authedCon = DriverManager.getConnection(jdbcUrl, "TLUALRR", "unusedPassword"); } catch (SQLException se) { fail("Access with 'twoRolesFn' failed"); } st = authedCon.createStatement(); assertFalse("Positive test #1 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t1 VALUES(1)")); assertFalse("Positive test #2 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t2 VALUES(2)")); assertTrue("Negative test #3 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t3 VALUES(3)")); assertTrue("Negative test #4 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t4 VALUES(4)")); assertEquals(twoRolesSet, AuthUtils.getEnabledRoles(authedCon)); } finally { if (st != null) try { st.close(); } catch (SQLException se) { logger.error("Close of Statement failed:" + se); } finally { st = null; } if (authedCon != null) try { authedCon.rollback(); authedCon.close(); } catch (SQLException se) { logger.error("Close of Authed Conn. failed:" + se); } finally { authedCon = null; } } } Code Sample 2: void execute(Connection conn, Component parent, String context, final ProgressMonitor progressMonitor, ProgressWrapper progressWrapper) throws Exception { int noOfComponents = m_components.length; Statement statement = null; StringBuffer pmNoteBuf = new StringBuffer(m_update ? "Updating " : "Creating "); pmNoteBuf.append(m_itemNameAbbrev); pmNoteBuf.append(" "); pmNoteBuf.append(m_itemNameValue); final String pmNote = pmNoteBuf.toString(); progressMonitor.setNote(pmNote); try { conn.setAutoCommit(false); int id = -1; if (m_update) { statement = conn.createStatement(); String sql = getUpdateSql(noOfComponents, m_id); statement.executeUpdate(sql); id = m_id; if (m_indexesChanged) deleteComponents(conn, id); } else { PreparedStatement pStmt = getInsertPrepStmt(conn, noOfComponents); pStmt.executeUpdate(); Integer res = DbCommon.getAutoGenId(parent, context, pStmt); if (res == null) return; id = res.intValue(); } if (!m_update || m_indexesChanged) { PreparedStatement insertCompPrepStmt = conn.prepareStatement(getInsertComponentPrepStmtSql()); for (int i = 0; i < noOfComponents; i++) { createComponent(progressMonitor, m_components, pmNote, id, i, insertCompPrepStmt); } } conn.commit(); m_itemTable.getPrimaryId().setVal(m_item, id); m_itemCache.updateCache(m_item, id); } catch (SQLException ex) { try { conn.rollback(); } catch (SQLException e) { e.printStackTrace(); } throw ex; } finally { if (statement != null) { statement.close(); } } }
00
Code Sample 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(); } } Code Sample 2: private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; }
00
Code Sample 1: public void run() { try { URL url = new URL("http://localhost:8080/WebGISTileServer/index.jsp?token_timeout=true"); URLConnection uc = url.openConnection(); uc.addRequestProperty("Referer", "http://localhost:8080/index.jsp"); BufferedReader rd = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line; while ((line = rd.readLine()) != null) System.out.println(line); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version_" + datastream + ".xml\""); } ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { StringBuffer sb = new StringBuffer(); if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/objectXML"); } else if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/").append(datastream).append("/content"); } InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { os.write(Constants.XML_HEADER_WITH_BACKSLASHES.getBytes()); } IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { is = null; } } } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); } } }
00
Code Sample 1: private File getDvdDataFileFromWeb() throws IOException { System.out.println("Downloading " + dvdCsvFileUrl); URL url = new URL(dvdCsvFileUrl); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(dvdCsvZipFileName); writeFromTo(in, out); System.out.println("Extracting " + dvdCsvFileName + " from " + dvdCsvZipFileName); File dvdZipFile = new File(dvdCsvZipFileName); File dvdCsvFile = new File(dvdCsvFileName); ZipFile zipFile = new ZipFile(dvdZipFile); ZipEntry zipEntry = zipFile.getEntry(dvdCsvFileName); FileOutputStream os = new FileOutputStream(dvdCsvFile); InputStream is = zipFile.getInputStream(zipEntry); writeFromTo(is, os); System.out.println("Deleting zip file"); dvdZipFile.delete(); System.out.println("Dvd csv file download complete"); return dvdCsvFile; } Code Sample 2: public static String unsecureHashConstantSalt(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT3 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT4; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
11
Code Sample 1: public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String dest1 = dest.getAbsolutePath() + File.separatorChar + list[i]; String src1 = src.getAbsolutePath() + File.separatorChar + list[i]; copyFiles(src1, dest1); } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } } Code Sample 2: public static File copyFile(File fileToCopy, File copiedFile) { BufferedInputStream in = null; BufferedOutputStream outWriter = null; if (!copiedFile.exists()) { try { copiedFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); return null; } } try { in = new BufferedInputStream(new FileInputStream(fileToCopy), 4096); outWriter = new BufferedOutputStream(new FileOutputStream(copiedFile), 4096); int c; while ((c = in.read()) != -1) outWriter.write(c); in.close(); outWriter.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } return copiedFile; }
11
Code Sample 1: public static String getMD5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes("ISO8859_1")); byte[] md5 = algorithm.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 (Exception ex) { } return res; } Code Sample 2: public static String encryptPassword(String password) throws PasswordException { String hash = null; if (password != null && !password.equals("")) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = String.valueOf(Base64Coder.encode(raw)); } catch (NoSuchAlgorithmException nsae) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } catch (UnsupportedEncodingException uee) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } } return hash; }
11
Code Sample 1: public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } Code Sample 2: public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); }
11
Code Sample 1: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public static boolean copy(File src, FileSystem dstFS, Path dst, boolean deleteSource, Configuration conf) throws IOException { dst = checkDest(src.getName(), dstFS, dst, false); if (src.isDirectory()) { if (!dstFS.mkdirs(dst)) { return false; } File contents[] = src.listFiles(); for (int i = 0; i < contents.length; i++) { copy(contents[i], dstFS, new Path(dst, contents[i].getName()), deleteSource, conf); } } else if (src.isFile()) { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = dstFS.create(dst); IOUtils.copyBytes(in, out, conf); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } if (deleteSource) { return FileUtil.fullyDelete(src); } else { return true; } }
00
Code Sample 1: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (doAuth(request, response)) { Connection conn = null; try { int UID = icsm.getIntChatSession(request).getUID(); conn = getJDBCConnection(icsm.getHeavyDatabaseConnectionPool(), request, response, HttpServletResponse.SC_SERVICE_UNAVAILABLE); if (conn == null) return; ResultSet rs = IntChatDatabaseOperations.executeQuery(conn, "SELECT id FROM ic_messagetypes WHERE templatename='" + IntChatConstants.MessageTemplates.IC_FILES + "' LIMIT 1"); if (rs.next()) { int fileTypeID = rs.getInt("id"); String recipients = request.getHeader(IntChatConstants.HEADER_FILERECIPIENTS); rs.getStatement().close(); rs = null; if (recipients != null) { HashMap<String, String> hm = Tools.parseMultiparamLine(request.getHeader("Content-Disposition")); String fileName = URLDecoder.decode(hm.get("filename"), IntChatServerDefaults.ENCODING); long fileLength = (request.getHeader("Content-Length") != null ? Long.parseLong(request.getHeader("Content-Length")) : -1); fileLength = (request.getHeader(IntChatConstants.HEADER_FILELENGTH) != null ? Long.parseLong(request.getHeader(IntChatConstants.HEADER_FILELENGTH)) : fileLength); long maxFileSize = RuntimeParameters.getIntValue(ParameterNames.MAX_FILE_SIZE) * 1048576; if (maxFileSize > 0 && fileLength > maxFileSize) { request.getInputStream().close(); response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); return; } long now = System.currentTimeMillis(); long nextid = ic_messages_id_seq.nextval(); IntChatServletInputStream in = new IntChatServletInputStream(request); IntChatMessage icm = null; conn.setAutoCommit(false); try { PreparedStatement ps = conn.prepareStatement("INSERT INTO ic_messages (id, tid, mhead, mbody, mdate, sid) VALUES (?, ?, ?, ?, ?, ?)"); ps.setLong(1, nextid); ps.setInt(2, fileTypeID); ps.setString(3, fileName); ps.setString(4, Long.toString(fileLength)); ps.setLong(5, now); ps.setInt(6, UID); ps.executeUpdate(); ps.close(); if (!insertBLOB(conn, in, fileLength, nextid, maxFileSize)) { conn.rollback(); return; } icm = new IntChatMessage(false, fileTypeID, null, null); String[] id = recipients.split(","); int id1; for (int i = 0; i < id.length; i++) { id1 = Integer.parseInt(id[i].trim()); IntChatDatabaseOperations.executeUpdate(conn, "INSERT INTO ic_recipients (mid, rid) VALUES ('" + nextid + "', '" + id1 + "')"); icm.addTo(id1); } conn.commit(); } catch (Exception e) { conn.rollback(); throw e; } finally { conn.setAutoCommit(true); } if (icm != null) { icm.setID(nextid); icm.setDate(new Timestamp(now - TimeZone.getDefault().getOffset(now))); icm.setFrom(UID); icm.setHeadText(fileName); icm.setBodyText(Long.toString(fileLength)); icsm.onClientSentMessage(icm); } response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } if (rs != null) { rs.getStatement().close(); rs = null; } } catch (RetryRequest rr) { throw rr; } catch (Exception e) { Tools.makeErrorResponse(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } finally { try { if (conn != null) icsm.getHeavyDatabaseConnectionPool().releaseConnection(conn); } catch (Exception e) { } } } } Code Sample 2: public boolean check(Object credentials) { String password = (credentials instanceof String) ? (String) credentials : credentials.toString(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] ha1; if (credentials instanceof Credential.MD5) { ha1 = ((Credential.MD5) credentials).getDigest(); } else { md.update(username.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(realm.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(password.getBytes(StringUtil.__ISO_8859_1)); ha1 = md.digest(); } md.reset(); md.update(method.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(uri.getBytes(StringUtil.__ISO_8859_1)); byte[] ha2 = md.digest(); md.update(TypeUtil.toString(ha1, 16).getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(nonce.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(nc.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(cnonce.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(qop.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(TypeUtil.toString(ha2, 16).getBytes(StringUtil.__ISO_8859_1)); byte[] digest = md.digest(); return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response)); } catch (Exception e) { Log.warn(e); } return false; }
00
Code Sample 1: public void testConvert() throws IOException, ConverterException { InputStreamReader reader = new InputStreamReader(new FileInputStream("test" + File.separator + "input" + File.separator + "A0851ohneex.dat"), CharsetUtil.forName("x-PICA")); FileWriter writer = new FileWriter("test" + File.separator + "output" + File.separator + "ddbInterToMarcxmlTest.out"); Converter c = context.getConverter("ddb-intern", "MARC21-xml", "x-PICA", "UTF-8"); ConversionParameters params = new ConversionParameters(); params.setSourceCharset("x-PICA"); params.setTargetCharset("UTF-8"); params.setAddCollectionHeader(true); params.setAddCollectionFooter(true); c.convert(reader, writer, params); } Code Sample 2: public void generateListOfSubscriptions() { try { java.net.URL url = new java.net.URL(NewGenLibDesktopRoot.getInstance().getURLRoot() + "/NEWGEN_JR/ListOfSubscriptions.xml"); System.out.println(NewGenLibDesktopRoot.getRoot() + "/NEWGEN_JR/ListOfSubscriptions.xml"); net.sf.jasperreports.engine.design.JasperDesign jd = net.sf.jasperreports.engine.xml.JRXmlLoader.load(url.openStream()); System.out.println("in generate Report 30" + dtm.getRowCount()); net.sf.jasperreports.engine.JasperReport jr = net.sf.jasperreports.engine.JasperCompileManager.compileReport(jd); System.out.println("in generate Report 32" + dtm.getRowCount()); java.util.Map param = new java.util.HashMap(); param.put("ReportTitle", "List of subscriptions"); Class.forName("org.postgresql.Driver"); System.out.println("in generate Report 37" + dtm.getRowCount()); net.sf.jasperreports.engine.JasperPrint jp = net.sf.jasperreports.engine.JasperFillManager.fillReport(jr, param, new net.sf.jasperreports.engine.data.JRTableModelDataSource(dtm)); System.out.println("in generate Report 39" + dtm.getRowCount()); java.sql.Timestamp currentTime = new java.sql.Timestamp(java.util.Calendar.getInstance().getTimeInMillis()); if (jp.getPages().size() != 0) net.sf.jasperreports.view.JasperViewer.viewReport(jp, false); else javax.swing.JOptionPane.showMessageDialog(reports.DeskTopFrame.getInstance(), "There are no records in the selected report option."); System.out.println("in generate Report 43" + dtm.getRowCount()); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } } Code Sample 2: public void doImport(File f, boolean checkHosp) throws Exception { connector.getConnection().setAutoCommit(false); File base = f.getParentFile(); ZipInputStream in = new ZipInputStream(new FileInputStream(f)); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { String outFileName = entry.getName(); File outFile = new File(base, outFileName); OutputStream out = new FileOutputStream(outFile, false); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); } in.close(); importDirectory(base, checkHosp); connector.getConnection().commit(); }
00
Code Sample 1: public boolean isValid(WizardContext context) { if (serviceSelection < 0) { return false; } ServiceReference selection = (ServiceReference) serviceList.getElementAt(serviceSelection); if (selection == null) { return false; } String function = (String) context.getAttribute(ServiceWizard.ATTRIBUTE_FUNCTION); context.setAttribute(ServiceWizard.ATTRIBUTE_SERVICE_REFERENCE, selection); URL url = selection.getResourceURL(); InputStream inputStream = null; try { inputStream = url.openStream(); InputSource inputSource = new InputSource(inputStream); JdbcService service = ServiceDigester.parseService(inputSource, IsqlToolkit.getSharedEntityResolver()); context.setAttribute(ServiceWizard.ATTRIBUTE_SERVICE, service); return true; } catch (IOException error) { if (!ServiceWizard.FUNCTION_DELETE.equals(function)) { String loc = url.toExternalForm(); String message = messages.format("SelectServiceStep.failed_to_load_service_from_url", loc); context.showErrorDialog(error, message); } else { return true; } } catch (Exception error) { String message = messages.format("SelectServiceStep.service_load_error", url.toExternalForm()); context.showErrorDialog(error, message); } return false; } Code Sample 2: public static void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
00
Code Sample 1: public void testIntegrityViolation() throws Exception { if (getDialect() instanceof MySQLMyISAMDialect) { reportSkip("MySQL (ISAM) does not support FK violation checking", "exception conversion"); return; } SQLExceptionConverter converter = getDialect().buildSQLExceptionConverter(); Session session = openSession(); session.beginTransaction(); Connection connection = session.connection(); PreparedStatement ps = null; try { ps = connection.prepareStatement("INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)"); ps.setLong(1, 52134241); ps.setLong(2, 5342); ps.executeUpdate(); fail("INSERT should have failed"); } catch (SQLException sqle) { JDBCExceptionReporter.logExceptions(sqle, "Just output!!!!"); JDBCException jdbcException = converter.convert(sqle, null, null); assertEquals("Bad conversion [" + sqle.getMessage() + "]", ConstraintViolationException.class, jdbcException.getClass()); ConstraintViolationException ex = (ConstraintViolationException) jdbcException; System.out.println("Violated constraint name: " + ex.getConstraintName()); } finally { if (ps != null) { try { ps.close(); } catch (Throwable ignore) { } } } session.getTransaction().rollback(); session.close(); } Code Sample 2: private static URL downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } URL localURL = destFile.toURI().toURL(); return localURL; } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } }
11
Code Sample 1: public void reademi(Vector<String> descriptions, Vector<String> links, String linkaddress, String idmap) { InputStream is = null; URL url; ArrayList<String> keys = new ArrayList<String>(); ArrayList<String> names = new ArrayList<String>(); try { url = new URL(idmap); is = url.openStream(); Scanner scanner = new Scanner(is); scanner.nextLine(); String line = ""; String id = ""; while (scanner.hasNextLine()) { line = scanner.nextLine(); Scanner linescanner = new Scanner(line); linescanner.useDelimiter("\t"); id = linescanner.next(); id = id.substring(0, id.length() - 2); keys.add(id); linescanner.next(); linescanner.next(); linescanner.next(); linescanner.useDelimiter("\n"); names.add(linescanner.next()); } BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(linkaddress).openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; while ((line = reader.readLine()) != null) { if (line.indexOf("style=raw") != -1) { int linkstart = line.indexOf("http://www.ebi.ac.uk/cgi-bin/dbfetch?db"); int idstart = line.indexOf("id=") + 3; int linkend = line.substring(linkstart).indexOf("\"") + linkstart; link = line.substring(linkstart, linkend); key = line.substring(idstart, linkend); if (keys.indexOf(key) != -1) { name = names.get(keys.indexOf(key)); counter++; descriptions.add(counter + " " + key + " " + name); links.add(link); } } } } catch (MalformedURLException e) { } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private void sendToServer(String fichaID, String respostas) throws FileNotFoundException, ParserConfigurationException, SAXException, IOException, URISyntaxException { ArrayList params = new ArrayList(); params.add(new BasicNameValuePair("xml", respostas)); params.add(new BasicNameValuePair("idForm", fichaID)); URI uri = URIUtils.createURI("http", "172.20.9.144", 8080, "/PSFServer/SaveAnswers", URLEncodedUtils.format(params, "UTF-8"), null); HttpPost request = new HttpPost(uri); request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpClient client = new DefaultHttpClient(); HttpResponse httpResponse = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String resposta = sb.toString(); if (resposta != null || resposta != "") { new DatabaseManager(this).getWritableDatabase().execSQL("delete from " + DatabaseManager.getTableDados()); } backToMain(); }
11
Code Sample 1: public static Drawable fetchCachedDrawable(String url) throws MalformedURLException, IOException { Log.d(LOG_TAG, "Fetching cached : " + url); String cacheName = md5(url); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); if (!r.exists()) { InputStream is = (InputStream) fetch(url); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); Drawable d = Drawable.createFromStream(fis, "src"); return d; } Code Sample 2: private void _save(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(this, "Property File save Failed " + e, e); } } SessionMessages.add(req, "message", "message.languagemanager.save"); }
00
Code Sample 1: public void sorter() { String inputLine1, inputLine2; String epiNames[] = new String[1000]; String epiEpisodes[] = new String[1000]; int lineCounter = 0; try { String pluginDir = pluginInterface.getPluginDirectoryName(); String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt"; File episodeList = new File(eplist_file); if (!episodeList.isFile()) { episodeList.createNewFile(); } final BufferedReader in = new BufferedReader(new FileReader(episodeList)); while ((inputLine1 = in.readLine()) != null) { if ((inputLine2 = in.readLine()) != null) { epiNames[lineCounter] = inputLine1; epiEpisodes[lineCounter] = inputLine2; lineCounter++; } } in.close(); int epiLength = epiNames.length; for (int i = 0; i < (lineCounter); i++) { for (int j = 0; j < (lineCounter - 1); j++) { if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) { String temp = epiNames[j]; epiNames[j] = epiNames[j + 1]; epiNames[j + 1] = temp; String temp2 = epiEpisodes[j]; epiEpisodes[j] = epiEpisodes[j + 1]; epiEpisodes[j + 1] = temp2; } } } File episodeList2 = new File(eplist_file); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2)); for (int i = 0; i <= lineCounter; i++) { if (epiNames[i] == null) { break; } bufWriter.write(epiNames[i] + "\n"); bufWriter.write(epiEpisodes[i] + "\n"); } bufWriter.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private String addEqError(EquivalencyException e, int namespaceId) throws SQLException { List l = Arrays.asList(e.getListOfEqErrors()); int size = l.size(); String sql = getClassifyDAO().getStatement(TABLE_KEY, "ADD_CLASSIFY_EQ_ERROR"); PreparedStatement ps = null; conn.setAutoCommit(false); try { deleteCycleError(namespaceId); deleteEqError(namespaceId); long conceptGID1 = -1; long conceptGID2 = -1; ps = conn.prepareStatement(sql); for (int i = 0; i < l.size(); i++) { EqError error = (EqError) l.get(i); ConceptRef ref1 = error.getConcept1(); ConceptRef ref2 = error.getConcept2(); conceptGID1 = getConceptGID(ref1, namespaceId); conceptGID2 = getConceptGID(ref2, namespaceId); ps.setLong(1, conceptGID1); ps.setLong(2, conceptGID2); ps.setInt(3, namespaceId); int result = ps.executeUpdate(); if (result == 0) { throw new SQLException("unable to add eq error: " + sql); } } conn.commit(); return "EquivalencyException: Concept: " + conceptGID1 + " namespaceId: " + namespaceId + " conceptGID2: " + conceptGID2 + ((size > 1) ? "...... more" : ""); } catch (SQLException sqle) { conn.rollback(); throw sqle; } catch (Exception ex) { conn.rollback(); throw toSQLException(ex, "cannot add eq errors"); } finally { conn.setAutoCommit(true); if (ps != null) { ps.close(); } } }
00
Code Sample 1: public void setRandom(boolean random) { this.random = random; if (random) { possibleScores = new int[NUM_SCORES]; for (int i = 0; i < NUM_SCORES - 1; i++) { getRandomScore: while (true) { int score = (int) (Math.random() * 20) + 1; for (int j = 0; j < i; j++) { if (score == possibleScores[j]) { continue getRandomScore; } } possibleScores[i] = score; break; } } possibleScores[NUM_SCORES - 1] = 25; boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < NUM_SCORES - 1; i++) { if (possibleScores[i] > possibleScores[i + 1]) { int t = possibleScores[i]; possibleScores[i] = possibleScores[i + 1]; possibleScores[i + 1] = t; sorted = false; } } } setPossibleScores(possibleScores); } } Code Sample 2: 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; } }
00
Code Sample 1: public static String rename_file(String sessionid, String key, String newFileName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_file"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_file")); nameValuePairs.add(new BasicNameValuePair("new_name", newFileName)); nameValuePairs.add(new BasicNameValuePair("key", key)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; } Code Sample 2: public static String encryptPassword(String password) throws PasswordException { String hash = null; if (password != null && !password.equals("")) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = String.valueOf(Base64Coder.encode(raw)); } catch (NoSuchAlgorithmException nsae) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } catch (UnsupportedEncodingException uee) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } } return hash; }
11
Code Sample 1: 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 { closeQuietly(in); closeQuietly(out); } return success; } Code Sample 2: public static void copyFile(File source, File target) throws Exception { if (source == null || target == null) { throw new IllegalArgumentException("The arguments may not be null."); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dtnChannel = new FileOutputStream(target).getChannel(); srcChannel.transferTo(0, srcChannel.size(), dtnChannel); srcChannel.close(); dtnChannel.close(); } catch (Exception e) { String message = "Unable to copy file '" + source.getName() + "' to '" + target.getName() + "'."; logger.error(message, e); throw new Exception(message, e); } }
00
Code Sample 1: private BundleURLClassPath createBundleURLClassPath(Bundle bundle, Version version, File bundleFile, File cache, boolean alreadyCached) throws Exception { String bundleClassPath = (String) bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); if (bundleClassPath == null) { bundleClassPath = "."; } ManifestEntry[] entries = ManifestEntry.parse(bundleClassPath); String[] classPaths = new String[0]; for (int i = 0; i < entries.length; i++) { String classPath = entries[i].getName(); if (classPath.startsWith("/")) { classPath = classPath.substring(1); } if (classPath.endsWith(".jar")) { try { File file = new File(cache, classPath); if (!alreadyCached) { file.getParentFile().mkdirs(); String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(classPath).toString(); OutputStream os = new FileOutputStream(file); InputStream is = new URL(url).openStream(); IOUtil.copy(is, os); is.close(); os.close(); } else { if (!file.exists()) { throw new IOException(new StringBuilder("classpath ").append(classPath).append(" not found").toString()); } } } catch (IOException e) { FrameworkEvent frameworkEvent = new FrameworkEvent(FrameworkEvent.INFO, bundle, e); framework.postFrameworkEvent(frameworkEvent); continue; } } classPaths = (String[]) ArrayUtil.add(classPaths, classPath); } if (!alreadyCached) { String bundleNativeCode = (String) bundle.getHeaders().get(Constants.BUNDLE_NATIVECODE); if (bundleNativeCode != null) { entries = ManifestEntry.parse(bundleNativeCode); for (int i = 0; i < entries.length; i++) { ManifestEntry entry = entries[i]; String libPath = entry.getName(); String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(libPath).toString(); File file = new File(cache, libPath); file.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(file); InputStream is = new URL(url).openStream(); IOUtil.copy(is, os); is.close(); os.close(); } } } BundleURLClassPath urlClassPath = new BundleURLClassPathImpl(bundle, version, classPaths, cache); return urlClassPath; } Code Sample 2: public void mkdirs(String path) throws IOException { GridFTP ftp = new GridFTP(); ftp.setDefaultPort(port); System.out.println(this + ".mkdirs " + path); try { ftp.connect(host); ftp.login(username, password); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("FTP server refused connection."); } ftp.mkdirs(path); ftp.logout(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } }
11
Code Sample 1: static void createCompleteXML(File file) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(errorFile); fos = new FileOutputStream(file); byte[] data = new byte[Integer.parseInt(BlueXStatics.prop.getProperty("allocationUnit"))]; int offset; while ((offset = fis.read(data)) != -1) fos.write(data, 0, offset); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } try { fos.close(); } catch (Exception e) { } } FileWriter fw = null; try { fw = new FileWriter(file, true); fw.append("</detail>"); fw.append("\n</exception>"); fw.append("\n</log>"); } catch (Exception e) { e.printStackTrace(); } finally { try { fw.close(); } catch (Exception e) { } } } Code Sample 2: protected void copyDependents() { for (File source : dependentFiles.keySet()) { try { if (!dependentFiles.get(source).exists()) { if (dependentFiles.get(source).isDirectory()) dependentFiles.get(source).mkdirs(); else dependentFiles.get(source).getParentFile().mkdirs(); } IOUtils.copyEverything(source, dependentFiles.get(source)); } catch (IOException e) { e.printStackTrace(); } } }
00
Code Sample 1: public GetMyDocuments() { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetMyDocuments"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "mydocuments.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "mydocuments.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("document"); int num = nodelist.getLength(); myDocsData = new String[num][4]; myDocsToolTip = new String[num]; myDocumentImageName = new String[num]; myDocIds = new int[num]; for (int i = 0; i < num; i++) { myDocsData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "filename")); myDocsData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "project")); myDocsData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "deadline")); myDocsData[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "workingfolder")); myDocsToolTip[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "title")); myDocumentImageName[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "imagename")); myDocIds[i] = (new Integer(new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid")))).intValue(); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException ex) { } catch (Exception ex) { System.out.println(ex); } } Code Sample 2: public static final String enCode(String algorithm, String string) { MessageDigest md; String result = ""; try { md = MessageDigest.getInstance(algorithm); md.update(string.getBytes()); result = binaryToString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
00
Code Sample 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; } Code Sample 2: public void loadFromURLPath(String type, URL urlPath, HashMap parentAttributes) throws IOException { this.urlPath = urlPath; this.type = type; JmeBinaryReader jbr = new JmeBinaryReader(); setProperties(jbr, parentAttributes); InputStream loaderInput = urlPath.openStream(); if (type.equals("xml")) { XMLtoBinary xtb = new XMLtoBinary(); ByteArrayOutputStream BO = new ByteArrayOutputStream(); xtb.sendXMLtoBinary(loaderInput, BO); loaderInput = new ByteArrayInputStream(BO.toByteArray()); } else if (!type.equals("binary")) throw new IOException("Unknown LoaderNode flag: " + type); jbr.loadBinaryFormat(this, loaderInput); }
11
Code Sample 1: public static void main(String[] args) throws Exception { String infile = "C:\\copy.sql"; String outfile = "C:\\copy.txt"; FileInputStream fin = new FileInputStream(infile); FileOutputStream fout = new FileOutputStream(outfile); FileChannel fcin = fin.getChannel(); FileChannel fcout = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { buffer.clear(); int r = fcin.read(buffer); if (r == -1) { break; } buffer.flip(); fcout.write(buffer); } } Code Sample 2: private void copyFileNFS(String sSource, String sTarget) throws Exception { FileInputStream fis = new FileInputStream(sSource); FileOutputStream fos = new FileOutputStream(sTarget); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buf = new byte[2048]; int i = 0; while ((i = bis.read(buf)) != -1) bos.write(buf, 0, i); bis.close(); bos.close(); fis.close(); fos.close(); }
00
Code Sample 1: public static String calcolaMd5(String messaggio) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.reset(); md.update(messaggio.getBytes()); byte[] impronta = md.digest(); return new String(impronta); } Code Sample 2: public void login() { loginsuccessful = false; try { cookies = new StringBuilder(); HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to crocko.com"); HttpPost httppost = new HttpPost("https://www.crocko.com/accounts/login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("login", getUsername())); formparams.add(new BasicNameValuePair("password", getPassword())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); NULogger.getLogger().info("Getting cookies........"); NULogger.getLogger().info(EntityUtils.toString(httpresponse.getEntity())); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); cookies.append(escookie.getName()).append("=").append(escookie.getValue()).append(";"); if (escookie.getName().equals("PHPSESSID")) { sessionid = escookie.getValue(); NULogger.getLogger().info(sessionid); } } if (cookies.toString().contains("logacc")) { NULogger.getLogger().info(cookies.toString()); loginsuccessful = true; username = getUsername(); password = getPassword(); NULogger.getLogger().info("Crocko login successful :)"); } if (!loginsuccessful) { NULogger.getLogger().info("Crocko.com Login failed :("); loginsuccessful = false; username = ""; password = ""; JOptionPane.showMessageDialog(NeembuuUploader.getInstance(), "<html><b>" + HOSTNAME + "</b> " + TranslationProvider.get("neembuuuploader.accounts.loginerror") + "</html>", HOSTNAME, JOptionPane.WARNING_MESSAGE); AccountsManager.getInstance().setVisible(true); } httpclient.getConnectionManager().shutdown(); } catch (Exception e) { NULogger.getLogger().log(Level.SEVERE, "{0}: {1}", new Object[] { getClass().getName(), e.toString() }); System.err.println(e); } }
00
Code Sample 1: public void download() { try { URL url = new URL(srcURL + src); URLConnection urlc = url.openConnection(); InputStream is = urlc.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); FileOutputStream fos = new FileOutputStream(dest); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buffer = new byte[1000000]; int readSize; readSize = bis.read(buffer); while (readSize > 0) { bos.write(buffer, 0, readSize); readSize = bis.read(buffer); } bos.close(); fos.close(); bis.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: 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(); }
11
Code Sample 1: public void testAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); } Code Sample 2: public static void copyFile(String inName, String otName) throws Exception { File inFile = null; File otFile = null; try { inFile = new File(inName); otFile = new File(otName); } catch (Exception e) { e.printStackTrace(); } if (inFile == null || otFile == null) return; FileChannel sourceChannel = new FileInputStream(inFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(otFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: protected boolean downloadFile(TestThread thread, ActionResult result) { result.setRequestString("download file " + remoteFile); InputStream input = null; OutputStream output = null; OutputStream target = null; boolean status = false; ftpClient.enterLocalPassiveMode(); try { if (localFile != null) { File lcFile = new File(localFile); if (lcFile.exists() && lcFile.isDirectory()) output = new FileOutputStream(new File(lcFile, remoteFile)); else output = new FileOutputStream(lcFile); target = output; } else { target = new FileOutputStream(remoteFile); } input = ftpClient.retrieveFileStream(remoteFile); long bytes = IOUtils.copy(input, target); status = bytes > 0; if (status) { result.setResponseLength(bytes); } } catch (Exception e) { result.setException(new TestActionException(config, e)); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } return status; } Code Sample 2: protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); try { boolean isMultipart = FileUpload.isMultipartContent(request); Store storeInstance = getStoreInstance(request); if (isMultipart) { Map fields = new HashMap(); Vector files = new Vector(); List items = diskFileUpload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fields.put(item.getFieldName(), item.getString()); } else { if (!StringUtils.isBlank(item.getName())) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); IOUtils.copy(item.getInputStream(), baos); MailPartObj part = new MailPartObj(); part.setAttachent(baos.toByteArray()); part.setContentType(item.getContentType()); part.setName(item.getName()); part.setSize(item.getSize()); files.addElement(part); } catch (Exception ex) { } finally { IOUtils.closeQuietly(baos); } } } } if (files.size() > 0) { storeInstance.send(files, 0, Charset.defaultCharset().displayName()); } } else { errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null")); request.setAttribute("exception", "The form is null"); request.setAttribute("newLocation", null); doTrace(request, DLog.ERROR, getClass(), "The form is null"); } } catch (Exception ex) { String errorMessage = ExceptionUtilities.parseMessage(ex); if (errorMessage == null) { errorMessage = "NullPointerException"; } errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage)); request.setAttribute("exception", errorMessage); doTrace(request, DLog.ERROR, getClass(), errorMessage); } finally { } if (errors.isEmpty()) { doTrace(request, DLog.INFO, getClass(), "OK"); return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD); } else { saveErrors(request, errors); return mapping.findForward(Constants.ACTION_FAIL_FORWARD); } }
11
Code Sample 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; } Code Sample 2: private void tar(FileHolder fileHolder, boolean gzipIt) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File tarDestFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(tarDestFile); if (gzipIt) { outStream = new GZIPOutputStream(outStream); } TarOutputStream tarOutStream = new TarOutputStream(outStream); for (int i = 0; i < fileHolder.selectedFileList.size(); i++) { File selectedFile = fileHolder.selectedFileList.get(i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); TarEntry tarEntry = null; try { tarEntry = new TarEntry(selectedFile, selectedFile.getName()); } catch (InvalidHeaderException e) { errEntry.setThrowable(e); errEntry.setAppContext("tar()"); errEntry.setAppMessage("Error tar'ing: " + selectedFile); logger.logError(errEntry); } tarOutStream.putNextEntry(tarEntry); while ((bytes_read = inStream.read(buffer)) != -1) { tarOutStream.write(buffer, 0, bytes_read); } tarOutStream.closeEntry(); inStream.close(); super.processorSyncFlag.restartWaitUntilFalse(); } tarOutStream.close(); } catch (Exception e) { errEntry.setThrowable(e); errEntry.setAppContext("tar()"); errEntry.setAppMessage("Error tar'ing: " + tarDestFile); logger.logError(errEntry); } }
11
Code Sample 1: public ArrayList parseFile(File newfile) throws IOException { String s; String firstName; String header; String name = null; Integer PVLoggerID = new Integer(0); String[] tokens; int nvalues = 0; double num1, num2, num3; double xoffset = 1.0; double xdelta = 1.0; double yoffset = 1.0; double ydelta = 1.0; double zoffset = 1.0; double zdelta = 1.0; boolean readfit = false; boolean readraw = false; boolean zerodata = false; boolean baddata = false; boolean harpdata = false; ArrayList fitparams = new ArrayList(); ArrayList xraw = new ArrayList(); ArrayList yraw = new ArrayList(); ArrayList zraw = new ArrayList(); ArrayList sraw = new ArrayList(); ArrayList sxraw = new ArrayList(); ArrayList syraw = new ArrayList(); ArrayList szraw = new ArrayList(); URL url = newfile.toURI().toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; firstName = (String) tokens[0]; if (((String) tokens[0]).length() == 0) { readraw = false; readfit = false; continue; } if ((nvalues == 4) && (!firstName.startsWith("---"))) { if ((Double.parseDouble(tokens[1]) == 0.) && (Double.parseDouble(tokens[2]) == 0.) && (Double.parseDouble(tokens[3]) == 0.)) { zerodata = true; } else { zerodata = false; } if (tokens[1].equals("NaN") || tokens[2].equals("NaN") || tokens[3].equals("NaN")) { baddata = true; } else { baddata = false; } } if (firstName.startsWith("start")) { header = s; } if (firstName.indexOf("WS") > 0) { if (name != null) { dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); } name = tokens[0]; readraw = false; readfit = false; zerodata = false; baddata = false; harpdata = false; fitparams.clear(); xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); } if (firstName.startsWith("Area")) ; if (firstName.startsWith("Ampl")) ; if (firstName.startsWith("Mean")) ; if (firstName.startsWith("Sigma")) { fitparams.add(new Double(Double.parseDouble(tokens[3]))); fitparams.add(new Double(Double.parseDouble(tokens[1]))); fitparams.add(new Double(Double.parseDouble(tokens[5]))); } if (firstName.startsWith("Offset")) ; if (firstName.startsWith("Slope")) ; if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Raw"))) { readraw = true; continue; } if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Fit"))) { readfit = true; continue; } if ((firstName.contains("Harp"))) { xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); harpdata = true; readraw = true; name = tokens[0]; continue; } if (firstName.startsWith("---")) continue; if (harpdata == true) { if (((String) tokens[0]).length() != 0) { if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } else { sxraw.add(new Double(Double.parseDouble(tokens[0]))); xraw.add(new Double(Double.parseDouble(tokens[1]))); syraw.add(new Double(Double.parseDouble(tokens[2]))); yraw.add(new Double(Double.parseDouble(tokens[3]))); szraw.add(new Double(Double.parseDouble(tokens[4]))); zraw.add(new Double(Double.parseDouble(tokens[5]))); } } continue; } if (readraw && (!zerodata) && (!baddata)) { sraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); sxraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); syraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); szraw.add(new Double(Double.parseDouble(tokens[0]))); yraw.add(new Double(Double.parseDouble(tokens[1]))); zraw.add(new Double(Double.parseDouble(tokens[2]))); xraw.add(new Double(Double.parseDouble(tokens[3]))); } if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } } dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); wiredata.add((Integer) PVLoggerID); return wiredata; } Code Sample 2: @Override public void exec() { BufferedReader in = null; try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer result = new StringBuffer(); String str; while ((str = in.readLine()) != null) { result.append(str); } logger.info("received message: " + result); } catch (Exception e) { logger.error("HttpGetEvent could not execute", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } }
00
Code Sample 1: protected Collection<BibtexEntry> getBibtexEntries(String ticket, String citations) throws IOException { try { URL url = new URL(URL_BIBTEX); URLConnection conn = url.openConnection(); conn.setRequestProperty("Cookie", ticket + "; " + citations); conn.connect(); BibtexParser parser = new BibtexParser(new BufferedReader(new InputStreamReader(conn.getInputStream()))); return parser.parse().getDatabase().getEntries(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } Code Sample 2: public void reademi(Vector<String> descriptions, Vector<String> links, String linkaddress, String idmap) { InputStream is = null; URL url; ArrayList<String> keys = new ArrayList<String>(); ArrayList<String> names = new ArrayList<String>(); try { url = new URL(idmap); is = url.openStream(); Scanner scanner = new Scanner(is); scanner.nextLine(); String line = ""; String id = ""; while (scanner.hasNextLine()) { line = scanner.nextLine(); Scanner linescanner = new Scanner(line); linescanner.useDelimiter("\t"); id = linescanner.next(); id = id.substring(0, id.length() - 2); keys.add(id); linescanner.next(); linescanner.next(); linescanner.next(); linescanner.useDelimiter("\n"); names.add(linescanner.next()); } BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(linkaddress).openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; while ((line = reader.readLine()) != null) { if (line.indexOf("style=raw") != -1) { int linkstart = line.indexOf("http://www.ebi.ac.uk/cgi-bin/dbfetch?db"); int idstart = line.indexOf("id=") + 3; int linkend = line.substring(linkstart).indexOf("\"") + linkstart; link = line.substring(linkstart, linkend); key = line.substring(idstart, linkend); if (keys.indexOf(key) != -1) { name = names.get(keys.indexOf(key)); counter++; descriptions.add(counter + " " + key + " " + name); links.add(link); } } } } catch (MalformedURLException e) { } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static void main(String[] args) throws Exception { InputStream in = null; try { in = new URL(args[0]).openStream(); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } } Code Sample 2: public static void copyDirs(File sourceDir, File destDir) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (File file : sourceDir.listFiles()) { if (file.isDirectory()) { copyDirs(file, new File(destDir, file.getName())); } else { FileChannel srcChannel = new FileInputStream(file).getChannel(); File out = new File(destDir, file.getName()); out.createNewFile(); FileChannel dstChannel = new FileOutputStream(out).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } }
11
Code Sample 1: public static boolean writeFileByBinary(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileOutputStream fos = new FileOutputStream(pFile, pAppend); IOUtils.copy(pIs, fos); fos.flush(); fos.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; } Code Sample 2: public static void save(String from, String recipient, InputStream in, MimeMessage message) throws IOException, MessagingException, DocumentVideException { ConversationManager conversationManager = FGDSpringUtils.getConversationManager(); conversationManager.beginConversation(); FGDDelegate delegate = new FGDDelegate(); UtilisateurIFGD utilisateur = delegate.getUtilisateurParCourriel(from); if (utilisateur == null) { String responseEmailSubject = "Votre adresse ne correspond pas à celle d'un utilisateur d'IntelliGID"; String responseEmailMessage = "<h3>Pour sauvegarder un courriel, vous devez être un utilisateur d'IntelliGID et l'adresse de courrier électronique utilisée doit être celle apparaissant dans votre profil.</h3>"; String sender = recipient.endsWith("localhost") ? FGDSpringUtils.getExpediteurSupport() : recipient; Map<String, String> recipients = new HashMap<String, String>(); recipients.put(from, null); MailUtils.sendSimpleHTMLMessage(recipients, responseEmailSubject, responseEmailMessage, sender); return; } File tempFile = File.createTempFile("email", ".eml"); tempFile.deleteOnExit(); BufferedInputStream bis = new BufferedInputStream(in); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tempFile)); IOUtils.copy(bis, bos); IOUtils.closeQuietly(bis); IOUtils.closeQuietly(bos); if (message == null) { GestionnaireProprietesMimeMessageParser gestionnaire = new GestionnaireProprietesMimeMessageParser(); message = gestionnaire.asMimeMessage(new BufferedInputStream(new FileInputStream(tempFile))); } String subject; try { subject = message.getSubject().replace("Fwd:", "").trim(); } catch (MessagingException e) { subject = "Message sans sujet"; } File tempDir = new File(System.getProperty("java.io.tmpdir")); if (!tempDir.exists()) { tempDir.mkdirs(); } File emailFile = new File(tempDir, FilenameUtils.normalize(subject) + ".eml"); FileUtils.copyFile(tempFile, emailFile); FicheDocument ficheDocument = new FicheDocument(); ficheDocument.setFicheCompletee(false); ficheDocument.setDateCreationHorodatee(new Date()); ficheDocument.setUtilisateurSoumetteur(utilisateur); ficheDocument.getLangues().addAll(getLanguesDefaut()); ficheDocument.setCourriel(true); FileIOContenuFichierElectronique contenuFichier = new FileIOContenuFichierElectronique(emailFile, "multipart/alternative"); SupportDocument support = new SupportDocument(); support.setFicheDocument(ficheDocument); FichierElectroniqueUtils.setContenu(ficheDocument, support, contenuFichier, utilisateur); ficheDocument.setTitre(subject); delegate.sauvegarder(ficheDocument, utilisateur); String modifyEmail = "http://" + FGDSpringUtils.getServerHost() + ":" + FGDSpringUtils.getServerPort() + "/" + FGDSpringUtils.getApplicationName() + "/app/modifierDocument/id/" + ficheDocument.getId(); System.out.println(modifyEmail); String responseEmailSubject = "Veuillez compléter la fiche du courriel «" + subject + "»"; String responseEmailMessage = "<h3>Le courrier électronique a été sauvegardé, mais il est nécessaire de <a href=\"" + modifyEmail + "\">compléter sa fiche</a>.</h3>"; String sender = recipient.endsWith("localhost") ? FGDSpringUtils.getExpediteurSupport() : recipient; try { MailUtils.sendSimpleHTMLMessage(utilisateur, responseEmailSubject, responseEmailMessage, sender); } catch (Throwable e) { e.printStackTrace(); } conversationManager.commitTransaction(); tempFile.delete(); }
11
Code Sample 1: @Override public void write(OutputStream output) throws IOException, WebApplicationException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final GZIPOutputStream gzipOs = new GZIPOutputStream(baos); IOUtils.copy(is, gzipOs); baos.close(); gzipOs.close(); output.write(baos.toByteArray()); } Code Sample 2: public void objectParserAssesmentItem(int file, int currentquestion, Resource resTemp) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int indexLastSeparator; String sOldPath = ""; try { if (file == 1) { nl = doc.getElementsByTagName("object"); } else { nl = doc_[currentquestion].getElementsByTagName("object"); } for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem("data"); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getFile(); sOldPath = sOldPath.replace('/', File.separatorChar); indexLastSeparator = sOldPath.lastIndexOf(File.separatorChar); String sSourcePath = sOldPath; sFilename = sOldPath.substring(indexLastSeparator + 1); sNewPath = this.sTempLocation + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } if (file == 1) { sXml = sXml.replace(nsrc.getTextContent(), sFilename); } else { sXml_[currentquestion] = sXml_[currentquestion].replace(nsrc.getTextContent(), sFilename); } lsImages.add(sFilename); resTemp.addFile(sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment) throws IOException, MessagingException { writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\""); writeHeader(writer, "Content-Transfer-Encoding", "base64"); writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName + "\";" + "\n size=" + Long.toString(attachment.mSize)); writeHeader(writer, "Content-ID", attachment.mContentId); writer.append("\r\n"); InputStream inStream = null; try { Uri fileUri = Uri.parse(attachment.mContentUri); inStream = context.getContentResolver().openInputStream(fileUri); writer.flush(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(inStream, base64Out); base64Out.close(); } catch (FileNotFoundException fnfe) { } catch (IOException ioe) { throw new MessagingException("Invalid attachment.", ioe); } } Code Sample 2: public void downloadFrinika() throws Exception { if (!frinikaFile.exists()) { String urlString = remoteURLPath + frinikaFileName; showMessage("Connecting to " + urlString); URLConnection uc = new URL(urlString).openConnection(); progressBar.setIndeterminate(false); showMessage("Downloading from " + urlString); progressBar.setValue(0); progressBar.setMinimum(0); progressBar.setMaximum(fileSize); InputStream is = uc.getInputStream(); FileOutputStream fos = new FileOutputStream(frinikaFile); byte[] b = new byte[BUFSIZE]; int c; while ((c = is.read(b)) != -1) { fos.write(b, 0, c); progressBar.setValue(progressBar.getValue() + c); } fos.close(); } }
00
Code Sample 1: public void run() { if (getCommand() == null) throw new IllegalArgumentException("Given command is null!"); if (getSocketProvider() == null) throw new IllegalArgumentException("Given connection is not open!"); if (getCommand() instanceof ListCommand) { try { setReply(ReplyWorker.readReply(getSocketProvider(), true)); setStatus(ReplyWorker.FINISHED); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } return; } else if (getCommand() instanceof RetrieveCommand) { RetrieveCommand retrieveCommand = (RetrieveCommand) getCommand(); if (retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_I || retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Download file: " + retrieveCommand.getFromFile().toString()); FileOutputStream out = null; FileChannel channel = null; if (getDownloadMethod() == RetrieveCommand.FILE_BASED) { out = new FileOutputStream(retrieveCommand.getToFile().getFile()); channel = out.getChannel(); if (retrieveCommand.getResumePosition() != -1) { try { channel.position(retrieveCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } int amount; try { while ((amount = getSocketProvider().read(buffer)) != -1) { if (amount == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); setStatus(ReplyWorker.FINISHED); if (channel != null) channel.close(); if (this.outputPipe != null) this.outputPipe.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for download!"); return; } else if (getCommand() instanceof StoreCommand) { StoreCommand storeCommand = (StoreCommand) getCommand(); if (storeCommand.getToFile().getTransferType().intern() == Command.TYPE_I || storeCommand.getToFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Upload file: " + storeCommand.getFromFile()); InputStream in = storeCommand.getStream(); int amount; int socketWrite; int socketAmount = 0; if (in instanceof FileInputStream) { FileChannel channel = ((FileInputStream) in).getChannel(); if (storeCommand.getResumePosition() != -1) { try { channel.position(storeCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } try { while ((amount = channel.read(buffer)) != -1) { buffer.flip(); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount += socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); channel.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } else { try { while ((amount = in.read(buffer.array())) != -1) { buffer.flip(); buffer.limit(amount); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount = socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); in.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { in.close(); getSocketProvider().close(); } catch (Exception e) { } } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for upload!"); } else throw new IllegalArgumentException("Given command is not supported!"); } Code Sample 2: @SuppressWarnings("unchecked") protected void handleRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost) throws ServletException, IOException { HttpClient httpclient = WebReader.getHttpClient(); try { StringBuffer sb = new StringBuffer(); sb.append(targetServer); sb.append(req.getRequestURI()); if (req.getQueryString() != null) { sb.append("?" + req.getQueryString()); } HttpRequestBase targetRequest = null; if (isPost) { HttpPost post = new HttpPost(sb.toString()); Enumeration<String> paramNames = req.getParameterNames(); String paramName = null; List<NameValuePair> params = new ArrayList<NameValuePair>(); while (paramNames.hasMoreElements()) { paramName = paramNames.nextElement(); params.add(new BasicNameValuePair(paramName, req.getParameterValues(paramName)[0])); } post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); targetRequest = post; } else { System.out.println("GET"); HttpGet get = new HttpGet(sb.toString()); targetRequest = get; } HttpResponse targetResponse = httpclient.execute(targetRequest); HttpEntity entity = targetResponse.getEntity(); InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output)); String line = reader.readLine(); while (line != null) { writer.write(line + "\n"); line = reader.readLine(); } reader.close(); writer.close(); } finally { WebReader.returnHttpClient(httpclient); } }
00
Code Sample 1: private void preprocessObjects(GeoObject[] objects) throws IOException { System.out.println("objects.length " + objects.length); for (int i = 0; i < objects.length; i++) { String fileName = objects[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("i: " + " world filename " + tmp); File worldFile = new File(tmp); if (worldFile.exists()) { BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); } } File file = new File(objects[i].getPath()); if (file.exists()) { System.out.println("object src file found "); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); objects[i].setPath(tmp); file = new File(fileName); if (file.exists()) { DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } } } } Code Sample 2: private static void readServicesFromUrl(Collection<String> list, URL url) throws IOException { InputStream in = url.openStream(); try { if (in == null) return; BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) break; int idx = line.indexOf('#'); if (idx != -1) line = line.substring(0, idx); line = line.trim(); if (line.length() == 0) continue; list.add(line); } } finally { try { if (in != null) in.close(); } catch (Throwable ignore) { } } }
11
Code Sample 1: 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; } Code Sample 2: private void _save(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(this, "Property File save Failed " + e, e); } } SessionMessages.add(req, "message", "message.languagemanager.save"); }
11
Code Sample 1: public void jsFunction_extract(ScriptableFile outputFile) throws IOException, FileSystemException, ArchiveException { InputStream is = file.jsFunction_createInputStream(); OutputStream output = outputFile.jsFunction_createOutputStream(); BufferedInputStream buf = new BufferedInputStream(is); ArchiveInputStream input = ScriptableZipArchive.getFactory().createArchiveInputStream(buf); try { long count = 0; while (input.getNextEntry() != null) { if (count == offset) { IOUtils.copy(input, output); break; } count++; } } finally { input.close(); output.close(); is.close(); } } Code Sample 2: private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
11
Code Sample 1: 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!"); } Code Sample 2: 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!"); }
00
Code Sample 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(); } } Code Sample 2: public void run() { logger.info("downloading '" + url.toString() + "' to: " + dstFile.getAbsolutePath()); Preferences prefs = Preferences.userRoot().node("gvsig.downloader"); int timeout = prefs.getInt("timeout", 60000); DataOutputStream dos; try { DataInputStream is; OutputStreamWriter os = null; HttpURLConnection connection = null; if (url.getProtocol().equals("https")) { disableHttsValidation(); } connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(timeout); if (data != null) { connection.setRequestProperty("SOAPAction", "post"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); os = new OutputStreamWriter(connection.getOutputStream()); os.write(data); os.flush(); is = new DataInputStream(connection.getInputStream()); } else { is = new DataInputStream(url.openStream()); } dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dstFile))); byte[] buffer = new byte[1024 * 4]; long readed = 0; for (int i = is.read(buffer); !Utilities.getCanceled(groupID) && i > 0; i = is.read(buffer)) { dos.write(buffer, 0, i); readed += i; } if (os != null) { os.close(); } dos.close(); is.close(); is = null; dos = null; if (Utilities.getCanceled(groupID)) { logger.warning("[RemoteServices] '" + url + "' CANCELED."); dstFile.delete(); dstFile = null; } else { Utilities.addDownloadedURL(url, dstFile.getAbsolutePath()); } } catch (Exception e) { e.printStackTrace(); Utilities.downloadException = e; } }
00
Code Sample 1: private static boolean isXmlApplicationFile(URL url) throws java.io.IOException { if (DEBUG) { System.out.println("Checking whether file is xml"); } String firstLine; BufferedReader fileReader = null; try { fileReader = new BomStrippingInputStreamReader(url.openStream()); firstLine = fileReader.readLine(); } finally { if (fileReader != null) fileReader.close(); } if (firstLine == null) { return false; } for (String startOfXml : STARTOFXMLAPPLICATIONFILES) { if (firstLine.length() >= startOfXml.length() && firstLine.substring(0, startOfXml.length()).equals(startOfXml)) { if (DEBUG) { System.out.println("isXMLApplicationFile = true"); } return true; } } if (DEBUG) { System.out.println("isXMLApplicationFile = false"); } return false; } Code Sample 2: public static String md5(String value) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); try { messageDigest.update(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { messageDigest.update(value.getBytes()); } byte[] bytes = messageDigest.digest(); return byteArrayToHexString(bytes); }
11
Code Sample 1: 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; } Code Sample 2: public void setContentAsStream(final InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { output.close(); } this.content = output.toByteArray(); }
00
Code Sample 1: private static String hash(String string) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (Exception e) { return null; } try { md.update(string.getBytes("UTF-8")); } catch (Exception e) { return null; } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); } Code Sample 2: private synchronized jdbcResultSet executeHTTP(String s) throws SQLException { byte result[]; try { URL url = new URL(sConnect); String p = StringConverter.unicodeToHexString(sUser); p += "+" + StringConverter.unicodeToHexString(sPassword); p += "+" + StringConverter.unicodeToHexString(s); URLConnection c = url.openConnection(); c.setDoOutput(true); OutputStream os = c.getOutputStream(); os.write(p.getBytes(ENCODING)); os.close(); c.connect(); InputStream is = (InputStream) c.getContent(); BufferedInputStream in = new BufferedInputStream(is); int len = c.getContentLength(); result = new byte[len]; for (int i = 0; i < len; i++) { int r = in.read(); result[i] = (byte) r; } } catch (Exception e) { throw Trace.error(Trace.CONNECTION_IS_BROKEN, e.getMessage()); } return new jdbcResultSet(new Result(result)); }
00
Code Sample 1: private int saveToTempTable(ArrayList cons, String tempTableName, boolean truncateFirst) throws SQLException { if (truncateFirst) { this.executeUpdate("TRUNCATE TABLE " + tempTableName); Categories.dataDb().debug("TABLE " + tempTableName + " TRUNCATED."); } PreparedStatement ps = null; int rows = 0; try { String insert = "INSERT INTO " + tempTableName + " VALUES (?)"; ps = this.conn.prepareStatement(insert); for (int i = 0; i < cons.size(); i++) { ps.setLong(1, ((Long) cons.get(i)).longValue()); rows = ps.executeUpdate(); if ((i % 500) == 0) { this.conn.commit(); } } this.conn.commit(); } catch (SQLException sqle) { this.conn.rollback(); throw sqle; } finally { if (ps != null) { ps.close(); } } return rows; } Code Sample 2: public void buildCache() { XMLCacheBuilder cacheBuilder = CompositePageUtil.getCacheBuilder(); String postFix = ""; if (cacheBuilder.getPostFix() != null && !cacheBuilder.getPostFix().equals("")) { postFix = "." + cacheBuilder.getPostFix(); } String basePath = cacheBuilder.getBasePath(); List actions = CompositePageUtil.getXMLActions(); for (int i = 0; i < actions.size(); i++) { try { XMLAction action = (XMLAction) actions.get(i); if (action.getEscapeCacheBuilder() != null && action.getEscapeCacheBuilder().equals("true")) continue; String actionUrl = basePath + action.getName() + postFix; URL url = new URL(actionUrl); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setDoInput(true); huc.setDoOutput(true); huc.setUseCaches(false); huc.setRequestProperty("Content-Type", "text/html"); DataOutputStream dos = new DataOutputStream(huc.getOutputStream()); dos.flush(); dos.close(); huc.disconnect(); } catch (MalformedURLException e) { logger.error(e); e.printStackTrace(); } catch (IOException e) { logger.equals(e); e.printStackTrace(); } } }
11
Code Sample 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); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + 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("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); 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) { ; } } } } Code Sample 2: public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException("Expected arguments: fileName log"); String fileName = args[0]; String logFile = args[1]; LineNumberReader reader = null; PrintWriter writer = null; try { Reader reader0 = new FileReader(fileName); reader = new LineNumberReader(reader0); Writer writer0 = new FileWriter(logFile); BufferedWriter writer1 = new BufferedWriter(writer0); writer = new PrintWriter(writer1); String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.length() >= 81) { writer.println("Analyzing Sudoku #" + reader.getLineNumber()); System.out.println("Analyzing Sudoku #" + reader.getLineNumber()); Grid grid = new Grid(); for (int i = 0; i < 81; i++) { char ch = line.charAt(i); if (ch >= '1' && ch <= '9') { int value = (ch - '0'); grid.setCellValue(i % 9, i / 9, value); } } Solver solver = new Solver(grid); solver.rebuildPotentialValues(); try { Map<Rule, Integer> rules = solver.solve(null); Map<String, Integer> ruleNames = solver.toNamedList(rules); double difficulty = 0; String hardestRule = ""; for (Rule rule : rules.keySet()) { if (rule.getDifficulty() > difficulty) { difficulty = rule.getDifficulty(); hardestRule = rule.getName(); } } for (String rule : ruleNames.keySet()) { int count = ruleNames.get(rule); writer.println(Integer.toString(count) + " " + rule); System.out.println(Integer.toString(count) + " " + rule); } writer.println("Hardest technique: " + hardestRule); System.out.println("Hardest technique: " + hardestRule); writer.println("Difficulty: " + difficulty); System.out.println("Difficulty: " + difficulty); } catch (UnsupportedOperationException ex) { writer.println("Failed !"); System.out.println("Failed !"); } writer.println(); System.out.println(); writer.flush(); } else System.out.println("Skipping incomplete line: " + line); line = reader.readLine(); } writer.close(); reader.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException ex) { ex.printStackTrace(); } } System.out.print("Finished."); }
11
Code Sample 1: private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException { final boolean stripHtmlEnabled = true; final boolean injectSecretTokensEnabled = true; final boolean encryptQueryStringsEnabled = true; final boolean protectParamsAndFormsEnabled = true; final boolean applyExtraProtectionForDisabledFormFields = true; final boolean applyExtraProtectionForReadonlyFormFields = false; final boolean applyExtraProtectionForRequestParamValueCount = false; final ContentInjectionHelper helper = new ContentInjectionHelper(); final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader(); ruleFileLoaderModificationExcludes.setPath(WebCastellumFilter.MODIFICATION_EXCLUDES_DEFAULT); final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes); containerModExcludes.parseDefinitions(); helper.setContentModificationExcludeDefinitions(containerModExcludes); final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true); final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", ""); final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true); final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader(); ruleFileLoaderResponseModifications.setPath(WebCastellumFilter.RESPONSE_MODIFICATIONS_DEFAULT); final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications); container.parseDefinitions(); final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions()); final List tmpPatternsToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); for (int i = 0; i < responseModificationDefinitions.length; i++) { final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i]; if (responseModificationDefinition.isMatchesScripts()) { tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern()); tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter()); tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } if (responseModificationDefinition.isMatchesTags()) { tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern()); tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter()); tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } } final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag); final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript); final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts); final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags); final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts); final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags); final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]); final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts); final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags); final Cipher cipher = CryptoUtils.getCipher(); final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false); Cipher.getInstance("AES"); MessageDigest.getInstance("SHA-1"); final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false); final List durations = new ArrayList(); for (int i = 0; i < executionCount; i++) { final long start = System.currentTimeMillis(); Reader reader = null; Writer writer = null; try { reader = new BufferedReader(new FileReader(this.htmlFile)); writer = new FileWriter(this.outputFile); if (applyFilter) { writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false); writer = new BufferedWriter(writer); } char[] chars = new char[16 * 1024]; int read; while ((read = reader.read(chars)) != -1) { if (read > 0) { writer.write(chars, 0, read); } } durations.add(new Long(System.currentTimeMillis() - start)); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } } } long sum = 0; for (final Iterator iter = durations.iterator(); iter.hasNext(); ) { Long value = (Long) iter.next(); sum += value.longValue(); } return sum / durations.size(); } Code Sample 2: public static boolean copyFile(String fromfile, String tofile) { File from = new File(fromfile); File to = new File(tofile); if (!from.exists()) return false; if (to.exists()) { log.error(tofile + "exists already"); return false; } BufferedInputStream in = null; BufferedOutputStream out = null; FileInputStream fis = null; FileOutputStream ois = null; boolean flag = true; try { to.createNewFile(); fis = new FileInputStream(from); ois = new FileOutputStream(to); in = new BufferedInputStream(fis); out = new BufferedOutputStream(ois); byte[] buf = new byte[2048]; int readBytes = 0; while ((readBytes = in.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, readBytes); } } catch (IOException e) { log.error(e); flag = false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { log.error(e); flag = false; } } return flag; }
00
Code Sample 1: @Override public void action(String msg, String uri, Gateway gateway) throws Exception { String city = "成都"; if (msg.indexOf("#") != -1) { city = msg.substring(msg.indexOf("#") + 1); } String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather?theCityCode={city}&theUserID="; url = url.replace("{city}", URLEncoder.encode(city, "UTF8")); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); if (conn.getResponseCode() == 200) { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(conn.getInputStream()); List strings = doc.getRootElement().getChildren(); String[] sugguestions = getText(strings.get(6)).split("\n"); StringBuffer buffer = new StringBuffer(); buffer.append("欢迎使用MapleSMS的天气服务!\n"); buffer.append("你查询的是 " + getText(strings.get(1)) + "的天气。\n"); buffer.append(getText(strings.get(4)) + "。\n"); buffer.append(getText(strings.get(5)) + "。\n"); buffer.append(sugguestions[0] + "\n"); buffer.append(sugguestions[1] + "\n"); buffer.append(sugguestions[7] + "\n"); buffer.append("感谢你使用MapleSMS的天气服务!祝你愉快!"); gateway.sendSMS(uri, buffer.toString()); } else { gateway.sendSMS(uri, "对不起,你输入的城市格式有误,请检查后再试~"); } } Code Sample 2: private static boolean initLOG4JProperties(String homeDir) { String Log4jURL = homeDir + LOG4J_URL; try { URL log4jurl = getURL(Log4jURL); InputStream inStreamLog4j = log4jurl.openStream(); Properties propertiesLog4j = new Properties(); try { propertiesLog4j.load(inStreamLog4j); PropertyConfigurator.configure(propertiesLog4j); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { logger.info("Failed to initialize LOG4J with properties file."); return false; } return true; }
11
Code Sample 1: public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } } Code Sample 2: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: public static void main(String[] args) { FTPClient f = new FTPClient(); String host = "ftpdatos.aemet.es"; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); final String datestamp = sdf.format(new Date()); System.out.println(datestamp); String pathname = "datos_observacion/observaciones_diezminutales/" + datestamp + "_diezminutales/"; try { InetAddress server = InetAddress.getByName(host); f.connect(server); String username = "anonymous"; String password = "a@b.c"; f.login(username, password); FTPFile[] files = f.listFiles(pathname, new FTPFileFilter() { @Override public boolean accept(FTPFile file) { return file.getName().startsWith(datestamp); } }); FTPFile file = files[files.length - 2]; f.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); boolean download = false; String remote = pathname + "/" + file.getName(); if (download) { File out = new File("/home/randres/Desktop/" + file.getName()); FileOutputStream fout = new FileOutputStream(out); System.out.println(f.retrieveFile(remote, fout)); fout.flush(); fout.close(); } else { GZIPInputStream gzipin = new GZIPInputStream(f.retrieveFileStream(remote)); LineNumberReader lreader = new LineNumberReader(new InputStreamReader(gzipin, "Cp1250")); String line = null; while ((line = lreader.readLine()) != null) { Aeminuto.processLine(line); } lreader.close(); } f.disconnect(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void actionPerformed(ActionEvent e) { int returnVal = chooser.showSaveDialog(jd); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String fileName = file.getPath(); String ext = StringUtil.getLowerExtension(fileName); if (!"png".equals(ext)) { fileName += ".png"; file = new File(fileName); } boolean doIt = true; if (file.exists()) { int i = JOptionPane.showConfirmDialog(jd, getMessage("warn_file_exist")); if (i != JOptionPane.YES_OPTION) doIt = false; } else if (!file.getParentFile().exists()) { doIt = file.getParentFile().mkdirs(); } if (doIt) { FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(imageURL.getPath()).getChannel(); dest = new FileOutputStream(fileName).getChannel(); src.transferTo(0, src.size(), dest); } catch (FileNotFoundException e1) { warn(jd, getMessage("err_no_source_file")); } catch (IOException e2) { warn(jd, getMessage("err_output_target")); } finally { try { if (src != null) src.close(); } catch (IOException e1) { } try { if (dest != null) dest.close(); } catch (IOException e1) { } src = null; dest = null; } } } }
00
Code Sample 1: public ObjectInputStream getObjectInputStreamFromServlet(String strUrl) throws Exception { if (cookie == null) { return null; } String starter = "-----------------------------"; String returnChar = "\r\n"; String lineEnd = "--"; String urlString = strUrl; String input = null; List txtList = new ArrayList(); List fileList = new ArrayList(); String targetFile = null; String actionStatus = null; StringBuffer returnMessage = new StringBuffer(); List head = new ArrayList(); final String boundary = String.valueOf(System.currentTimeMillis()); URL url = null; URLConnection conn = null; DataOutputStream dos = null; ObjectInputStream inputFromServlet = null; try { url = new URL(urlString); conn = url.openConnection(); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "multipart/form-data, boundary=" + "---------------------------" + boundary); conn.setRequestProperty(HEADER_COOKIE, cookie); if (input != null) { String auth = "Basic " + new sun.misc.BASE64Encoder().encode(input.getBytes()); conn.setRequestProperty("Authorization", auth); } dos = new DataOutputStream(conn.getOutputStream()); dos.flush(); inputFromServlet = new ObjectInputStream(conn.getInputStream()); txtList.clear(); fileList.clear(); } catch (Exception e) { log.error(e, e); return null; } finally { try { dos.close(); } catch (Exception e) { } } return inputFromServlet; } Code Sample 2: private static void copyFile(File sourceFile, File destFile) { try { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: private static URLConnection connectToNCBIValidator() throws IOException { final URL url = new URL(NCBI_URL); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", CONTENT_TYPE); return connection; } Code Sample 2: private boolean dependencyOutOfDate(ScriptCacheEntry entry) { if (entry != null) { for (Iterator i = entry.dependencies.keySet().iterator(); i.hasNext(); ) { URLConnection urlc = null; URL url = (URL) i.next(); try { urlc = url.openConnection(); urlc.setDoInput(false); urlc.setDoOutput(false); long dependentLastModified = urlc.getLastModified(); if (dependentLastModified > ((Long) entry.dependencies.get(url)).longValue()) { return true; } } catch (IOException ioe) { return true; } } } return false; }
00
Code Sample 1: public static InputStream getNotCacheResourceAsStream(final String fileName) { if ((fileName.indexOf("file:") >= 0) || (fileName.indexOf(":/") > 0)) { try { URL url = new URL(fileName); return new BufferedInputStream(url.openStream()); } catch (Exception e) { return null; } } return new ByteArrayInputStream(getNotCacheResource(fileName).getData()); } Code Sample 2: protected byte[] bytesFromJar(String path) throws IOException { URL url = new URL(path); InputStream is = url.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int n; while ((n = is.read(buffer)) >= 0) baos.write(buffer, 0, n); is.close(); return baos.toByteArray(); }
00
Code Sample 1: private void DrawModel(Graphics offg, int obj_num, boolean object, float h, float s, int vt_num, int fc_num) { int px[] = new int[3]; int py[] = new int[3]; int count = 0; int tmp[] = new int[fc_num]; double tmp_depth[] = new double[fc_num]; rotate(vt_num); offg.setColor(Color.black); for (int i = 0; i < fc_num; i++) { double a1 = fc[i].vt1.x - fc[i].vt0.x; double a2 = fc[i].vt1.y - fc[i].vt0.y; double a3 = fc[i].vt1.z - fc[i].vt0.z; double b1 = fc[i].vt2.x - fc[i].vt1.x; double b2 = fc[i].vt2.y - fc[i].vt1.y; double b3 = fc[i].vt2.z - fc[i].vt1.z; fc[i].nx = a2 * b3 - a3 * b2; fc[i].ny = a3 * b1 - a1 * b3; fc[i].nz = a1 * b2 - a2 * b1; if (fc[i].nz < 0) { fc[i].nx = a2 * b3 - a3 * b2; fc[i].ny = a3 * b1 - a1 * b3; tmp[count] = i; tmp_depth[count] = fc[i].getDepth(); count++; } } int lim = count - 1; do { int m = 0; for (int n = 0; n <= lim - 1; n++) { if (tmp_depth[n] < tmp_depth[n + 1]) { double t = tmp_depth[n]; tmp_depth[n] = tmp_depth[n + 1]; tmp_depth[n + 1] = t; int ti = tmp[n]; tmp[n] = tmp[n + 1]; tmp[n + 1] = ti; m = n; } } lim = m; } while (lim != 0); for (int m = 0; m < count; m++) { int i = tmp[m]; double l = Math.sqrt(fc[i].nx * fc[i].nx + fc[i].ny * fc[i].ny + fc[i].nz * fc[i].nz); test(offg, i, l, h, s); px[0] = (int) (fc[i].vt0.x * m_Scale + centerp.x); py[0] = (int) (-fc[i].vt0.y * m_Scale + centerp.y); px[1] = (int) (fc[i].vt1.x * m_Scale + centerp.x); py[1] = (int) (-fc[i].vt1.y * m_Scale + centerp.y); px[2] = (int) (fc[i].vt2.x * m_Scale + centerp.x); py[2] = (int) (-fc[i].vt2.y * m_Scale + centerp.y); offg.fillPolygon(px, py, 3); } if (labelFlag && object) { offg.setFont(Fonts.FONT_REAL); offg.drawString(d_con.getPointerData().getRealObjName(obj_num), (int) ((fc[0].vt0.x + 10) * m_Scale + centerp.x), (int) (-(fc[0].vt0.y + 10) * m_Scale + centerp.y)); } } Code Sample 2: @Override public URLConnection openConnection(URL url, Proxy proxy) throws IOException { if (null == url) { throw new IllegalArgumentException(Messages.getString("luni.1B")); } String host = url.getHost(); if (host == null || host.length() == 0 || host.equalsIgnoreCase("localhost")) { return new FileURLConnection(url); } URL ftpURL = new URL("ftp", host, url.getFile()); return (proxy == null) ? ftpURL.openConnection() : ftpURL.openConnection(proxy); }
00
Code Sample 1: public void startImport(ActionEvent evt) { final PsiExchange psiExchange = PsiExchangeFactory.createPsiExchange(IntactContext.getCurrentInstance().getSpringContext()); for (final URL url : urlsToImport) { try { if (log.isInfoEnabled()) log.info("Importing: " + url); psiExchange.importIntoIntact(url.openStream()); } catch (IOException e) { handleException(e); return; } } addInfoMessage("File successfully imported", Arrays.asList(urlsToImport).toString()); } Code Sample 2: public static String checkUpdate() { URL url = null; try { url = new URL("http://googlemeupdate.bravehost.com/"); } catch (MalformedURLException ex) { ex.printStackTrace(); } InputStream html = null; try { html = url.openStream(); int c = 0; String Buffer = ""; String Code = ""; while (c != -1) { try { c = html.read(); } catch (IOException ex) { } Buffer = Buffer + (char) c; } return Buffer.substring(Buffer.lastIndexOf("Google.mE Version: ") + 19, Buffer.indexOf("||")); } catch (IOException ex) { ex.printStackTrace(); return ""; } }
11
Code Sample 1: public static ObjectID[] sortDecending(ObjectID[] oids) { for (int i = 1; i < oids.length; i++) { ObjectID iId = oids[i]; for (int j = 0; j < oids.length - i; j++) { if (oids[j].getTypePrefix() > oids[j + 1].getTypePrefix()) { ObjectID temp = oids[j]; oids[j] = oids[j + 1]; oids[j + 1] = temp; } } } return oids; } Code Sample 2: public static int[] sortDescending(float input[]) { int[] order = new int[input.length]; for (int i = 0; i < order.length; i++) order[i] = i; for (int i = input.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (input[j] < input[j + 1]) { float mem = input[j]; input[j] = input[j + 1]; input[j + 1] = mem; int id = order[j]; order[j] = order[j + 1]; order[j + 1] = id; } } } return order; }
00
Code Sample 1: private void announce(String trackerURL, byte[] hash, byte[] peerId, int port) { try { String strUrl = trackerURL + "?info_hash=" + URLEncoder.encode(new String(hash, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&peer_id=" + URLEncoder.encode(new String(peerId, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&port=" + port + "&uploaded=0&downloaded=0&left=0&numwant=50&no_peer_id=1&compact=1"; URL url = new URL(strUrl); URLConnection con = url.openConnection(); con.connect(); con.getContent(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public boolean parseResults(URL url, String analysis_type, CurationI curation, Date analysis_date, String regexp) throws OutputMalFormatException { boolean parsed = false; try { InputStream data_stream = url.openStream(); parsed = parseResults(data_stream, analysis_type, curation, analysis_date, regexp); } catch (OutputMalFormatException ex) { throw new OutputMalFormatException(ex.getMessage(), ex); } catch (Exception ex) { System.out.println(ex.getMessage()); } return parsed; }
11
Code Sample 1: public static String md5(String text) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(text.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] bytes = msgDigest.digest(); String md5Str = new String(encodeHex(bytes)); return md5Str; } Code Sample 2: public static String login() throws Exception { if (sid == null) { String login = ROLAPClientAux.loadProperties().getProperty("user"); String password = ROLAPClientAux.loadProperties().getProperty("password"); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); String password2 = asHexString(md.digest()); String query = "/server/login?user=" + login + "&extern_password=" + password + "&password=" + password2; Vector<String> res = ROLAPClientAux.sendRequest(query); String vals[] = res.get(0).split(";"); sid = vals[0]; } return sid; }
11
Code Sample 1: private synchronized Frame addFrame(INSERT_TYPE type, File source) throws IOException { if (source == null) throw new NullPointerException("Parameter 'source' is null"); if (!source.exists()) throw new IOException("File does not exist: " + source.getAbsolutePath()); if (source.length() <= 0) throw new IOException("File is empty: " + source.getAbsolutePath()); File newLocation = new File(Settings.getPropertyString(ConstantKeys.project_dir), formatFileName(frames_.size())); if (newLocation.compareTo(source) != 0) { switch(type) { case MOVE: source.renameTo(newLocation); break; case COPY: FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(newLocation).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); break; } } Frame f = new Frame(newLocation); f.createThumbNail(); frames_.add(f); return f; } Code Sample 2: public he3Decode(String in_file) { try { File out = new File(in_file + extension); File in = new File(in_file); int file_size = (int) in.length(); FileInputStream in_stream = new FileInputStream(in_file); out.createNewFile(); FileOutputStream out_stream = new FileOutputStream(out.getName()); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; int buff_size = byte_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + "decoding: " + in_file + "\n" + "decoding to: " + in_file + extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = in_stream.read(byte_arr, 0, buff_size); if (_chars_read == -1) break; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\ndecoding: "); out_stream.write(_decode((ByteArrayOutputStream) os)); System.out.print("complete\n\n"); } catch (java.io.FileNotFoundException fnfEx) { System.err.println("Exception: " + fnfEx.getMessage()); } catch (java.io.IOException ioEx) { System.err.println("Exception: " + ioEx.getMessage()); } }
00
Code Sample 1: public String buscaCDA() { Properties prop = new CargaProperties().Carga(); URL url; BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("CDA")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("cda-TRUNK-")) { miLinea = inputLine; miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/dist/cda-TRUNK")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build CDA: " + miLinea); return miLinea; } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) try { inChannel.close(); } catch (Exception e) { } ; if (outChannel != null) try { outChannel.close(); } catch (Exception e) { } ; } }
00
Code Sample 1: private void readChildrenData() throws Exception { URL url; URLConnection connect; BufferedInputStream in; try { url = getURL("CHILDREN.TAB"); connect = url.openConnection(); InputStream ois = connect.getInputStream(); if (ois == null) { concepts3 = new IntegerArray(1); return; } in = new BufferedInputStream(ois); int k1 = in.read(); concepts3 = new IntegerArray(4096); StreamDecompressor sddocs = new StreamDecompressor(in); sddocs.ascDecode(k1, concepts3); int k2 = in.read(); offsets3 = new IntegerArray(concepts3.cardinality() + 1); offsets3.add(0); StreamDecompressor sdoffsets = new StreamDecompressor(in); sdoffsets.ascDecode(k2, offsets3); in.close(); url = getURL("CHILDREN"); connect = url.openConnection(); ois = connect.getInputStream(); if (ois == null) { concepts3 = new IntegerArray(1); return; } in = new BufferedInputStream(ois); int length = connect.getContentLength(); allChildren = new byte[length]; in.read(allChildren); in.close(); } catch (MalformedURLException e) { concepts3 = new IntegerArray(1); } catch (FileNotFoundException e2) { concepts3 = new IntegerArray(1); } catch (IOException e2) { concepts3 = new IntegerArray(1); } } Code Sample 2: public static void copyFile(String sourceFilePath, String destFilePath) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sourceFilePath).getChannel(); out = new FileOutputStream(destFilePath).getChannel(); long inputSize = in.size(); in.transferTo(0, inputSize, out); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, inputSize); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: public static File jar(File in, String outArc, File tempDir, PatchConfigXML conf) { FileOutputStream arcFile = null; JarOutputStream jout = null; DirectoryScanner ds = null; ds = new DirectoryScanner(); ds.setCaseSensitive(true); ds.setBasedir(in); ds.scan(); ds.setCaseSensitive(true); String[] names = ds.getIncludedFiles(); ArrayList exName = new ArrayList(); if (names == null || names.length < 1) return null; File tempArc = new File(tempDir, outArc.substring(0, outArc.length())); try { Manifest mf = null; List v = new ArrayList(); for (int i = 0; i < names.length; i++) { if (names[i].toUpperCase().indexOf("MANIFEST.MF") > -1) { FileInputStream fis = new FileInputStream(in.getAbsolutePath() + "/" + names[i].replace('\\', '/')); mf = new Manifest(fis); } else v.add(names[i]); } String[] toJar = new String[v.size()]; v.toArray(toJar); tempArc.createNewFile(); arcFile = new FileOutputStream(tempArc); if (mf == null) jout = new JarOutputStream(arcFile); else jout = new JarOutputStream(arcFile, mf); byte[] buffer = new byte[1024]; for (int i = 0; i < toJar.length; i++) { if (conf != null) { if (!conf.allowFileAction(toJar[i], PatchConfigXML.OP_CREATE)) { exName.add(toJar[i]); continue; } } String currentPath = in.getAbsolutePath() + "/" + toJar[i]; String entryName = toJar[i].replace('\\', '/'); JarEntry currentEntry = new JarEntry(entryName); jout.putNextEntry(currentEntry); FileInputStream fis = new FileInputStream(currentPath); int len; while ((len = fis.read(buffer)) >= 0) jout.write(buffer, 0, len); fis.close(); jout.closeEntry(); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { jout.close(); arcFile.close(); } catch (IOException e1) { throw new RuntimeException(e1); } } return tempArc; } Code Sample 2: public static String getEncryptedPassword(String password) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); } catch (Exception e) { throw new PasswordException(e); } return convertToString(md.digest()); }
11
Code Sample 1: 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!"); } Code Sample 2: public static final boolean zipUpdate(String zipfile, String name, String oldname, byte[] contents, boolean delete) { try { File temp = File.createTempFile("atf", ".zip"); InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); OutputStream os = new BufferedOutputStream(new FileOutputStream(temp)); ZipInputStream zin = new ZipInputStream(in); ZipOutputStream zout = new ZipOutputStream(os); ZipEntry e; ZipEntry e2; byte buffer[] = new byte[TEMP_FILE_BUFFER_SIZE]; int bytesRead; boolean found = false; boolean rename = false; String oname = name; if (oldname != null) { name = oldname; rename = true; } while ((e = zin.getNextEntry()) != null) { if (!e.isDirectory()) { String ename = e.getName(); if (delete && ename.equals(name)) continue; e2 = new ZipEntry(rename ? oname : ename); zout.putNextEntry(e2); if (ename.equals(name)) { found = true; zout.write(contents); } else { while ((bytesRead = zin.read(buffer)) != -1) zout.write(buffer, 0, bytesRead); } zout.closeEntry(); } } if (!found && !delete) { e = new ZipEntry(name); zout.putNextEntry(e); zout.write(contents); zout.closeEntry(); } zin.close(); zout.close(); File fp = new File(zipfile); fp.delete(); MLUtil.copyFile(temp, fp); temp.delete(); return (true); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } return (false); }
11
Code Sample 1: public static final void copyFile(File source, File target) { try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (java.io.IOException e) { } } Code Sample 2: public ResourceMigratorBuilder createResourceMigratorBuilder(NotificationReporter reporter) { return new ResourceMigratorBuilder() { public ResourceMigrator getCompletedResourceMigrator() { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; } public void setTarget(Version version) { } public void startType(String typeName) { } public void setRegexpPathRecogniser(String re) { } public void setCustomPathRecogniser(PathRecogniser pathRecogniser) { } public void addRegexpContentRecogniser(Version version, String re) { } public void addCustomContentRecogniser(Version version, ContentRecogniser contentRecogniser) { } public XSLStreamMigratorBuilder createXSLStreamMigratorBuilder() { return null; } public void addStep(Version inputVersion, Version outputVersion, StreamMigrator streamMigrator) { } public void endType() { } }; }
00
Code Sample 1: public boolean compile(URL url) { try { final InputStream stream = url.openStream(); final InputSource input = new InputSource(stream); input.setSystemId(url.toString()); return compile(input, _className); } catch (IOException e) { _parser.reportError(Constants.FATAL, new ErrorMsg(e)); return false; } } Code Sample 2: private int resourceToString(String aFile, StringBuffer aBuffer) { int cols = 0; URL url = getClass().getResource(aFile); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; do { line = in.readLine(); if (line != null) { if (line.length() > cols) cols = line.length(); aBuffer.append(line); aBuffer.append('\n'); } } while (line != null); } catch (IOException e) { e.printStackTrace(); } return cols; }
11
Code Sample 1: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); } Code Sample 2: private void insertContent(ImageData imageData, Element element) { URL url = getClass().getResource(imageData.getURL()); try { File imageFileRead = new File(url.toURI()); FileInputStream inputStream = new FileInputStream(imageFileRead); String imageFileWritePath = "htmlReportFiles" + "/" + imageData.getURL(); File imageFileWrite = new File(imageFileWritePath); String[] filePathTokens = imageFileWritePath.split("/"); String directoryPathCreate = filePathTokens[0]; int i = 1; while (i < filePathTokens.length - 1) { directoryPathCreate = directoryPathCreate + "/" + filePathTokens[i]; i++; } File fileDirectoryPathCreate = new File(directoryPathCreate); if (!fileDirectoryPathCreate.exists()) { boolean successfulFileCreation = fileDirectoryPathCreate.mkdirs(); if (successfulFileCreation == false) { throw new ExplanationException("Unable to create folders in path " + directoryPathCreate); } } FileOutputStream fileOutputStream = new FileOutputStream(imageFileWrite); byte[] data = new byte[1024]; int readDataNumberOfBytes = 0; while (readDataNumberOfBytes != -1) { readDataNumberOfBytes = inputStream.read(data, 0, data.length); if (readDataNumberOfBytes != -1) { fileOutputStream.write(data, 0, readDataNumberOfBytes); } } inputStream.close(); fileOutputStream.close(); } catch (Exception ex) { throw new ExplanationException(ex.getMessage()); } String caption = imageData.getCaption(); Element imageElement = element.addElement("img"); if (imageData.getURL().charAt(0) != '/') imageElement.addAttribute("src", "htmlReportFiles" + "/" + imageData.getURL()); else imageElement.addAttribute("src", "htmlReportFiles" + imageData.getURL()); imageElement.addAttribute("alt", "image not available"); if (caption != null) { element.addElement("br"); element.addText(caption); } }
00
Code Sample 1: public void store(String path, InputStream stream) throws IOException { toIgnore.add(normalizePath(path)); ZipEntry entry = new ZipEntry(path); zipOutput.putNextEntry(entry); IOUtils.copy(stream, zipOutput); zipOutput.closeEntry(); } Code Sample 2: @Test public void test_lookupType_FullSearch_TwoWords() throws Exception { URL url = new URL(baseUrl + "/lookupType/deep+core"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("[{\"itemTypeID\":11395,\"itemCategoryID\":16,\"name\":\"Deep Core Mining\",\"icon\":\"50_11\"},{\"itemTypeID\":12108,\"itemCategoryID\":7,\"name\":\"Deep Core Mining Laser I\",\"icon\":\"35_01\",\"metaLevel\":0},{\"itemTypeID\":12109,\"itemCategoryID\":9,\"name\":\"Deep Core Mining Laser I Blueprint\",\"icon\":\"12_08\"},{\"itemTypeID\":18068,\"itemCategoryID\":7,\"name\":\"Modulated Deep Core Miner II\",\"icon\":\"35_01\",\"metaLevel\":5},{\"itemTypeID\":18069,\"itemCategoryID\":9,\"name\":\"Modulated Deep Core Miner II Blueprint\",\"icon\":\"12_08\"},{\"itemTypeID\":24305,\"itemCategoryID\":7,\"name\":\"Modulated Deep Core Strip Miner II\",\"icon\":\"49_05\",\"metaLevel\":5},{\"itemTypeID\":24306,\"itemCategoryID\":9,\"name\":\"Modulated Deep Core Strip Miner II Blueprint\",\"icon\":\"12_08\"},{\"itemTypeID\":28748,\"itemCategoryID\":7,\"name\":\"ORE Deep Core Mining Laser\",\"icon\":\"35_01\",\"metaLevel\":6}]")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); }
00
Code Sample 1: public synchronized long nextValue(final Session session) { if (sequence < seqLimit) { return ++sequence; } else { final MetaDatabase db = MetaTable.DATABASE.of(table); Connection connection = null; ResultSet res = null; String sql = null; PreparedStatement statement = null; StringBuilder out = new StringBuilder(64); try { connection = session.getSeqConnection(db); String tableName = db.getDialect().printFullTableName(getTable(), true, out).toString(); out.setLength(0); out.setLength(0); sql = db.getDialect().printSequenceNextValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); int i = statement.executeUpdate(); if (i == 0) { out.setLength(0); sql = db.getDialect().printSequenceInit(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.executeUpdate(); } out.setLength(0); sql = db.getDialect().printSequenceCurrentValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); res = statement.executeQuery(); res.next(); seqLimit = res.getLong(1); int step = res.getInt(2); maxValue = res.getLong(3); sequence = (seqLimit - step) + 1; if (maxValue != 0L) { if (seqLimit > maxValue) { seqLimit = maxValue; if (sequence > maxValue) { String msg = "The sequence '" + tableName + "' needs to raise the maximum value: " + maxValue; throw new IllegalStateException(msg); } statement.close(); sql = db.getDialect().printSetMaxSequence(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.execute(); } if (maxValue > Long.MAX_VALUE - step) { String msg = "The sequence attribute '" + tableName + ".maxValue' is too hight," + " the recommended maximal value is: " + (Long.MAX_VALUE - step) + " (Long.MAX_VALUE-step)"; LOGGER.log(Level.WARNING, msg); } } connection.commit(); } catch (Throwable e) { if (connection != null) try { connection.rollback(); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "Rollback fails"); } IllegalStateException exception = e instanceof IllegalStateException ? (IllegalStateException) e : new IllegalStateException("ILLEGAL SQL: " + sql, e); throw exception; } finally { MetaDatabase.close(null, statement, res, true); } return sequence; } } Code Sample 2: private void copyOutResource(String dstPath, InputStream in) throws FileNotFoundException, IOException { FileOutputStream out = null; try { dstPath = this.outputDir + dstPath; File file = new File(dstPath); file.getParentFile().mkdirs(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } } }
11
Code Sample 1: private static URL downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } URL localURL = destFile.toURI().toURL(); return localURL; } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } } Code Sample 2: private void doConvert(HttpServletResponse response, ConversionRequestResolver rr, EGE ege, ConversionsPath cpath) throws FileUploadException, IOException, RequestResolvingException, EGEException, FileNotFoundException, ConverterException, ZipException { InputStream is = null; OutputStream os = null; if (ServletFileUpload.isMultipartContent(rr.getRequest())) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(rr.getRequest()); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { is = item.openStream(); applyConversionsProperties(rr.getConversionProperties(), cpath); DataBuffer buffer = new DataBuffer(0, EGEConstants.BUFFER_TEMP_PATH); String alloc = buffer.allocate(is); InputStream ins = buffer.getDataAsStream(alloc); is.close(); try { ValidationResult vRes = ege.performValidation(ins, cpath.getInputDataType()); if (vRes.getStatus().equals(ValidationResult.Status.FATAL)) { ValidationServlet valServ = new ValidationServlet(); valServ.printValidationResult(response, vRes); try { ins.close(); } finally { buffer.removeData(alloc, true); } return; } } catch (ValidatorException vex) { LOGGER.warn(vex.getMessage()); } finally { try { ins.close(); } catch (Exception ex) { } } File zipFile = null; FileOutputStream fos = null; String newTemp = UUID.randomUUID().toString(); IOResolver ior = EGEConfigurationManager.getInstance().getStandardIOResolver(); File buffDir = new File(buffer.getDataDir(alloc)); zipFile = new File(EGEConstants.BUFFER_TEMP_PATH + File.separator + newTemp + EZP_EXT); fos = new FileOutputStream(zipFile); ior.compressData(buffDir, fos); ins = new FileInputStream(zipFile); File szipFile = new File(EGEConstants.BUFFER_TEMP_PATH + File.separator + newTemp + ZIP_EXT); fos = new FileOutputStream(szipFile); try { try { ege.performConversion(ins, fos, cpath); } finally { fos.close(); } boolean isComplex = EGEIOUtils.isComplexZip(szipFile); response.setContentType(APPLICATION_OCTET_STREAM); String fN = item.getName().substring(0, item.getName().lastIndexOf(".")); if (isComplex) { String fileExt; if (cpath.getOutputDataType().getMimeType().equals(APPLICATION_MSWORD)) { fileExt = DOCX_EXT; } else { fileExt = ZIP_EXT; } response.setHeader("Content-Disposition", "attachment; filename=\"" + fN + fileExt + "\""); FileInputStream fis = new FileInputStream(szipFile); os = response.getOutputStream(); try { EGEIOUtils.copyStream(fis, os); } finally { fis.close(); } } else { String fileExt = getMimeExtensionProvider().getFileExtension(cpath.getOutputDataType().getMimeType()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fN + fileExt + "\""); os = response.getOutputStream(); EGEIOUtils.unzipSingleFile(new ZipFile(szipFile), os); } } finally { ins.close(); if (os != null) { os.flush(); os.close(); } buffer.clear(true); szipFile.delete(); if (zipFile != null) { zipFile.delete(); } } } } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } }
11
Code Sample 1: public static Photo createPhoto(String title, String userLogin, String pathToPhoto, String basePathImage) throws NoSuchAlgorithmException, IOException { String id = CryptSHA1.genPhotoID(userLogin, title); String extension = pathToPhoto.substring(pathToPhoto.lastIndexOf(".")); String destination = basePathImage + id + extension; FileInputStream fis = new FileInputStream(pathToPhoto); FileOutputStream fos = new FileOutputStream(destination); FileChannel fci = fis.getChannel(); FileChannel fco = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int read = fci.read(buffer); if (read == -1) break; buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); fco.close(); fos.close(); fis.close(); ImageIcon image; ImageIcon thumb; String destinationThumb = basePathImage + "thumb/" + id + extension; image = new ImageIcon(destination); int maxSize = 150; int origWidth = image.getIconWidth(); int origHeight = image.getIconHeight(); if (origWidth > origHeight) { thumb = new ImageIcon(image.getImage().getScaledInstance(maxSize, -1, Image.SCALE_SMOOTH)); } else { thumb = new ImageIcon(image.getImage().getScaledInstance(-1, maxSize, Image.SCALE_SMOOTH)); } BufferedImage bi = new BufferedImage(thumb.getIconWidth(), thumb.getIconHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.drawImage(thumb.getImage(), 0, 0, null); try { ImageIO.write(bi, "JPG", new File(destinationThumb)); } catch (IOException ioe) { System.out.println("Error occured saving thumbnail"); } Photo photo = new Photo(id); photo.setTitle(title); photo.basePathImage = basePathImage; return photo; } Code Sample 2: 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(); } }
11
Code Sample 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(); } } Code Sample 2: public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = dest.getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: public String getHtmlCode(String urlString) { StringBuffer result = new StringBuffer(); BufferedReader in = null; try { URL url = new URL((urlString)); URLConnection con = url.openConnection(); in = new BufferedReader(new InputStreamReader(con.getInputStream(), "ISO-8859-1")); String line = null; while ((line = in.readLine()) != null) { result.append(line + "\r\n"); } in.close(); } catch (MalformedURLException e) { System.out.println("Unable to connect to URL: " + urlString); } catch (IOException e) { System.out.println("IOException when connecting to URL: " + urlString); } finally { if (in != null) { try { in.close(); } catch (Exception ex) { System.out.println("Exception throws at finally close reader when connecting to URL: " + urlString); } } } return result.toString(); } Code Sample 2: 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; }
11
Code Sample 1: private void copy(File source, File dest) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { close(in); close(out); } } Code Sample 2: 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); }
00
Code Sample 1: private void show(String fileName, HttpServletResponse response) throws IOException { TelnetInputStream ftpIn = ftpClient_sun.get(fileName); OutputStream out = null; try { out = response.getOutputStream(); IOUtils.copy(ftpIn, out); } finally { if (ftpIn != null) { ftpIn.close(); } } } Code Sample 2: public void sendPOIGpxLocation() { this.myloc = new Position(45.56, 5.9); this.left = myloc.getY() - 0.025; this.right = myloc.getY() + 0.025; this.top = myloc.getX() + 0.03; this.bottom = myloc.getX() - 0.03; assertEquals("left test", left, (5.9 - 0.025)); assertEquals("right test", right, (5.9 + 0.025)); assertEquals("top test", top, (45.56 - 0.025)); assertEquals("bottom test", left, (45.56 + 0.025)); this.poisCheck.add("amenity"); try { if (this.poisCheck.get(0).compareTo("None") == 0) { model.setPointsOfInterest(new Items()); } else { this.url = new URL("http://www.informationfreeway.org/api/0.6/node[" + poisCheck.get(0) + "=*][bbox=" + left + "," + bottom + "," + right + "," + top + "]"); assertEquals("url informationfreeway.org test", url, "http://www.informationfreeway.org/api/0.6/node[amenity=*]" + "[bbox=" + left + "," + bottom + "," + right + "," + top + "]"); SAXParser pars = null; ParsePoiGpx gpxHandler = new ParsePoiGpx(poisCheck, this.model.getContext()); pars = SAXParserFactory.newInstance().newSAXParser(); pars.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true); pars.parse(url.openStream(), gpxHandler); this.pois = gpxHandler.getPOIResultsItems(); assertTrue("there is some pois", !this.pois.equals(0)); assertFalse("there is some pois", this.pois.equals(0)); } } catch (Exception e) { e.printStackTrace(); assertFalse(!e.getCause().equals(null)); } }
11
Code Sample 1: public static void copy(File inputFile, File target) throws IOException { if (!inputFile.exists()) return; OutputStream output = new FileOutputStream(target); InputStream input = new BufferedInputStream(new FileInputStream(inputFile)); int b; while ((b = input.read()) != -1) output.write(b); output.close(); input.close(); } Code Sample 2: @SuppressWarnings("static-access") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { filename = URLDecoder.decode(filename, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { is = request.getInputStream(); File newFile = new File(realPath + filename); if (!newFile.exists()) { fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true,detailMsg}"); } else { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false,detailMsg:'文件已经存在!请重命名后上传!'}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + filename + " has existed!"); } } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
00
Code Sample 1: public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } return hexString.toString(); } Code Sample 2: private void copyFile(File f) throws IOException { File newFile = new File(destdir + "/" + f.getName()); newFile.createNewFile(); FileInputStream fin = new FileInputStream(f); FileOutputStream fout = new FileOutputStream(newFile); int c; while ((c = fin.read()) != -1) fout.write(c); fin.close(); fout.close(); }