label
int64 0
1
| func1
stringlengths 173
53.1k
| func2
stringlengths 173
53.1k
| id
int64 0
901k
|
---|---|---|---|
0 | public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } | public boolean storeFile(String local, String remote) throws IOException { boolean stored = false; GridFTP ftp = new GridFTP(); ftp.setDefaultPort(port); System.out.println(this + ".storeFile " + remote); try { ftp.connect(host); ftp.login(username, password); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return false; } ftp.put(local, remote); ftp.logout(); stored = true; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } return stored; } | 1,000 |
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!"); } | public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } | 1,001 |
0 | private static void salvarObra(Artista artista, Obra obra) throws Exception { Connection conn = null; PreparedStatement ps = null; int categoria; System.out.println("Migracao.salvarObra() obra: " + obra.toString2()); if (obra.getCategoria() != null) { categoria = getCategoria(obra.getCategoria().getNome()).getCodigo(); } else { categoria = getCategoria("Sem Categoria").getCodigo(); } try { conn = C3P0Pool.getConnection(); String sql = "insert into obra VALUES (?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setNull(1, Types.INTEGER); ps.setString(2, obra.getTitulo()); ps.setInt(3, obra.getSelec()); ps.setInt(4, categoria); ps.setInt(5, artista.getNumeroInscricao()); ps.setInt(6, obra.getCodigo()); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } | public static Element postMessage() throws Exception { final URL theUrl = getHostURL(); lf.debug("url = " + theUrl.toExternalForm()); final HttpURLConnection urlConn = (HttpURLConnection) (theUrl).openConnection(); urlConn.setRequestMethod("POST"); urlConn.setDoInput(true); urlConn.setDoOutput(true); final BufferedOutputStream bos = new BufferedOutputStream(urlConn.getOutputStream()); final InputStream bis = urlConn.getInputStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int count = 0; while ((count = bis.read(buffer)) > -1) { baos.write(buffer, 0, count); } final SAXBuilder sb = new SAXBuilder(); lf.debug("Received XML response from server: " + baos.toString()); return sb.build(new StringReader(baos.toString())).getRootElement(); } | 1,002 |
0 | public XMLTreeView(JFrame frame, Web3DService web3DService) { frame.getContentPane().setLayout(new BorderLayout()); DefaultMutableTreeNode top = new DefaultMutableTreeNode(file); saxTree = new SAXTreeBuilder(top); InputStream urlIn = null; try { SAXParser saxParser = new SAXParser(); saxParser.setContentHandler(saxTree); String request = web3DService.getServiceEndPoint() + "?" + "SERVICE=" + web3DService.getService() + "&" + "REQUEST=GetCapabilities&" + "ACCEPTFORMATS=text/xml&" + "ACCEPTVERSIONS="; for (int i = 0; i < web3DService.getAcceptVersions().length; i++) { if (i > 0) request += ","; request += web3DService.getAcceptVersions()[i]; } System.out.println(request); URL url = new URL(request); URLConnection urlc = url.openConnection(); urlc.setReadTimeout(Navigator.TIME_OUT); if (web3DService.getEncoding() != null) { urlc.setRequestProperty("Authorization", "Basic " + web3DService.getEncoding()); } urlIn = urlc.getInputStream(); saxParser.parse(new InputSource(urlIn)); } catch (Exception ex) { top.add(new DefaultMutableTreeNode(ex.getMessage())); } try { urlIn.close(); } catch (Exception e) { } JTree tree = new JTree(saxTree.getTree()); JScrollPane scrollPane = new JScrollPane(tree); frame.getContentPane().add("Center", scrollPane); frame.setVisible(true); } | protected void processAnnotationsJndi(URL url) { try { URLConnection urlConn = url.openConnection(); DirContextURLConnection dcUrlConn; if (!(urlConn instanceof DirContextURLConnection)) { sm.getString("contextConfig.jndiUrlNotDirContextConn", url); return; } dcUrlConn = (DirContextURLConnection) urlConn; dcUrlConn.setUseCaches(false); String type = dcUrlConn.getHeaderField(ResourceAttributes.TYPE); if (ResourceAttributes.COLLECTION_TYPE.equals(type)) { Enumeration<String> dirs = dcUrlConn.list(); while (dirs.hasMoreElements()) { String dir = dirs.nextElement(); URL dirUrl = new URL(url.toString() + '/' + dir); processAnnotationsJndi(dirUrl); } } else { if (url.getPath().endsWith(".class")) { InputStream is = null; try { is = dcUrlConn.getInputStream(); processAnnotationsStream(is); } catch (IOException e) { logger.error(sm.getString("contextConfig.inputStreamJndi", url), e); } finally { if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } } } catch (IOException e) { logger.error(sm.getString("contextConfig.jndiUrl", url), e); } } | 1,003 |
1 | public static void addClasses(URL url) { BufferedReader reader = null; String line; ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { line = line.trim(); if ((line.length() == 0) || line.startsWith(";")) { continue; } try { classes.add(Class.forName(line, true, cl)); } catch (Throwable t) { } } } catch (Throwable t) { } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } } | private static String sendGetRequest(String endpoint, String requestParameters) throws Exception { String result = null; if (endpoint.startsWith("http://")) { StringBuffer data = new StringBuffer(); String urlStr = prepareUrl(endpoint, requestParameters); URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } return result; } | 1,004 |
0 | public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); } | public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } | 1,005 |
0 | @Override protected String doIt() throws Exception { PreparedStatement insertStmt = null; try { insertStmt = DB.prepareStatement("INSERT INTO AD_Sequence_No(AD_SEQUENCE_ID, CALENDARYEAR, " + "AD_CLIENT_ID, AD_ORG_ID, ISACTIVE, CREATED, CREATEDBY, " + "UPDATED, UPDATEDBY, CURRENTNEXT) " + "(SELECT AD_Sequence_ID, '" + year + "', " + "AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, " + "Updated, UpdatedBy, StartNo " + "FROM AD_Sequence a " + "WHERE StartNewYear = 'Y' AND NOT EXISTS ( " + "SELECT AD_Sequence_ID " + "FROM AD_Sequence_No b " + "WHERE a.AD_Sequence_ID = b.AD_Sequence_ID " + "AND CalendarYear = ?)) ", get_TrxName()); insertStmt.setString(1, year); insertStmt.executeUpdate(); commit(); } catch (Exception ex) { rollback(); throw ex; } finally { DB.close(insertStmt); } return "Sequence No updated successfully"; } | public void url2SaveAsFile(String urlStr, String saveAsFileName) throws Exception { URL url = new URL(urlStr); URLConnection uc = url.openConnection(); File f = new File(saveAsFileName); if (!f.exists()) { FileOutputStream fos = new FileOutputStream(f); BufferedInputStream bis = new BufferedInputStream(uc.getInputStream()); byte[] buffer = new byte[4096]; int readCount = 0; while ((readCount = bis.read(buffer)) != -1) { fos.write(buffer, 0, readCount); } fos.flush(); fos.close(); bis.close(); } } | 1,006 |
1 | public static void copyFile(final FileInputStream in, final File out) throws IOException { final FileChannel inChannel = in.getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } | 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(); } } | 1,007 |
1 | @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final Map<String, String> fileAttr = new HashMap<String, String>(); boolean download = false; String dw = req.getParameter("d"); if (StringUtils.isNotEmpty(dw) && StringUtils.equals(dw, "true")) { download = true; } final ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream(DEFAULT_CONTENT_LENGTH_SIZE); InputStream imageInputStream = null; try { imageInputStream = getImageAsStream(req, fileAttr); IOUtils.copy(imageInputStream, imageOutputStream); resp.setHeader("Cache-Control", "no-store"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType(fileAttr.get("mimetype")); if (download) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileAttr.get("filename") + "\""); } final ServletOutputStream responseOutputStream = resp.getOutputStream(); responseOutputStream.write(imageOutputStream.toByteArray()); responseOutputStream.flush(); responseOutputStream.close(); } catch (Exception e) { e.printStackTrace(); resp.setContentType("text/html"); resp.getWriter().println("<h1>Sorry... cannot find document</h1>"); } finally { IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(imageOutputStream); } } | public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception { String attachmentName = request.getParameter("attachment"); String virtualWiki = getVirtualWiki(request); File uploadPath = getEnvironment().uploadPath(virtualWiki, attachmentName); response.reset(); response.setHeader("Content-Disposition", getEnvironment().getStringSetting(Environment.PROPERTY_ATTACHMENT_TYPE) + ";filename=" + attachmentName + ";"); int dotIndex = attachmentName.indexOf('.'); if (dotIndex >= 0 && dotIndex < attachmentName.length() - 1) { String extension = attachmentName.substring(attachmentName.lastIndexOf('.') + 1); logger.fine("Extension: " + extension); String mimetype = (String) getMimeByExtension().get(extension.toLowerCase()); logger.fine("MIME: " + mimetype); if (mimetype != null) { logger.fine("Setting content type to: " + mimetype); response.setContentType(mimetype); } } FileInputStream in = null; ServletOutputStream out = null; try { in = new FileInputStream(uploadPath); out = response.getOutputStream(); IOUtils.copy(in, out); out.flush(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } | 1,008 |
0 | public void testSimpleBasicHttpRequests() throws Exception { int reqNo = 20; Random rnd = new Random(); final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String s = request.getRequestLine().getUri(); if (s.startsWith("/?")) { s = s.substring(2); } int index = Integer.parseInt(s); byte[] data = (byte[]) testData.get(index); ByteArrayEntity entity = new ByteArrayEntity(data); response.setEntity(entity); } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpRequest get = new BasicHttpRequest("GET", "/?" + r); HttpResponse response = this.client.execute(get, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } | public void delete(String language, String tag, int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { String sql = "delete from LanguageMorphologies " + "where LanguageName = '" + language + "' and MorphologyTag = '" + tag + "' and " + " Rank = " + row; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate(sql); bumpAllRowsUp(stmt, language, tag, row); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } | 1,009 |
1 | private void listAndInstantiateServiceProviders() { final Enumeration<URL> resources = ClassLoaderHelper.getResources(SERVICES_FILE, ServiceManager.class); String name; try { while (resources.hasMoreElements()) { URL url = resources.nextElement(); InputStream stream = url.openStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream), 100); name = reader.readLine(); while (name != null) { name = name.trim(); if (!name.startsWith("#")) { final ServiceProvider<?> serviceProvider = ClassLoaderHelper.instanceFromName(ServiceProvider.class, name, ServiceManager.class, "service provider"); @SuppressWarnings("unchecked") final Class<ServiceProvider<?>> serviceProviderClass = (Class<ServiceProvider<?>>) serviceProvider.getClass(); managedProviders.put(serviceProviderClass, new ServiceProviderWrapper(serviceProvider)); } name = reader.readLine(); } } finally { stream.close(); } } } catch (IOException e) { throw new SearchException("Unable to read " + SERVICES_FILE, e); } } | 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(); } | 1,010 |
1 | private String getPlayerName(String id) throws UnsupportedEncodingException, IOException { String result = ""; Map<String, String> players = (Map<String, String>) sc.getAttribute("players"); if (players.containsKey(id)) { result = players.get(id); System.out.println("skip name:" + result); } else { String palyerURL = "http://goal.2010worldcup.163.com/player/" + id + ".html"; URL url = new URL(palyerURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; String nameFrom = "英文名:"; String nameTo = "</dd>"; while ((line = reader.readLine()) != null) { if (line.indexOf(nameFrom) != -1) { result = line.substring(line.indexOf(nameFrom) + nameFrom.length(), line.indexOf(nameTo)); break; } } reader.close(); players.put(id, result); } return result; } | public static String getRandomUserAgent() { if (USER_AGENT_CACHE == null) { Collection<String> userAgentsCache = new ArrayList<String>(); try { URL url = Tools.getResource(UserAgent.class.getClassLoader(), "user-agents-browser.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { userAgentsCache.add(str); } in.close(); USER_AGENT_CACHE = userAgentsCache.toArray(new String[userAgentsCache.size()]); } catch (Exception e) { System.err.println("Can not read file; using default user-agent; error message: " + e.getMessage()); return DEFAULT_USER_AGENT; } } return USER_AGENT_CACHE[new Random().nextInt(USER_AGENT_CACHE.length)]; } | 1,011 |
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: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </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()); } | 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(); } | 1,012 |
1 | private void fileCopy(final File src, final File dest) throws IOException { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } | 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: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </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()); } | 1,013 |
0 | private HttpURLConnection getConnection() throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(method); conn.setDoOutput(true); conn.setDoInput(true); if (cookie != null) conn.setRequestProperty("Cookie", cookie); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.setRequestProperty("User-Agent", Constants.USER_AGENT()); conn.connect(); if (!parameters.equals("")) { DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(parameters); out.flush(); out.close(); } return conn; } | public void remove(String oid) throws PersisterException { String key = getLock(oid); if (key == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(key)) { throw new PersisterException("The object is currently locked: OID = " + oid + ", LOCK = " + key); } Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("delete from " + _table_name + " where " + _oid_col + " = ?"); ps.setString(1, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to delete object: OID = " + oid, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } } | 1,014 |
0 | protected void load() throws IOException { for (ClassLoader classLoader : classLoaders) { Enumeration<URL> en = classLoader.getResources("META-INF/services/" + serviceClass.getName()); while (en.hasMoreElements()) { URL url = en.nextElement(); InputStream in = url.openStream(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); try { String line = null; while ((line = reader.readLine()) != null) { if (!line.startsWith("#")) { line = line.trim(); if (line.length() > 0) contributions.add(resolveClass(url, line)); } } } finally { reader.close(); } } finally { in.close(); } } } } | public static String hexMD5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(value.getBytes("utf-8")); byte[] digest = messageDigest.digest(); return byteToHexString(digest); } catch (Exception ex) { throw new UnexpectedException(ex); } } | 1,015 |
1 | public static void copy(String a, String b) throws IOException { File inputFile = new File(a); File outputFile = new File(b); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } | private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } | 1,016 |
0 | private void readFromFile1() throws DException { URL url1 = null; if (url == null) { url = getClass().getResource("/com/daffodilwoods/daffodildb/utils/parser/parser.schema"); try { url = new URL(url.getProtocol() + ":" + url.getPath().substring(0, url.getPath().indexOf("/parser.schema"))); } catch (MalformedURLException ex2) { ex2.printStackTrace(); throw new DException("DSE0", new Object[] { ex2 }); } try { url1 = new URL(url.getProtocol() + ":" + url.getPath() + "/parser.schema"); } catch (MalformedURLException ex) { throw new DException("DSE0", new Object[] { ex }); } if (url1 == null) { throw new DException("DSE0", new Object[] { "Parser.schema file is missing in classpath." }); } } else { try { url1 = new URL(url.getProtocol() + ":" + url.getPath() + "/parser.schema"); } catch (MalformedURLException ex) { throw new DException("DSE0", new Object[] { ex }); } } ArrayList arr1 = null; StringBuffer rule = null; try { LineNumberReader raf = new LineNumberReader(new BufferedReader(new InputStreamReader(url1.openStream()))); arr1 = new ArrayList(); rule = new StringBuffer(""); while (true) { String str1 = raf.readLine(); if (str1 == null) { break; } String str = str1.trim(); if (str.length() == 0) { if (rule.length() > 0) { arr1.add(rule.toString()); } rule = new StringBuffer(""); } else { rule.append(" ").append(str); } } raf.close(); } catch (IOException ex1) { ex1.printStackTrace(); throw new DException("DSE0", new Object[] { ex1 }); } if (rule.length() > 0) arr1.add(rule.toString()); for (int i = 0; i < arr1.size(); i++) { String str = (String) arr1.get(i); int index = str.indexOf("::="); if (index == -1) { P.pln("Error " + str); throw new DException("DSE0", new Object[] { "Rule is missing from parser.schema" }); } String key = str.substring(0, index).trim(); String value = str.substring(index + 3).trim(); Object o = fileEntries.put(key, value); if (o != null) { new Exception("Duplicate Defination for Rule [" + key + "] Value [" + value + "] Is Replaced By [" + o + "]").printStackTrace(); } } } | public void createVendorSignature() { byte b; try { _vendorMessageDigest = MessageDigest.getInstance("MD5"); _vendorSig = Signature.getInstance("MD5/RSA/PKCS#1"); _vendorSig.initSign((PrivateKey) _vendorPrivateKey); _vendorMessageDigest.update(getBankString().getBytes()); _vendorMessageDigestBytes = _vendorMessageDigest.digest(); _vendorSig.update(_vendorMessageDigestBytes); _vendorSignatureBytes = _vendorSig.sign(); } catch (Exception e) { } ; } | 1,017 |
0 | private static void salvarCategoria(Categoria categoria) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "insert into categoria VALUES (?,?)"; ps = conn.prepareStatement(sql); ps.setNull(1, Types.INTEGER); ps.setString(2, categoria.getNome()); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } | public static String readURL(String urlStr, boolean debug) { if (debug) System.out.print(" trying: " + urlStr + "\n"); URL url = null; try { url = new URL(urlStr); } catch (java.net.MalformedURLException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentType = huc.getContentType(); if (contentType == null || contentType.indexOf("text/xml") < 0) { System.out.print("*** Warning *** Content-Type not set to text/xml"); System.out.print('\n'); System.out.print(" Content-type: "); System.out.print(contentType); System.out.print('\n'); } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { System.out.print("test failed: opening URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading first line of response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } if (inputLine == null) { System.out.print("test failed: No input read from URL"); System.out.print('\n'); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); System.out.print(" successfully applied stylesheet '"); System.out.print(href); System.out.print("'"); System.out.print('\n'); } catch (javax.xml.transform.TransformerException e) { System.out.print("unable to apply stylesheet '"); System.out.print(href); System.out.print("'to response: "); System.out.print(e.getMessage()); System.out.print('\n'); e.printStackTrace(); } } return contentStr; } | 1,018 |
1 | protected byte[] computeHash() { try { final MessageDigest inputHash = MessageDigest.getInstance("SHA"); inputHash.update(bufferFileData().getBytes()); return inputHash.digest(); } catch (final NoSuchAlgorithmException nsae) { lastException = nsae; return new byte[0]; } catch (final IOException ioe) { lastException = ioe; return new byte[0]; } } | public static final String enctrypt(String password) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); throw new RuntimeException("NoSuchAlgorithmException SHA1"); } md.reset(); md.update(password.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } | 1,019 |
0 | public <T extends FetionResponse> T executeAction(FetionAction<T> fetionAction) throws IOException { URL url = new URL(fetionAction.getProtocol().name().toLowerCase() + "://" + fetionUrl + fetionAction.getRequestData()); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); byte[] buffer = new byte[10240]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); int read = 0; while ((read = in.read(buffer)) > 0) { bout.write(buffer, 0, read); } return fetionAction.processResponse(parseRawResponse(bout.toByteArray())); } | byte[] calculateDigest(String value) { try { MessageDigest mg = MessageDigest.getInstance("SHA1"); mg.update(value.getBytes()); return mg.digest(); } catch (Exception e) { throw Bark.unchecker(e); } } | 1,020 |
1 | private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } | private void copyXsl(File aTargetLogDir) { Trace.println(Trace.LEVEL.UTIL, "copyXsl( " + aTargetLogDir.getName() + " )", true); if (myXslSourceDir == null) { return; } File[] files = myXslSourceDir.listFiles(); for (int i = 0; i < files.length; i++) { File srcFile = files[i]; if (!srcFile.isDirectory()) { File tgtFile = new File(aTargetLogDir + File.separator + srcFile.getName()); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(srcFile).getChannel(); outChannel = new FileOutputStream(tgtFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new IOError(e); } finally { if (inChannel != null) try { inChannel.close(); } catch (IOException exc) { throw new IOError(exc); } if (outChannel != null) try { outChannel.close(); } catch (IOException exc) { throw new IOError(exc); } } } } } | 1,021 |
0 | public int read(String name) { status = STATUS_OK; try { name = name.trim(); if (name.indexOf("://") > 0) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; } | public void run() { StringBuffer messageStringBuffer = new StringBuffer(); messageStringBuffer.append("Program: \t" + UpdateChannel.getCurrentChannel().getApplicationTitle() + "\n"); messageStringBuffer.append("Version: \t" + Lister.version + "\n"); messageStringBuffer.append("Revision: \t" + Lister.revision + "\n"); messageStringBuffer.append("Channel: \t" + UpdateChannel.getCurrentChannel().getName() + "\n"); messageStringBuffer.append("Date: \t\t" + Lister.date + "\n\n"); messageStringBuffer.append("OS: \t\t" + System.getProperty("os.name") + " (" + System.getProperty("os.version") + ")\n"); messageStringBuffer.append("JAVA: \t\t" + System.getProperty("java.version") + " (" + System.getProperty("java.specification.vendor") + ")\n"); messageStringBuffer.append("Desktop: \t" + System.getProperty("sun.desktop") + "\n"); messageStringBuffer.append("Language: \t" + Language.getCurrentInstance() + "\n\n"); messageStringBuffer.append("------------------------------------------\n"); if (summary != null) { messageStringBuffer.append(summary + "\n\n"); } messageStringBuffer.append("Details:\n"); if (description != null) { messageStringBuffer.append(description); } if (exception != null) { messageStringBuffer.append("\n\nStacktrace:\n"); printStackTrace(exception, messageStringBuffer); } try { if (dialog != null) { setComponentsEnabled(dialog.getContentPane(), false); } URL url = UpdateChannel.getCurrentChannel().getErrorReportURL(); URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); if (sender != null) { outputStreamWriter.write(URLEncoder.encode("sender", "UTF-8") + "=" + URLEncoder.encode(sender, "UTF-8")); outputStreamWriter.write("&"); } outputStreamWriter.write(URLEncoder.encode("report", "UTF-8") + "=" + URLEncoder.encode(messageStringBuffer.toString(), "UTF-8")); if (attachErrorLog) { outputStreamWriter.write("&"); outputStreamWriter.write(URLEncoder.encode("error.log", "UTF-8") + "=" + URLEncoder.encode(Logger.getErrorLogContent(), "UTF-8")); } outputStreamWriter.flush(); urlConnection.getInputStream().close(); outputStreamWriter.close(); if (dialog != null) { dialog.dispose(); } JOptionPane.showMessageDialog(Lister.getCurrentInstance(), Language.translateStatic("MESSAGE_ERRORREPORTSENT")); } catch (Exception exception) { ErrorJDialog.showErrorDialog(dialog, exception); if (dialog != null) { setComponentsEnabled(dialog.getContentPane(), true); } } } | 1,022 |
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!"); } | static void cleanFile(File file) { final Counter cnt = new Counter(); final File out = new File(FileUtils.appendToFileName(file.getAbsolutePath(), ".cleaned")); final SAMFileReader reader = new SAMFileReader(file); final SAMRecordIterator it = reader.iterator(); final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, out); if (!it.hasNext()) return; log.info("Cleaning file " + file + " to " + out.getName()); SAMRecord last = it.next(); writer.addAlignment(last); while (it.hasNext()) { final SAMRecord now = it.next(); final int start1 = last.getAlignmentStart(); final int start2 = now.getAlignmentStart(); final int end1 = last.getAlignmentEnd(); final int end2 = now.getAlignmentEnd(); if (start1 == start2 && end1 == end2) { log.debug("Discarding record " + now.toString()); cnt.count(); continue; } writer.addAlignment(now); last = now; } writer.close(); reader.close(); log.info(file + " done, discarded " + cnt.getCount() + " reads"); exe.shutdown(); } | 1,023 |
1 | private void initialize() { StringBuffer license = new StringBuffer(); URL url; InputStreamReader in; BufferedReader reader; String str; JTextArea textArea; JButton button; GridBagConstraints c; setTitle("Mibble License"); setSize(600, 600); setDefaultCloseOperation(DISPOSE_ON_CLOSE); getContentPane().setLayout(new GridBagLayout()); url = getClass().getClassLoader().getResource("LICENSE.txt"); if (url == null) { license.append("Couldn't locate license file (LICENSE.txt)."); } else { try { in = new InputStreamReader(url.openStream()); reader = new BufferedReader(in); while ((str = reader.readLine()) != null) { if (!str.equals(" ")) { license.append(str); } license.append("\n"); } reader.close(); } catch (IOException e) { license.append("Error reading license file "); license.append("(LICENSE.txt):\n\n"); license.append(e.getMessage()); } } textArea = new JTextArea(license.toString()); textArea.setEditable(false); c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0d; c.weighty = 1.0d; c.insets = new Insets(4, 5, 4, 5); getContentPane().add(new JScrollPane(textArea), c); button = new JButton("Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); c = new GridBagConstraints(); c.gridy = 1; c.anchor = GridBagConstraints.CENTER; c.insets = new Insets(10, 10, 10, 10); getContentPane().add(button, c); } | public boolean loadResource(String resourcePath) { try { URL url = Thread.currentThread().getContextClassLoader().getResource(resourcePath); if (url == null) { logger.error("Cannot find the resource named: '" + resourcePath + "'. Failed to load the keyword list."); return false; } InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ligne = br.readLine(); while (ligne != null) { if (!contains(ligne.toUpperCase())) addLast(ligne.toUpperCase()); ligne = br.readLine(); } return true; } catch (IOException ioe) { logger.log(Level.ERROR, "Cannot load default SQL keywords file.", ioe); } return false; } | 1,024 |
0 | public void listgroups() throws Exception { String lapage = new String(""); Pattern pat; Matcher mat; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearAll(); System.out.print("http://groups.yahoo.com/mygroups : "); do { myurl = new URL(myurl.toString()); conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } System.out.print("."); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<td class=\"grpname selected\"><a href=\"(.+?)\".*?><em>(.+?)</em></a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(mat.group(2), "", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<a href=\"(.+?)\">Next ></a>"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); System.out.println(""); } | 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(); } } | 1,025 |
1 | public static boolean encodeFileToFile(final String infile, final 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)); final byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (final java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (final Exception exc) { } try { out.close(); } catch (final Exception exc) { } } return success; } | public void reqservmodif(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { try { System.err.println(req.getSession().getServletContext().getRealPath("WEB-INF/syncWork")); File tempFile = File.createTempFile("localmodif-", ".medoorequest"); OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); InputStream fis = new FileInputStream(tempFile); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); tempFile.delete(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } catch (ImogSerializationException ex) { logger.error(ex.getMessage()); } } | 1,026 |
1 | public static String getTextFromUrl(final String url) { InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { final StringBuilder result = new StringBuilder(); inputStreamReader = new InputStreamReader(new URL(url).openStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { result.append(HtmlUtil.quoteHtml(line)).append("\r"); } return result.toString(); } catch (final IOException exception) { return exception.getMessage(); } finally { InputOutputUtil.close(bufferedReader); InputOutputUtil.close(inputStreamReader); } } | public static String[] parseM3U(String strURL, Context c) { URL url; URLConnection urlConn = null; String TAG = "parseM3U"; Vector<String> radio = new Vector<String>(); final String filetoken = "http"; try { url = new URL(strURL); urlConn = url.openConnection(); Log.d(TAG, "Got data"); } catch (IOException ioe) { Log.e(TAG, "Could not connect to " + strURL); } try { DataInputStream in = new DataInputStream(urlConn.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { String temp = strLine.toLowerCase(); Log.d(TAG, strLine); if (temp.startsWith(filetoken)) { radio.add(temp); Log.d(TAG, "Found audio " + temp); } } br.close(); in.close(); } catch (Exception e) { Log.e(TAG, "Trouble reading file: " + e.getMessage()); } String[] t = new String[0]; String[] r = null; if (radio.size() != 0) { r = (String[]) radio.toArray(t); Log.d(TAG, "Found total: " + String.valueOf(r.length)); } return r; } | 1,027 |
1 | public static final String crypt(String password, String salt) throws NoSuchAlgorithmException { String magic = "$1$"; byte finalState[]; MessageDigest ctx, ctx1; long l; if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if (salt.indexOf('$') != -1) { salt = salt.substring(0, salt.indexOf('$')); } if (salt.length() > 8) { salt = salt.substring(0, 8); } ctx = MessageDigest.getInstance("MD5"); ctx.update(password.getBytes()); ctx.update(magic.getBytes()); ctx.update(salt.getBytes()); ctx1 = MessageDigest.getInstance("MD5"); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16) { for (int i = 0; i < (pl > 16 ? 16 : pl); i++) ctx.update(finalState[i]); } clearbits(finalState); for (int i = password.length(); i != 0; i >>>= 1) { if ((i & 1) != 0) { ctx.update(finalState[0]); } else { ctx.update(password.getBytes()[0]); } } finalState = ctx.digest(); for (int i = 0; i < 1000; i++) { ctx1 = MessageDigest.getInstance("MD5"); if ((i & 1) != 0) { ctx1.update(password.getBytes()); } else { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } if ((i % 3) != 0) { ctx1.update(salt.getBytes()); } if ((i % 7) != 0) { ctx1.update(password.getBytes()); } if ((i & 1) != 0) { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } else { ctx1.update(password.getBytes()); } finalState = ctx1.digest(); } StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]); result.append(to64(l, 4)); l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]); result.append(to64(l, 4)); l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]); result.append(to64(l, 4)); l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]); result.append(to64(l, 4)); l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]); result.append(to64(l, 4)); l = bytes2u(finalState[11]); result.append(to64(l, 2)); clearbits(finalState); return result.toString(); } | public static String getHash(String userName, String pass) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(userName.getBytes()); hash = ISOUtil.hexString(md.digest(pass.getBytes())).toLowerCase(); } catch (NoSuchAlgorithmException e) { } return hash; } | 1,028 |
0 | public static Set<Address> getDatosCatastrales(String pURL) { Set<Address> result = new HashSet<Address>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniInm1 = "<rcdnp>"; String finInm1 = "</rcdnp>"; String iniInm2 = "<bi>"; String finInm2 = "</bi>"; String iniPC1 = "<pc1>"; String iniPC2 = "<pc2>"; String finPC1 = "</pc1>"; String finPC2 = "</pc2>"; String iniCar = "<car>"; String finCar = "</car>"; String iniCC1 = "<cc1>"; String finCC1 = "</cc1>"; String iniCC2 = "<cc2>"; String finCC2 = "</cc2>"; String iniLDT = "<ldt>"; String iniBq = "<bq>"; String finBq = "</bq>"; String iniEs = "<es>"; String finEs = "</es>"; String iniPt = "<pt>"; String finPt = "</pt>"; String iniPu = "<pu>"; String finPu = "</pu>"; boolean error = false; int ini, fin; int postal = 0; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = br.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniInm1) || str.contains(iniInm2)) { Address inmueble = new Address(); while ((str = br.readLine()) != null && !str.contains(finInm1) && !str.contains(finInm2)) { if (str.contains(iniPC1) && str.contains(finPC1)) { ini = str.indexOf(iniPC1) + iniPC1.length(); fin = str.indexOf(finPC1); inmueble.setDescription(str.substring(ini, fin)); } if (str.contains(iniPC2) && str.contains(finPC2)) { ini = str.indexOf(iniPC2) + iniPC2.length(); fin = str.indexOf(finPC2); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniLDT) && str.contains("-")) { postal = Integer.parseInt(str.substring(str.lastIndexOf("-") - 5, str.lastIndexOf("-"))); } if (str.contains(iniCar) && str.contains(finCar)) { ini = str.indexOf(iniCar) + iniCar.length(); fin = str.indexOf(finCar); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniCC1) && str.contains(finCC1)) { ini = str.indexOf(iniCC1) + iniCC1.length(); fin = str.indexOf(finCC1); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniCC2) && str.contains(finCC2)) { ini = str.indexOf(iniCC2) + iniCC2.length(); fin = str.indexOf(finCC2); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniBq) && str.contains(finBq)) { ini = str.indexOf(iniBq) + iniBq.length(); fin = str.indexOf(finBq); inmueble.setBlock(str.substring(ini, fin)); } if (str.contains(iniEs) && str.contains(finEs)) { ini = str.indexOf(iniEs) + iniEs.length(); fin = str.indexOf(finEs); inmueble.setStairs(str.substring(ini, fin)); } if (str.contains(iniPt) && str.contains(finPt)) { ini = str.indexOf(iniPt) + iniPt.length(); fin = str.indexOf(finPt); inmueble.setFloor(str.substring(ini, fin)); } if (str.contains(iniPu) && str.contains(finPu)) { ini = str.indexOf(iniPu) + iniPu.length(); fin = str.indexOf(finPu); inmueble.setDoor(str.substring(ini, fin)); } } result.add(inmueble); } } } br.close(); if (result.size() == 1) { Object ad[] = result.toArray(); Coordinate coord = ConversorCoordenadas.getCoordenadas(((Address) ad[0]).getDescription()); coord.setPostcode(postal); for (Address inm : result) inm.setCoodinate(coord); } } catch (Exception e) { System.err.println(e); } return result; } | public static String md5(String text, String charset) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } msgDigest.update(text.getBytes()); byte[] bytes = msgDigest.digest(); byte tb; char low; char high; char tmpChar; String md5Str = new String(); for (int i = 0; i < bytes.length; i++) { tb = bytes[i]; tmpChar = (char) ((tb >>> 4) & 0x000f); if (tmpChar >= 10) { high = (char) (('a' + tmpChar) - 10); } else { high = (char) ('0' + tmpChar); } md5Str += high; tmpChar = (char) (tb & 0x000f); if (tmpChar >= 10) { low = (char) (('a' + tmpChar) - 10); } else { low = (char) ('0' + tmpChar); } md5Str += low; } return md5Str; } | 1,029 |
1 | public ChatClient registerPlayer(int playerId, String playerLogin) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(playerLogin.getBytes("UTF-8"), 0, playerLogin.length()); byte[] accountToken = md.digest(); byte[] token = generateToken(accountToken); ChatClient chatClient = new ChatClient(playerId, token); players.put(playerId, chatClient); return chatClient; } | public String hmacSHA256(String message, byte[] key) { MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new java.lang.AssertionError(this.getClass().getName() + ".hmacSHA256(): SHA-256 algorithm not found!"); } if (key.length > 64) { sha256.update(key); key = sha256.digest(); sha256.reset(); } byte block[] = new byte[64]; for (int i = 0; i < key.length; ++i) block[i] = key[i]; for (int i = key.length; i < block.length; ++i) block[i] = 0; for (int i = 0; i < 64; ++i) block[i] ^= 0x36; sha256.update(block); try { sha256.update(message.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new java.lang.AssertionError("ITunesU.hmacSH256(): UTF-8 encoding not supported!"); } byte[] hash = sha256.digest(); sha256.reset(); for (int i = 0; i < 64; ++i) block[i] ^= (0x36 ^ 0x5c); sha256.update(block); sha256.update(hash); hash = sha256.digest(); char[] hexadecimals = new char[hash.length * 2]; for (int i = 0; i < hash.length; ++i) { for (int j = 0; j < 2; ++j) { int value = (hash[i] >> (4 - 4 * j)) & 0xf; char base = (value < 10) ? ('0') : ('a' - 10); hexadecimals[i * 2 + j] = (char) (base + value); } } return new String(hexadecimals); } | 1,030 |
1 | public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } } | public static void copy(File sourceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } | 1,031 |
0 | private void loadProperties() throws IOException { if (properties == null) { return; } printDebugIfEnabled("Loading properties"); InputStream inputStream = configurationSource.openStream(); Properties newProperties = new Properties(); try { newProperties.load(inputStream); } finally { inputStream.close(); } String importList = newProperties.getProperty(KEY_IMPORT); if (importList != null) { importList = importList.trim(); if (importList.length() > 0) { String[] filesToImport = importList.split(","); if (filesToImport != null && filesToImport.length != 0) { String configurationContext = configurationSource.toExternalForm(); int lastSlash = configurationContext.lastIndexOf('/'); lastSlash += 1; configurationContext = configurationContext.substring(0, lastSlash); for (int i = 0; i < filesToImport.length; i++) { String filenameToImport = filesToImport[i]; URL urlToImport = new URL(configurationContext + filenameToImport); InputStream importStream = null; try { printDebugIfEnabled("Importing file", urlToImport); importStream = urlToImport.openStream(); newProperties.load(importStream); } catch (IOException e) { printError("Error importing properties file: " + filenameToImport + "(" + urlToImport + ")", e, true); } finally { if (importStream != null) importStream.close(); } } } } } if (devDebug) { Set properties = newProperties.entrySet(); printDebugIfEnabled("_____ Properties List START _____"); for (Iterator iterator = properties.iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); printDebugIfEnabled((String) entry.getKey(), entry.getValue()); } printDebugIfEnabled("______ Properties List END ______"); } properties.clear(); properties.putAll(newProperties); } | public synchronized String encrypt(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } | 1,032 |
0 | public LocalizationSolver(String name, String serverIP, int portNum, String workDir) { this.info = new HashMap<String, Object>(); this.workDir = workDir; try { Socket solverSocket = new Socket(serverIP, portNum); this.fromServer = new Scanner(solverSocket.getInputStream()); this.toServer = new PrintWriter(solverSocket.getOutputStream(), true); this.toServer.println("login client abc"); this.toServer.println("solver " + name); System.out.println(this.fromServer.nextLine()); } catch (IOException e) { System.err.println(e); e.printStackTrace(); System.exit(1); } System.out.println("Localization Solver started with name: " + name); } | @Override protected ResourceHandler doGet(final URI resourceUri) throws ResourceException { if (resourceUri.getHost() == null) { throw new IllegalStateException(InternalBundleHelper.StoreMessageBundle.getMessage("store.uri.ftp.illegal", resourceUri.toString())); } try { final URL configUrl = resourceUri.toURL(); final URLConnection urlConnection; Proxy httpProxy = null; if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxySet))) { if (context.getBoolean(FileStoreContextBuilder.ProxySet)) { final String proxyHost = context.getString(FileStoreContextBuilder.ProxyHost); final String proxyPort = context.getString(FileStoreContextBuilder.ProxyPort); if (!StringHelper.isEmpty(proxyHost)) { httpProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, !StringHelper.isEmpty(proxyPort) ? Integer.parseInt(proxyPort) : 80)); if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.NonProxyHosts))) { System.getProperties().put("ftp.nonProxyHosts", context.getProperty(FileStoreContextBuilder.NonProxyHosts)); } if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxyUser)) && !StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxyPassword))) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(context.getString(FileStoreContextBuilder.ProxyUser), context.getString(FileStoreContextBuilder.ProxyPassword).toCharArray()); } }); } } } } if (httpProxy == null) { urlConnection = configUrl.openConnection(); } else { urlConnection = configUrl.openConnection(httpProxy); } setUrlConnectionSettings(urlConnection); urlConnection.connect(); try { return createResourceHandler(resourceUri.toString(), urlConnection.getInputStream()); } catch (final FileNotFoundException fnfe) { throw new ResourceNotFoundException(resourceUri.toString()); } } catch (final MalformedURLException mure) { throw new IllegalStateException(InternalBundleHelper.StoreMessageBundle.getMessage("store.uri.malformed", resourceUri.toString())); } catch (final ConnectException ce) { throw new ResourceException("store.connection.error", ce, resourceUri.toString()); } catch (final IOException ioe) { if (ioe instanceof ResourceException) { throw (ResourceException) ioe; } else { throw new ResourceException(ioe, resourceUri.toString()); } } } | 1,033 |
0 | public void display(WebPage page, HttpServletRequest req, HttpServletResponse resp) throws DisplayException { page.getDisplayInitialiser().initDisplay(new HttpRequestDisplayContext(req), req); StreamProvider is = (StreamProvider) req.getAttribute(INPUTSTREAM_KEY); if (is == null) { throw new IllegalStateException("No OutputStreamDisplayHandlerXML.InputStream found in request attribute" + " OutputStreamDisplayHandlerXML.INPUTSTREAM_KEY"); } resp.setContentType(is.getMimeType()); resp.setHeader("Content-Disposition", "attachment;filename=" + is.getName()); try { InputStream in = is.getInputStream(); OutputStream out = resp.getOutputStream(); if (in != null) { IOUtils.copy(in, out); } is.write(resp.getOutputStream()); resp.flushBuffer(); } catch (IOException e) { throw new DisplayException("Error writing input stream to response", e); } } | public static String readRss(String feed, int num) { InputStream stream = null; try { feed = appendParam(feed, "num", "" + num); System.out.println("feed=" + feed); URL url = new URL(feed); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", RSS_USER_AGENT); stream = connection.getInputStream(); return CFileHelper.readInputStream(stream); } catch (Exception e) { throw new CException(e); } finally { CFileHelper.closeStream(stream); } } | 1,034 |
0 | private boolean doDelete(String identifier) throws IOException, MalformedURLException { URL url = new URL(baseurl.toString() + "/" + identifier); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); huc.setRequestMethod("DELETE"); huc.connect(); if (huc.getResponseCode() == 200) { return true; } else return false; } | private JButton getButtonSonido() { if (buttonSonido == null) { buttonSonido = new JButton(); buttonSonido.setText(Messages.getString("gui.AdministracionResorces.15")); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetree.png")); buttonSonido.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonSonido; } | 1,035 |
0 | private Document saveFile(Document document, File file) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { Preference preference = preferences.get(0); String repo = preference.getRepository(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(document.getLocation()); File folder = new File(sbRepo.append(sbFolder).toString()); log.info("Check in file ID [" + document.getId() + "] to " + folder.getAbsolutePath()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null, fcVersionDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append(".").append(document.getExt()); StringBuffer sbVersionFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append("_").append(document.getVersion().toString()).append(".").append(document.getExt()); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcVersionDest = new FileOutputStream(sbVersionFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); fcSource = new FileInputStream(file).getChannel(); fcVersionDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } if (fcVersionDest != null) { fcVersionDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return document; } | private FTPClient connect() throws IOException { FTPClient client = null; Configuration conf = getConf(); String host = conf.get("fs.ftp.host"); int port = conf.getInt("fs.ftp.host.port", FTP.DEFAULT_PORT); String user = conf.get("fs.ftp.user." + host); String password = conf.get("fs.ftp.password." + host); client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Server - " + host + " refused connection on port - " + port); } else if (client.login(user, password)) { client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE); client.setFileType(FTP.BINARY_FILE_TYPE); client.setBufferSize(DEFAULT_BUFFER_SIZE); } else { throw new IOException("Login failed on server - " + host + ", port - " + port); } return client; } | 1,036 |
1 | private void copyFile(File dir, File fileToAdd) { try { byte[] readBuffer = new byte[1024]; File file = new File(dir.getCanonicalPath() + File.separatorChar + fileToAdd.getName()); if (file.createNewFile()) { FileInputStream fis = new FileInputStream(fileToAdd); FileOutputStream fos = new FileOutputStream(file); int bytesRead; do { bytesRead = fis.read(readBuffer); fos.write(readBuffer, 0, bytesRead); } while (bytesRead == 0); fos.flush(); fos.close(); fis.close(); } else { logger.severe("unable to create file:" + file.getAbsolutePath()); } } catch (IOException ioe) { logger.severe("unable to create file:" + ioe); } } | 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!"); } | 1,037 |
1 | public void downloadTranslationsAndReload() { File languages = new File(this.translationsFile); try { URL languageURL = new URL(languageServer); InputStream is = languageURL.openStream(); OutputStream os = new FileOutputStream(languages); byte[] read = new byte[512000]; int bytesRead = 0; do { bytesRead = is.read(read); if (bytesRead > 0) { os.write(read, 0, bytesRead); } } while (bytesRead > 0); is.close(); os.close(); this.loadTranslations(); } catch (Exception e) { System.err.println("Remote languages file not found!"); if (languages.exists()) { try { XMLDecoder loader = new XMLDecoder(new FileInputStream(languages)); this.languages = (Hashtable) loader.readObject(); loader.close(); } catch (Exception ex) { ex.printStackTrace(); this.languages.put(naiveLanguage, new Hashtable()); } } else this.languages.put(naiveLanguage, new Hashtable()); } } | private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; } | 1,038 |
1 | public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = MessageLocalizer.getMessage("SCHEMA_CREATED_BY_OBJECT") + " [" + objectControlller + "] " + MessageLocalizer.getMessage("WITH_BOUI") + " [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (SCHEMA,OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } } | public static void main(String[] args) { try { Class.forName("org.hsqldb.jdbcDriver"); } catch (ClassNotFoundException e) { System.out.println("HSQL Driver not found."); System.exit(1); } Connection con = null; try { con = DriverManager.getConnection("jdbc:hsqldb:.", "sa", ""); con.setAutoCommit(false); } catch (SQLException e) { System.out.println("Connection error: " + e.getMessage()); System.exit(e.getErrorCode()); } String createTable = "CREATE TABLE NAMES (NAME VARCHAR(100))"; Statement stmt = null; try { stmt = con.createStatement(); con.commit(); stmt.executeUpdate(createTable); con.commit(); } catch (SQLException e) { System.out.println("Create table error: " + e.getMessage()); try { con.rollback(); con.close(); System.exit(e.getErrorCode()); } catch (SQLException ex) { } } Vector names = new Vector(4); names.addElement("FRANK"); names.addElement("FRED"); names.addElement("JACK"); names.addElement("JIM"); String ins = "INSERT INTO NAMES VALUES (?)"; PreparedStatement pstmt = null; try { con.commit(); pstmt = con.prepareStatement(ins); for (int i = 0; i < names.size(); i++) { pstmt.setString(1, (String) names.elementAt(i)); pstmt.executeUpdate(); } con.commit(); } catch (SQLException e) { System.out.println("Insert error: " + e.getMessage()); try { con.rollback(); con.close(); System.exit(e.getErrorCode()); } catch (SQLException ex) { } } String selAll = "SELECT * FROM NAMES"; ResultSet rs = null; stmt = null; try { stmt = con.createStatement(); rs = stmt.executeQuery(selAll); System.out.println("SELECT * FROM NAMES"); while (rs.next()) { String name = rs.getString(1); System.out.println("\t" + name); } stmt.close(); } catch (SQLException e) { System.out.println("Select All error: " + e.getMessage()); try { con.close(); System.exit(e.getErrorCode()); } catch (SQLException ex) { } } String selectLike = "SELECT * FROM NAMES WHERE NAME LIKE 'F%'"; rs = null; stmt = null; try { stmt = con.createStatement(); rs = stmt.executeQuery(selectLike); System.out.println("SELECT * FROM NAMES WHERE NAME LIKE 'F%'"); while (rs.next()) { String name = rs.getString(1); System.out.println("\t" + name); } stmt.close(); } catch (SQLException e) { System.out.println("Select Like error: " + e.getMessage()); try { con.close(); System.exit(e.getErrorCode()); } catch (SQLException ex) { } } try { con.close(); } catch (SQLException e) { } } | 1,039 |
1 | public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } } | private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) throw new IOException("Destination '" + destFile + "' exists but is a directory"); FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); if (preserveFileDate) destFile.setLastModified(srcFile.lastModified()); } | 1,040 |
1 | public static void compressFile(File f) throws IOException { File target = new File(f.toString() + ".gz"); System.out.print("Compressing: " + f.getName() + ".. "); long initialSize = f.length(); FileInputStream fis = new FileInputStream(f); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(target)); byte[] buf = new byte[1024]; int read; while ((read = fis.read(buf)) != -1) { out.write(buf, 0, read); } System.out.println("Done."); fis.close(); out.close(); long endSize = target.length(); System.out.println("Initial size: " + initialSize + "; Compressed size: " + endSize); } | public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } } | 1,041 |
1 | public void testReadNormal() throws Exception { archiveFileManager.executeWith(new TemporaryFileExecutor() { public void execute(File temporaryFile) throws Exception { ZipArchive archive = new ZipArchive(temporaryFile.getPath()); InputStream input = archive.getInputFrom(ARCHIVE_FILE_1); if (input != null) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copyAndClose(input, output); assertEquals(ARCHIVE_FILE_1 + " contents not correct", ARCHIVE_FILE_1_CONTENT, output.toString()); } else { fail("cannot open " + ARCHIVE_FILE_1); } } }); } | public static void fileCopy(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destFile); source = fis.getChannel(); destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { fis.close(); fos.close(); if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } | 1,042 |
0 | public void bubbleSort(int[] arr) { BasicProcessor.getInstance().getStartBlock(); BasicProcessor.getInstance().getVarDeclaration(); boolean swapped = true; BasicProcessor.getInstance().getVarDeclaration(); int j = 0; BasicProcessor.getInstance().getVarDeclaration(); int tmp; { BasicProcessor.getInstance().getWhileStatement(); while (swapped) { BasicProcessor.getInstance().getStartBlock(); swapped = false; j++; { BasicProcessor.getInstance().getForStatement(); for (int i = 0; i < arr.length - j; i++) { BasicProcessor.getInstance().getStartBlock(); { BasicProcessor.getInstance().getIfStatement(); if (arr[i] > arr[i + 1]) { BasicProcessor.getInstance().getStartBlock(); tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } | public static void copy(File source, File destination) throws IOException { InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); in.close(); out.close(); } | 1,043 |
0 | private static String webService(String strUrl) { StringBuffer buffer = new StringBuffer(); try { URL url = new URL(strUrl); InputStream input = url.openStream(); String sCurrentLine = ""; InputStreamReader read = new InputStreamReader(input, "utf-8"); BufferedReader l_reader = new java.io.BufferedReader(read); while ((sCurrentLine = l_reader.readLine()) != null) { buffer.append(sCurrentLine); } return buffer.toString(); } catch (Exception e) { e.printStackTrace(); return null; } } | public HttpURLConnection openConnection(String url) throws IOException { if (isDebugMode()) System.out.println("open: " + url); URL u = new URL(url); HttpURLConnection urlConnection; if (proxy != null) urlConnection = (HttpURLConnection) u.openConnection(proxy); else urlConnection = (HttpURLConnection) u.openConnection(); urlConnection.setRequestProperty("User-Agent", userAgent); return urlConnection; } | 1,044 |
0 | @SuppressWarnings("deprecation") private void loadClassFilesFromJar() { IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) getJavaElement(); File jarFile = packageFragmentRoot.getResource().getLocation().toFile(); try { URL url = jarFile.toURL(); URLConnection u = url.openConnection(); ZipInputStream inputStream = new ZipInputStream(u.getInputStream()); ZipEntry entry = inputStream.getNextEntry(); while (null != entry) { if (entry.getName().endsWith(".class")) { ClassParser parser = new ClassParser(inputStream, entry.getName()); Repository.addClass(parser.parse()); } entry = inputStream.getNextEntry(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } | protected Object serveFile(MyServerSocket socket, String filenm, URL url) { PrintStream out = null; InputStream in = null; long len = 0; try { out = new PrintStream(socket.getOutputStream()); in = url.openStream(); len = in.available(); } catch (IOException e) { HttpHelper.httpWrap(HttpHelper.EXC, e.toString(), 0); } if (HttpHelper.isImage(filenm)) { out.print(HttpHelper.httpWrapPic(filenm, len)); } else if (filenm.endsWith(".html")) { Comms.copyStreamSED(in, out, MPRES); } else if (HttpHelper.isOtherFile(filenm)) { out.print(HttpHelper.httpWrapOtherFile(filenm, len)); } else { String type = MimeUtils.getMimeType(filenm); if (type.equals(MimeUtils.UNKNOWN_MIME_TYPE)) { out.print(HttpHelper.httpWrapMimeType(type, len)); } else { out.print(HttpHelper.httpWrapMimeType(type, len)); } } if (in == null) { Log.logThis("THE INPUT STREAM IS NULL...url=" + url); } else Files.copyStream(in, out); return null; } | 1,045 |
0 | public void testReleaseOnEntityWriteTo() throws Exception { HttpParams params = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(params, 1); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1)); ThreadSafeClientConnManager mgr = createTSCCM(params, null); assertEquals(0, mgr.getConnectionsInPool()); DefaultHttpClient client = new DefaultHttpClient(mgr, params); HttpGet httpget = new HttpGet("/random/20000"); HttpHost target = getServerHttp(); HttpResponse response = client.execute(target, httpget); ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null); try { connreq.getConnection(250, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException expected) { } HttpEntity e = response.getEntity(); assertNotNull(e); ByteArrayOutputStream outsteam = new ByteArrayOutputStream(); e.writeTo(outsteam); assertEquals(1, mgr.getConnectionsInPool()); connreq = mgr.requestConnection(new HttpRoute(target), null); ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); } | public void readPersistentProperties() { try { String file = System.getProperty("user.home") + System.getProperty("file.separator") + ".das2rc"; File f = new File(file); if (f.canRead()) { try { InputStream in = new FileInputStream(f); load(in); in.close(); } catch (IOException e) { e.printStackTrace(); org.das2.util.DasExceptionHandler.handle(e); } } else { if (!f.exists() && f.canWrite()) { try { OutputStream out = new FileOutputStream(f); store(out, ""); out.close(); } catch (IOException e) { e.printStackTrace(); org.das2.util.DasExceptionHandler.handle(e); } } else { System.err.println("Unable to read or write " + file + ". Using defaults."); } } } catch (SecurityException ex) { ex.printStackTrace(); } } | 1,046 |
1 | public void process() throws Exception { String searchXML = FileUtils.readFileToString(new File(getSearchRequestRelativeFilePath())); Map<String, String> parametersMap = new HashMap<String, String>(); parametersMap.put("searchXML", searchXML); String proxyHost = null; int proxyPort = -1; String serverUserName = null; String serverUserPassword = null; FileOutputStream fos = null; if (getUseProxy()) { serverUserName = getServerUserName(); serverUserPassword = getServerUserPassword(); } if (getUseProxy()) { proxyHost = getProxyHost(); proxyPort = getProxyPort(); } try { InputStream responseInputStream = URLUtils.getHttpResponse(getSearchBaseURL(), serverUserName, serverUserPassword, URLUtils.HTTP_POST_METHOD, proxyHost, proxyPort, parametersMap, -1); fos = new FileOutputStream(getSearchResponseRelativeFilePath()); IOUtils.copyLarge(responseInputStream, fos); } finally { if (null != fos) { fos.flush(); fos.close(); } } } | public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } } | 1,047 |
0 | protected void onSubmit() { super.onSubmit(); if (!this.hasError()) { final FileUpload upload = fileUploadField.getFileUpload(); if (upload != null) { try { StringWriter xmlSourceWriter = new StringWriter(); IOUtils.copy(upload.getInputStream(), xmlSourceWriter); processSubmittedDoap(xmlSourceWriter.toString()); } catch (IOException e) { setResponsePage(new ErrorReportPage(new UserReportableException("Unable to add doap using RDF supplied", DoapFormPage.class, e))); } } } } | @edu.umd.cs.findbugs.annotations.SuppressWarnings({ "DLS", "REC" }) public static String md5Encode(String val) { String output = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(val.getBytes()); byte[] digest = md.digest(); output = base64Encode(digest); } catch (Exception e) { } return output; } | 1,048 |
1 | public OutputStream getAsOutputStream() throws IOException { OutputStream out; if (contentStream != null) { File tmp = File.createTempFile(getId(), null); out = new FileOutputStream(tmp); IOUtils.copy(contentStream, out); } else { out = new ByteArrayOutputStream(); out.write(getContent()); } return out; } | public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); } | 1,049 |
1 | private final String encryptPassword(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.log(Level.WARNING, "Error while obtaining decript algorithm", e); throw new RuntimeException("AccountData.encryptPassword()"); } try { md.update(pass.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { log.log(Level.WARNING, "Problem with decript algorithm occured.", e); throw new RuntimeException("AccountData.encryptPassword()"); } return new BASE64Encoder().encode(md.digest()); } | private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } | 1,050 |
0 | public static boolean downloadFile(String srcUri, String srcDest) { try { URL url = new URL(srcUri); InputStream is = url.openStream(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(srcDest)); byte[] buff = new byte[10000]; int b; while ((b = is.read(buff)) > 0) bos.write(buff, 0, b); is.close(); bos.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } | public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { log.error(e, e); } finally { if (in != null) in.close(); if (out != null) out.close(); } } | 1,051 |
1 | public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } | private static String getVisitorId(String guid, String account, String userAgent, Cookie cookie) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (cookie != null && cookie.getValue() != null) { return cookie.getValue(); } String message; if (!isEmpty(guid)) { message = guid + account; } else { message = userAgent + getRandomNumber() + UUID.randomUUID().toString(); } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(message.getBytes("UTF-8"), 0, message.length()); byte[] sum = m.digest(); BigInteger messageAsNumber = new BigInteger(1, sum); String md5String = messageAsNumber.toString(16); while (md5String.length() < 32) { md5String = "0" + md5String; } return "0x" + md5String.substring(0, 16); } | 1,052 |
1 | public void copyFile(String source_file_path, String destination_file_path) { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(source_file_path); fw = new FileWriter(destination_file_path); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(source_file_path); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { System.out.println(source_file_path + " does not exist!"); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } } | public static void write(File file, InputStream source) throws IOException { OutputStream outputStream = null; assert file != null : "file must not be null."; assert file.isFile() : "file must be a file."; assert file.canWrite() : "file must be writable."; assert source != null : "source must not be null."; try { outputStream = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(source, outputStream); outputStream.flush(); } finally { IOUtils.closeQuietly(outputStream); } } | 1,053 |
1 | protected void updateJava2ScriptProject(String prjFolder, String binRelative) { try { File cpFile = new File(prjFolder, ".classpath"); FileInputStream fis = new FileInputStream(cpFile); String classpath = J2SLaunchingUtil.readAFile(fis); if (classpath != null) { boolean needUpdate = false; if (classpath.indexOf("ECLIPSE_SWT") == -1 && classpath.indexOf("SWT_LIBRARY") == -1 && classpath.indexOf("eclipse.swt") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry kind=\"var\" path=\"ECLIPSE_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_SWT") == -1 && classpath.indexOf("ajaxswt.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_SWT_SRC\" kind=\"var\" path=\"AJAX_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_RPC") == -1 && classpath.indexOf("ajaxrpc.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_RPC_SRC\" kind=\"var\" path=\"AJAX_RPC\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_PIPE") == -1 && classpath.indexOf("ajaxpipe.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_PIPE_SRC\" kind=\"var\" path=\"AJAX_PIPE\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (needUpdate) { try { FileOutputStream fos = new FileOutputStream(cpFile); fos.write(classpath.getBytes("utf-8")); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } File webinf = new File(prjFolder, "WEB-INF"); webinf.mkdir(); new File(webinf, "classes").mkdir(); File lib = new File(webinf, "lib"); lib.mkdir(); IPath newPath = null; URL starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); String root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxrpc.jar"); File rpcFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(rpcFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxrpc.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxpipe.jar"); File pipeFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(pipeFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxpipe.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } StringBuffer buildxml = new StringBuffer(); buildxml.append("<?xml version=\"1.0\"?>\r\n"); buildxml.append("<project name=\"java2script.servlet.pack\" default=\"pack.war\" basedir=\".\">\r\n"); buildxml.append(" <description>Pack Java2Script Servlet Application</description>\r\n"); buildxml.append("\r\n"); String name = new File(prjFolder).getName(); buildxml.append(" <property name=\"java2script.app.name\" value=\"" + name + "\"/>\r\n"); buildxml.append(" <property name=\"bin.folder\" value=\"${basedir}/../" + binRelative + "\"/>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.war\" depends=\"pack.jar\">\r\n"); buildxml.append(" <tstamp>\r\n"); buildxml.append(" <format property=\"now\" pattern=\"yyyy-MM-dd-HH-mm-ss\"/>\r\n"); buildxml.append(" </tstamp>\r\n"); buildxml.append(" <delete file=\"${basedir}/../${java2script.app.name}.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../${java2script.app.name}.${now}.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/../\">\r\n"); buildxml.append(" <exclude name=\"src/**\"/>\r\n"); buildxml.append(" <exclude name=\"META-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.java\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.class\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" <fileset dir=\"${basedir}/..\">\r\n"); buildxml.append(" <include name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/build.xml\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" <copy file=\"${basedir}/../${java2script.app.name}.${now}.war\"\r\n"); buildxml.append(" tofile=\"${basedir}/../${java2script.app.name}.war\"/>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.jar\">\r\n"); buildxml.append(" <delete file=\"${basedir}/lib/${java2script.app.name}.jar\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/lib/${java2script.app.name}.jar\">\r\n"); buildxml.append(" <fileset dir=\"${bin.folder}\">\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.html\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.js\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.css\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.bmp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.gif\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.png\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpeg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root); String ajaxPath = newPath.toOSString(); String key = "net.sf.j2s.ajax"; int idx = ajaxPath.lastIndexOf(key); if (idx != -1) { ajaxPath = ajaxPath.substring(0, idx) + "net.sf.j2s.lib" + ajaxPath.substring(idx + key.length()); } File libFile = new File(ajaxPath); String j2sRelativePath = FileUtil.toRelativePath(libFile.getAbsolutePath(), webinf.getAbsolutePath()); if (j2sRelativePath.length() > 0 && !j2sRelativePath.endsWith("/")) { j2sRelativePath += "/"; } int slashIndex = j2sRelativePath.lastIndexOf('/', j2sRelativePath.length() - 2); String pluginPath = j2sRelativePath.substring(0, slashIndex); String libPluginPath = j2sRelativePath.substring(slashIndex + 1, j2sRelativePath.length() - 1); buildxml.append(" <target name=\"pack.plugins.j2slib.war\">\r\n"); buildxml.append(" <delete file=\"${basedir}/../plugins.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../plugins.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/" + pluginPath + "/\">\r\n"); buildxml.append(" <include name=\"" + libPluginPath + "/**\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/library.jar\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/META-INF/**\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append("</project>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "build.xml")); fos.write(buildxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } StringBuffer webxml = new StringBuffer(); webxml.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n"); webxml.append("<!DOCTYPE web-app\r\n"); webxml.append(" PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\r\n"); webxml.append(" \"http://java.sun.com/dtd/web-app_2_3.dtd\">\r\n"); webxml.append("<web-app>\r\n"); webxml.append(" <display-name>Java2Script</display-name>\r\n"); webxml.append(" <description>Java2Script application</description>\r\n"); webxml.append(genereateServlet("simplerpc", "net.sf.j2s.ajax.SimpleRPCHttpServlet")); webxml.append(genereateServlet("piperpc", "net.sf.j2s.ajax.CompoundPipeRPCHttpServlet")); webxml.append(" <servlet>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <servlet-class>net.sf.j2s.ajax.SimplePipeHttpServlet</servlet-class>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.query.timeout</param-name>\r\n"); webxml.append(" <param-value>20000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.script.breakout</param-name>\r\n"); webxml.append(" <param-value>1200000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.max.items.per.query</param-name>\r\n"); webxml.append(" <param-value>60</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" </servlet>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplerpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplerpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>piperpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/piperpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplepipe</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append("</web-app>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "web.xml")); fos.write(webxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } } | @Test public void testCascadeTraining() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("parity8.train"), new FileOutputStream(temp)); Fann fann = new FannShortcut(8, 1); Trainer trainer = new Trainer(fann); float desiredError = .00f; float mse = trainer.cascadeTrain(temp.getPath(), 30, 1, desiredError); assertTrue("" + mse, mse <= desiredError); } | 1,054 |
0 | private String hash(String text) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } | public void setPilot(PilotData pilotData) throws UsernameNotValidException { try { if (pilotData.username.trim().equals("") || pilotData.password.trim().equals("")) throw new UsernameNotValidException(1, "Username or password missing"); PreparedStatement psta; if (pilotData.id == 0) { psta = jdbc.prepareStatement("INSERT INTO pilot " + "(name, address1, address2, zip, city, state, country, birthdate, " + "pft_theory, pft, medical, passenger, instructor, loc_language, " + "loc_country, loc_variant, username, password, id) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,pilot_id_seq.nextval)"); } else { psta = jdbc.prepareStatement("UPDATE pilot SET " + "name = ?, address1 = ?, address2 = ?, " + "zip = ?, city = ?, state = ?, country = ?, birthdate = ?, pft_theory = ?," + "pft = ?, medical = ?, passenger = ?, instructor = ?, loc_language = ?, " + "loc_country = ?, loc_variant = ?, username = ?, password = ? " + "WHERE id = ?"); } psta.setString(1, pilotData.name); psta.setString(2, pilotData.address1); psta.setString(3, pilotData.address2); psta.setString(4, pilotData.zip); psta.setString(5, pilotData.city); psta.setString(6, pilotData.state); psta.setString(7, pilotData.country); if (pilotData.birthdate != null) psta.setLong(8, pilotData.birthdate.getTime()); else psta.setNull(8, java.sql.Types.INTEGER); if (pilotData.pft_theory != null) psta.setLong(9, pilotData.pft_theory.getTime()); else psta.setNull(9, java.sql.Types.INTEGER); if (pilotData.pft != null) psta.setLong(10, pilotData.pft.getTime()); else psta.setNull(10, java.sql.Types.INTEGER); if (pilotData.medical != null) psta.setLong(11, pilotData.medical.getTime()); else psta.setNull(11, java.sql.Types.INTEGER); if (pilotData.passenger) psta.setString(12, "Y"); else psta.setString(12, "N"); if (pilotData.instructor) psta.setString(13, "Y"); else psta.setString(13, "N"); psta.setString(14, pilotData.loc_language); psta.setString(15, pilotData.loc_country); psta.setString(16, pilotData.loc_variant); psta.setString(17, pilotData.username); psta.setString(18, pilotData.password); if (pilotData.id != 0) { psta.setInt(19, pilotData.id); } psta.executeUpdate(); jdbc.commit(); } catch (SQLException sql) { jdbc.rollback(); sql.printStackTrace(); throw new UsernameNotValidException(2, "Username allready exist"); } } | 1,055 |
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(); try { MessageDigest md = MessageDigest.getInstance("MD5"); 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])); } } } catch (NoSuchAlgorithmException e) { throw new ForumException("" + e); } return hexString.toString(); } | public static byte[] MD5(String... strings) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); for (String string : strings) { digest.update(string.getBytes("UTF-8")); } return digest.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.toString(), e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.toString(), e); } } | 1,056 |
1 | public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { from.close(); to.close(); } } | public static void copy(File source, File dest) throws IOException { if (dest.isDirectory()) { dest = new File(dest + File.separator + source.getName()); } FileChannel in = null, 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 { if (in != null) in.close(); if (out != null) out.close(); } } | 1,057 |
1 | public final boolean login(String user, String pass) { if (user == null || pass == null) return false; connectionInfo.setData("com.tensegrity.palojava.pass#" + user, pass); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); pass = asHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { throw new PaloException("Failed to create encrypted password for " + "user '" + user + "'!", ex); } connectionInfo.setUser(user); connectionInfo.setPassword(pass); return loginInternal(user, pass); } | 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()); } | 1,058 |
0 | private int[] get51JobId(String address, String category, int pageNum) { StringBuffer htmlContent = null; try { URL url = new URL(ConfigJob51.STR_51JOB_ADVANCE); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStream raw = connection.getOutputStream(); OutputStream buf = new BufferedOutputStream(raw); OutputStreamWriter out = new OutputStreamWriter(buf, "gb2312"); out.write("jobarea=" + address + "&funtype=" + category + "&curr_page=" + pageNum + ""); out.flush(); out.close(); InputStream in = connection.getInputStream(); in = new BufferedInputStream(in); Reader r = new InputStreamReader(in); int c; htmlContent = new StringBuffer(); while ((c = r.read()) != -1) { htmlContent.append((char) c); } in.close(); } catch (IOException e) { e.printStackTrace(); } Pattern p = Pattern.compile(JOB51_SEARCHLIST_URL_PATTERN, Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(htmlContent); int idSum = 0; int writeToDBSuccessful = 0; while (matcher.find()) { String s = matcher.group(); String sql = "insert into `job51`(`id`,`retryCnt`,`Category`) values('" + s.replaceAll("[^0-9]", "") + "','0','" + category + "')"; if (mysql.executeInsert(sql)) { writeToDBSuccessful++; } idSum++; } return new int[] { idSum, writeToDBSuccessful }; } | public BufferedWriter createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); return new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); } | 1,059 |
1 | public void writeToFile(File file, File source) throws IOException { BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file)); BufferedInputStream bin = new BufferedInputStream(new FileInputStream(source)); bin.skip(header.getHeaderEndingOffset()); for (long i = 0; i < this.streamLength; i++) { bout.write(bin.read()); } bin.close(); bout.close(); } | public static void copy(FileInputStream source, FileOutputStream target) throws IOException { FileChannel sourceChannel = source.getChannel(); FileChannel targetChannel = target.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); } | 1,060 |
0 | private void uploadLogin() { try { status = UploadStatus.INITIALISING; if (file.length() > 419430400) { JOptionPane.showMessageDialog(neembuuuploader.NeembuuUploader.getInstance(), "<html><b>" + getClass().getSimpleName() + "</b> " + TranslationProvider.get("neembuuuploader.uploaders.maxfilesize") + ": <b>400MB</b></html>", getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE); uploadFailed(); return; } status = UploadStatus.GETTINGCOOKIE; 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); httpget = new HttpGet("http://hotfile.com/?cookiecheck=1"); httpget.setHeader("Referer", "http://www.hotfile.com/"); httpget.setHeader("Cache-Control", "max-age=0"); httpget.setHeader("Origin", "http://www.hotfile.com/"); httpget.setHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); httpclient = new DefaultHttpClient(params); httpclient.getCookieStore().addCookie(HotFileAccount.getHfcookie()); HttpResponse httpresponse = httpclient.execute(httpget); strResponse = EntityUtils.toString(httpresponse.getEntity()); start = "<form action=\""; link = strResponse.substring(strResponse.indexOf(start + "http://") + start.length()); link = link.substring(0, link.indexOf("\"")); NULogger.getLogger().info(link); httppost = new HttpPost(link); httppost.setHeader("Referer", "http://www.hotfile.com/"); httppost.setHeader("Cache-Control", "max-age=0"); httppost.setHeader("Origin", "http://www.hotfile.com/"); httppost.setHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); MultipartEntity requestEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); requestEntity.addPart("uploads[]", new MonitoredFileBody(file, uploadProgress)); requestEntity.addPart("iagree", new StringBody("on")); requestEntity.addPart("", new StringBody("Upload")); httppost.setEntity(requestEntity); status = UploadStatus.UPLOADING; httpresponse = httpclient.execute(httppost); manageURL = httpresponse.getHeaders("Location")[0].getValue(); NULogger.getLogger().log(Level.INFO, "HotFile Manage URL{0}", manageURL); NULogger.getLogger().info("Getting links from Manage URL"); status = UploadStatus.GETTINGLINK; httpget = new HttpGet(manageURL); httpclient = new DefaultHttpClient(params); httpresponse = httpclient.execute(httpget); strResponse = EntityUtils.toString(httpresponse.getEntity()); start = "<input type=\"text\" name=\"url\" id=\"url\" class=\"textfield\" value=\""; downURL = strResponse.substring(strResponse.indexOf(start) + start.length()); downURL = downURL.substring(0, downURL.indexOf("\"")); start = "<input type=\"text\" name=\"delete\" id=\"delete\" class=\"textfield\" value=\""; delURL = strResponse.substring(strResponse.indexOf(start) + start.length()); delURL = delURL.substring(0, delURL.indexOf("\"")); NULogger.getLogger().log(Level.INFO, "Download Link: {0}", downURL); NULogger.getLogger().log(Level.INFO, "Delete link: {0}", delURL); uploadFinished(); } catch (Exception ex) { ex.printStackTrace(); NULogger.getLogger().severe(ex.toString()); uploadFailed(); } } | static final String md5(String text) throws RtmApiException { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RtmApiException("Md5 error: NoSuchAlgorithmException - " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RtmApiException("Md5 error: UnsupportedEncodingException - " + e.getMessage()); } } | 1,061 |
0 | public Certificate(URL url) throws CertificateException { try { URLConnection con = url.openConnection(); InputStream in2 = con.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(in2)); String inputLine; StringBuffer cert = new StringBuffer(); while ((inputLine = in.readLine()) != null) { cert.append(inputLine); cert.append("\n"); } in.close(); this.certificate = cert.toString(); } catch (IOException ex) { throw new CertificateException("Unable to read in credential: " + ex.getMessage(), ex); } loadCredential(this.certificate); } | public CmsSetupTestResult execute(CmsSetupBean setupBean) { CmsSetupTestResult testResult = new CmsSetupTestResult(this); String basePath = setupBean.getWebAppRfsPath(); if (!basePath.endsWith(File.separator)) { basePath += File.separator; } File file1; Random rnd = new Random(); do { file1 = new File(basePath + "test" + rnd.nextInt(1000)); } while (file1.exists()); boolean success = false; try { file1.createNewFile(); FileWriter fw = new FileWriter(file1); fw.write("aA1"); fw.close(); success = true; FileReader fr = new FileReader(file1); success = success && (fr.read() == 'a'); success = success && (fr.read() == 'A'); success = success && (fr.read() == '1'); success = success && (fr.read() == -1); fr.close(); success = file1.delete(); success = !file1.exists(); } catch (Exception e) { success = false; } if (!success) { testResult.setRed(); testResult.setInfo("OpenCms cannot be installed without read and write privileges for path " + basePath + "! Please check you are running your servlet container with the right user and privileges."); testResult.setHelp("Not enough permissions to create/read/write a file"); testResult.setResult(RESULT_FAILED); } else { testResult.setGreen(); testResult.setResult(RESULT_PASSED); } return testResult; } | 1,062 |
0 | public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); } | public static boolean processUrl(String urlPath, UrlLineHandler handler) { boolean ret = true; URL url; InputStream in = null; BufferedReader bin = null; try { url = new URL(urlPath); in = url.openStream(); bin = new BufferedReader(new InputStreamReader(in)); String line; while ((line = bin.readLine()) != null) { if (!handler.process(line)) break; } } catch (IOException e) { ret = false; } finally { safelyClose(bin, in); } return ret; } | 1,063 |
0 | public static String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; } | public static void concatenateOutput(File[] inputFiles, File outputFile) { int numberOfInputFiles = inputFiles.length; byte lf = (byte) '\n'; try { FileOutputStream fos = new FileOutputStream(outputFile); FileChannel outfc = fos.getChannel(); System.out.println("Processing " + inputFiles[0].getPath()); FileInputStream fis = new FileInputStream(inputFiles[0]); FileChannel infc = fis.getChannel(); int bufferCapacity = 100000; ByteBuffer bb = ByteBuffer.allocate(bufferCapacity); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); for (int f = 1; f < numberOfInputFiles; f++) { System.out.println("Processing " + inputFiles[f].getPath()); fis = new FileInputStream(inputFiles[f]); infc = fis.getChannel(); bb.clear(); int bytesread = infc.read(bb); bb.flip(); byte b = bb.get(); while (b != lf) { b = bb.get(); } outfc.write(bb); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); } outfc.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } | 1,064 |
1 | private void externalizeFiles(Document doc, File out) throws IOException { File[] files = doc.getImages(); if (files.length > 0) { File dir = new File(out.getParentFile(), out.getName() + ".images"); if (!dir.mkdirs()) throw new IOException("cannot create directory " + dir); if (dir.exists()) { for (int i = 0; i < files.length; i++) { File file = files[i]; File copy = new File(dir, file.getName()); FileChannel from = null, to = null; long count = -1; try { from = new FileInputStream(file).getChannel(); count = from.size(); to = new FileOutputStream(copy).getChannel(); from.transferTo(0, count, to); doc.setImage(file, dir.getName() + "/" + copy.getName()); } catch (Throwable t) { LOG.log(Level.WARNING, "Copying '" + file + "' to '" + copy + "' failed (size=" + count + ")", t); } finally { try { to.close(); } catch (Throwable t) { } try { from.close(); } catch (Throwable t) { } } } } } } | private void removeSessionId(InputStream inputStream, Output output) throws IOException { String jsessionid = RewriteUtils.getSessionId(target); boolean textContentType = ResourceUtils.isTextContentType(httpClientResponse.getHeader(HttpHeaders.CONTENT_TYPE), target.getDriver().getConfiguration().getParsableContentTypes()); if (jsessionid == null || !textContentType) { IOUtils.copy(inputStream, output.getOutputStream()); } else { String charset = httpClientResponse.getContentCharset(); if (charset == null) { charset = "ISO-8859-1"; } String content = IOUtils.toString(inputStream, charset); content = removeSessionId(jsessionid, content); if (output.getHeader(HttpHeaders.CONTENT_LENGTH) != null) { output.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(content.length())); } OutputStream outputStream = output.getOutputStream(); IOUtils.write(content, outputStream, charset); } inputStream.close(); } | 1,065 |
0 | private void doProcess(HttpServletRequest request, HttpServletResponse resp) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { Analyzer analyzer = new Analyzer(); ServletContext context = getServletContext(); String xml = context.getRealPath("data\\log.xml"); String xsd = context.getRealPath("data\\log.xsd"); String grs = context.getRealPath("reports\\" + request.getParameter("type") + ".grs"); String pdf = context.getRealPath("html\\report.pdf"); System.out.println("omg: " + request.getParameter("type")); System.out.println("omg: " + request.getParameter("pc")); int pcount = Integer.parseInt(request.getParameter("pc")); String[] params = new String[pcount]; for (int i = 0; i < pcount; i++) { params[i] = request.getParameter("p" + i); } try { analyzer.generateReport(xml, xsd, grs, pdf, params); } catch (Exception e) { e.printStackTrace(); } File file = new File(pdf); byte[] bs = tryLoadFile(pdf); if (bs == null) throw new NullPointerException(); resp.setHeader("Content-Disposition", " filename=\"" + file.getName() + "\";"); resp.setContentLength(bs.length); InputStream is = new ByteArrayInputStream(bs); IOUtils.copy(is, resp.getOutputStream()); } | public String md5Encode(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(pass.getBytes()); byte[] result = md.digest(); return new String(result); } | 1,066 |
0 | public void update() { Vector invalids = new Vector(); for (int i = 0; i < urls.size(); i++) { URL url = null; try { url = new URL((String) urls.elementAt(i)); InputStream stream = url.openStream(); stream.close(); } catch (MalformedURLException urlE) { Logger.logWarning("Malformed URL: " + urls.elementAt(i)); } catch (IOException ioE) { invalids.addElement(url); } } for (int i = 0; i < invalids.size(); i++) { urls.removeElement(invalids.elementAt(i)); Logger.logInfo("Removed " + invalids.elementAt(i) + " - no longer available"); } } | public static String md5String(String string) { try { MessageDigest msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(string.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); String result = ""; for (int i = 0; i < digest.length; i++) { int value = digest[i]; if (value < 0) value += 256; result += Integer.toHexString(value); } return result; } catch (UnsupportedEncodingException error) { throw new IllegalArgumentException(error); } catch (NoSuchAlgorithmException error) { throw new IllegalArgumentException(error); } } | 1,067 |
1 | @SuppressWarnings("unchecked") protected void displayFreeMarkerResponse(HttpServletRequest request, HttpServletResponse response, String templateName, Map<String, Object> variableMap) throws IOException { Enumeration<String> attrNameEnum = request.getSession().getAttributeNames(); String attrName; while (attrNameEnum.hasMoreElements()) { attrName = attrNameEnum.nextElement(); if (attrName != null && attrName.startsWith(ADMIN4J_SESSION_VARIABLE_PREFIX)) { variableMap.put("Session" + attrName, request.getSession().getAttribute(attrName)); } } variableMap.put("RequestAdmin4jCurrentUri", request.getRequestURI()); Template temp = FreemarkerUtils.createConfiguredTemplate(this.getClass(), templateName); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { temp.process(variableMap, new OutputStreamWriter(outStream)); response.setContentLength(outStream.size()); IOUtils.copy(new ByteArrayInputStream(outStream.toByteArray()), response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { throw new Admin4jRuntimeException(e); } } | @Override public void copyTo(ManagedFile other) throws ManagedIOException { try { if (other.getType() == ManagedFileType.FILE) { IOUtils.copy(this.getContent().getInputStream(), other.getContent().getOutputStream()); } else { ManagedFile newFile = other.retrive(this.getPath()); newFile.createFile(); IOUtils.copy(this.getContent().getInputStream(), newFile.getContent().getOutputStream()); } } catch (IOException ioe) { throw ManagedIOException.manage(ioe); } } | 1,068 |
0 | public static String getUploadDeleteComboBox(String fromMode, String fromFolder, String action, String object, HttpSession session) { FTPClient ftp = new FTPClient(); CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); StringBuffer links = new StringBuffer(); StringBuffer folders = new StringBuffer(); String folder = ""; String server = ""; String login = ""; String password = ""; int i = 0; String liveFTPServer = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER") + ""; liveFTPServer = liveFTPServer.trim(); if ((liveFTPServer == null) || (liveFTPServer.equals("null")) || (liveFTPServer.equals(""))) { return ("This tool is not " + "configured and will not operate. " + "If you wish it to do so, please edit " + "this publication's properties and add correct values to " + " the Remote Server Upstreaming section."); } if (action.equals("Upload")) { server = (String) user.workingPubConfigElementsHash.get("TESTFTPSERVER"); login = (String) user.workingPubConfigElementsHash.get("TESTFTPLOGIN"); password = (String) user.workingPubConfigElementsHash.get("TESTFTPPASSWORD"); CofaxToolsUtil.log("server= " + server + " , login= " + login + " , password=" + password); if (object.equals("Media")) { folder = (String) user.workingPubConfigElementsHash.get("TESTIMAGESFOLDER"); } if (object.equals("Templates")) { folder = (String) user.workingPubConfigElementsHash.get("TESTTEMPLATEFOLDER"); CofaxToolsUtil.log("testTemplateFolder= " + folder); } } if (action.equals("Delete")) { login = (String) user.workingPubConfigElementsHash.get("LIVEFTPLOGIN"); password = (String) user.workingPubConfigElementsHash.get("LIVEFTPPASSWORD"); if (object.equals("Media")) { server = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESSERVER"); folder = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESFOLDER"); } if (object.equals("Templates")) { server = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER"); folder = (String) user.workingPubConfigElementsHash.get("LIVETEMPLATEFOLDER"); } } ArrayList servers = splitServers(server); try { int reply; ftp.connect((String) servers.get(0)); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox connecting to server: " + (String) servers.get(0)); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox results: " + ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ("CofaxToolsFTP getUploadDeleteComboBox ERROR: FTP server refused connection: " + server); } else { ftp.login(login, password); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox login / pass " + login + " " + password); } try { String tempParentFolderName = folder; CofaxToolsUtil.log("fromfolder is " + fromFolder); if ((fromFolder != null) && (fromFolder.length() > folder.length())) { folder = fromFolder; tempParentFolderName = folder; int subSt = folder.lastIndexOf("/"); tempParentFolderName = tempParentFolderName.substring(0, subSt); String publicName = ""; int subStri = folder.lastIndexOf((String) user.workingPubName); if (subStri > -1) { publicName = folder.substring(subStri); } folders.append("<B><A HREF=\'/tools/?mode=" + fromMode + "&hl=templates_view_templates_images&fromFolder=" + tempParentFolderName + "\'>" + tempParentFolderName + "</A></B><BR>\n"); } else if ((fromFolder != null) && (fromFolder.length() == folder.length())) { folder = fromFolder; tempParentFolderName = folder; int subSt = folder.lastIndexOf("/"); tempParentFolderName = tempParentFolderName.substring(0, subSt); } boolean changed = ftp.changeWorkingDirectory(folder); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox changing working directory to " + folder); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox results " + changed); FTPFile[] files = null; if ((action.equals("Delete")) && (object.equals("Templates"))) { files = ftp.listFiles(new CofaxToolsNTFileListParser()); } else { files = ftp.listFiles(new CofaxToolsNTFileListParser()); } if (files == null) { CofaxToolsUtil.log("null"); } for (int ii = 0; ii < files.length; ii++) { FTPFile thisFile = (FTPFile) files[ii]; String name = thisFile.getName(); if (!thisFile.isDirectory()) { links.append("<INPUT TYPE=CHECKBOX NAME=" + i + " VALUE=" + folder + "/" + name + ">" + name + "<BR>\n"); i++; } if ((thisFile.isDirectory()) && (!name.startsWith(".")) && (!name.endsWith("."))) { int subStr = folder.lastIndexOf((String) user.workingPubName); String tempFolderName = ""; if (subStr > -1) { tempFolderName = folder.substring(subStr); } else { tempFolderName = folder; } folders.append("<LI><A HREF=\'/tools/?mode=" + fromMode + "&hl=templates_view_templates_images&fromFolder=" + folder + "/" + name + "\'>" + tempFolderName + "/" + name + "</A><BR>"); } } ftp.logout(); ftp.disconnect(); } catch (java.io.IOException e) { return ("CofaxToolsFTP getUploadDeleteComboBox cannot read directory: " + folder); } } catch (IOException e) { return ("Could not connect to server: " + e); } links.append("<INPUT TYPE=HIDDEN NAME=numElements VALUE=" + i + " >\n"); links.append("<INPUT TYPE=SUBMIT VALUE=\"" + action + " " + object + "\">\n"); return (folders.toString() + links.toString()); } | public void saveMapping() throws SQLException { Connection connection = null; PreparedStatement ps = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = (Connection) DriverManager.getConnection(this.jdbcURL); connection.setAutoCommit(false); String query = "INSERT INTO mapping(product_id, comp_id, count) VALUES(?,?,?)"; ps = (PreparedStatement) connection.prepareStatement(query); ps.setInt(1, this.productId); ps.setInt(2, this.componentId); ps.setInt(3, 1); ps.executeUpdate(); } catch (Exception ex) { connection.rollback(); } finally { try { connection.close(); } catch (Exception ex) { } try { ps.close(); } catch (Exception ex) { } } } | 1,069 |
1 | private byte[] streamToBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } return out.toByteArray(); } | private static void addFile(File file, TarArchiveOutputStream taos) throws IOException { String filename = null; filename = file.getName(); TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } | 1,070 |
0 | private static String genRandomGUID(boolean secure) { String valueBeforeMD5 = ""; String valueAfterMD5 = ""; MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); return valueBeforeMD5; } long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); String strTemp = ""; for (int i = 0; i < array.length; i++) { strTemp = (Integer.toHexString(array[i] & 0XFF)); if (strTemp.length() == 1) { valueAfterMD5 = valueAfterMD5 + "0" + strTemp; } else { valueAfterMD5 = valueAfterMD5 + strTemp; } } return valueAfterMD5.toUpperCase(); } | public void run() { String baseUrl; if (_rdoSRTM3FtpUrl.getSelection()) { } else { baseUrl = _txtSRTM3HttpUrl.getText().trim(); try { final URL url = new URL(baseUrl); final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.connect(); final int response = urlConn.getResponseCode(); final String responseMessage = urlConn.getResponseMessage(); final String message = response == HttpURLConnection.HTTP_OK ? NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionOK_message, baseUrl) : NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionFAILED_message, new Object[] { baseUrl, Integer.toString(response), responseMessage == null ? UI.EMPTY_STRING : responseMessage }); MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, message); } catch (final IOException e) { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, NLS.bind(Messages.prefPage_srtm_checkHTTPConnection_message, baseUrl)); e.printStackTrace(); } } } | 1,071 |
0 | protected boolean update(String sql, int requiredRows, int maxRows) throws SQLException { if (LOG.isDebugEnabled()) { LOG.debug("executing " + sql + "..."); } Connection connection = null; boolean oldAutoCommit = true; try { connection = dataSource.getConnection(); connection.clearWarnings(); oldAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); Statement statement = connection.createStatement(); int rowsAffected = statement.executeUpdate(sql); if (requiredRows != -1 && rowsAffected < requiredRows) { LOG.warn("(" + rowsAffected + ") less than " + requiredRows + " rows affected, rolling back..."); connection.rollback(); return false; } if (maxRows != -1 && rowsAffected > maxRows) { LOG.warn("(" + rowsAffected + ") more than " + maxRows + " rows affected, rolling back..."); connection.rollback(); return false; } connection.commit(); return true; } catch (SQLException e) { LOG.error("Unable to update database using: " + sql, e); throw e; } finally { try { if (connection != null) { connection.setAutoCommit(oldAutoCommit); connection.close(); } } catch (SQLException e) { LOG.error("Unable to close connection: " + e, e); } } } | public static boolean getFile(String s, String name) { try { File f = new File("D:\\buttons\\data\\sounds\\" + name); URL url = new URL(s); URLConnection conn = url.openConnection(); BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); int ch; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f)); while ((ch = bis.read()) != -1) { bos.write(ch); } System.out.println("wrote audio url: " + s + " \nto file " + f); } catch (Exception e) { e.printStackTrace(); return false; } return true; } | 1,072 |
0 | public static String sha1Hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; } | public Constructor run() throws Exception { String path = "META-INF/services/" + BeanletApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = BeanletApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (BeanletApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new BeanletApplicationException("No " + "BeanletApplicationContext implementation " + "found."); } | 1,073 |
0 | private static String fetch(String urltxt, String cookie) { try { URL url = new URL(urltxt); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream source = url.openStream(); String data = new Scanner(source).useDelimiter("\\A").next(); Pattern p = Pattern.compile("form action=\"(.*)\" method=\"post\""); Matcher m = p.matcher(data); if (!m.find()) return ""; urltxt = m.group(1); url = new URL(urltxt); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie", cookie); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write("dl.start=PREMIUM"); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); while ((data = in.readLine()) != null) sb.append(data + System.getProperty("line.separator")); data = urltxt.substring(urltxt.lastIndexOf("/") + 1); p = Pattern.compile("<tr><td><a href=\"(.*?)" + data); m = p.matcher(sb.toString()); data = (m.find()) ? (m.group(1) + data + System.getProperty("line.separator")) : ""; return data; } catch (Exception e) { return ""; } } | public static boolean sendPostRequest(String path, Map<String, String> params, String encoding) throws Exception { StringBuilder sb = new StringBuilder(""); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), encoding)).append('&'); } sb.deleteCharAt(sb.length() - 1); } byte[] data = sb.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(data); outStream.flush(); outStream.close(); if (conn.getResponseCode() == 200) { InputStream inputStream = conn.getInputStream(); return ResponseResult.parseXML(inputStream); } return false; } | 1,074 |
1 | public static final String MD5(String value) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(value.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String newValue = hash.toString(16); return newValue; } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return null; } } | public String obfuscateString(String string) { String obfuscatedString = null; try { MessageDigest md = MessageDigest.getInstance(ENCRYPTION_ALGORITHM); md.update(string.getBytes()); byte[] digest = md.digest(); obfuscatedString = new String(Base64.encode(digest)).replace(DELIM_PATH, '='); } catch (NoSuchAlgorithmException e) { StatusHandler.log("SHA not available", null); obfuscatedString = LABEL_FAILED_TO_OBFUSCATE; } return obfuscatedString; } | 1,075 |
0 | private static String getRegistrationClasses() { CentralRegistrationClass c = new CentralRegistrationClass(); String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class"); try { Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); String file = url.getFile(); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest mf = jarConnection.getManifest(); Attributes attrs = (Attributes) mf.getAttributes(name); if (attrs != null) { String classes = attrs.getValue("RegistrationClasses"); return classes; } } } catch (IOException ex) { ex.printStackTrace(); } return ""; } | protected Ontology loadOntology(String ontologyIri) throws IOException, ParserException, InvalidModelException { assert ontologyIri != null; URL url = null; Ontology ontology = null; url = new URL(ontologyIri); InputStream is = url.openStream(); TopEntity[] identifiable = parser.parse(new InputStreamReader(is)); if (identifiable.length > 0 && identifiable[0] instanceof Ontology) { ontology = ((Ontology) identifiable[0]); } return ontology; } | 1,076 |
1 | protected File downloadFile(String href) { Map<String, File> currentDownloadDirMap = downloadedFiles.get(downloadDir); if (currentDownloadDirMap != null) { File downloadedFile = currentDownloadDirMap.get(href); if (downloadedFile != null) { return downloadedFile; } } else { downloadedFiles.put(downloadDir, new HashMap<String, File>()); currentDownloadDirMap = downloadedFiles.get(downloadDir); } URL url; File result; try { FilesystemUtils.forceMkdirIfNotExists(downloadDir); url = generateUrl(href); result = createUniqueFile(downloadDir, href); } catch (IOException e) { LOG.warn("Failed to create file for download", e); return null; } currentDownloadDirMap.put(href, result); LOG.info("Downloading " + url); try { IOUtils.copy(url.openStream(), new FileOutputStream(result)); } catch (IOException e) { LOG.warn("Failed to download file " + url); } return result; } | 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; } | 1,077 |
1 | public static void main(String[] args) { try { { byte[] bytes1 = { (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; byte[] bytes2 = { (byte) 99, (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; System.out.println("Bytes 2,2,3,0,9 as Base64: " + encodeBytes(bytes1)); System.out.println("Bytes 2,2,3,0,9 w/ offset: " + encodeBytes(bytes2, 1, bytes2.length - 1)); byte[] dbytes = decode(encodeBytes(bytes1)); System.out.print(encodeBytes(bytes1) + " decoded: "); for (int i = 0; i < dbytes.length; i++) System.out.print(dbytes[i] + (i < dbytes.length - 1 ? "," : "\n")); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif.b64"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); byte[] bytes = new byte[0]; int b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[bytes.length + 1]; System.arraycopy(bytes, 0, temp, 0, bytes.length); temp[bytes.length] = (byte) b; bytes = temp; } b64is.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon(bytes); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif.b64", iicon, 0); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif_out"); fos.write(bytes); fos.close(); fis = new java.io.FileInputStream("test.gif_out"); b64is = new Base64.InputStream(fis, ENCODE); byte[] ebytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[ebytes.length + 1]; System.arraycopy(ebytes, 0, temp, 0, ebytes.length); temp[ebytes.length] = (byte) b; ebytes = temp; } b64is.close(); String s = new String(ebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif_out"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.setVisible(true); fos = new java.io.FileOutputStream("test.gif.b64_out"); fos.write(ebytes); fis = new java.io.FileInputStream("test.gif.b64_out"); b64is = new Base64.InputStream(fis, DECODE); byte[] edbytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[edbytes.length + 1]; System.arraycopy(edbytes, 0, temp, 0, edbytes.length); temp[edbytes.length] = (byte) b; edbytes = temp; } b64is.close(); iicon = new javax.swing.ImageIcon(edbytes); jlabel = new javax.swing.JLabel("Read from test.gif.b64_out", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif_out"); byte[] rbytes = new byte[0]; int b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rbytes.length + 1]; System.arraycopy(rbytes, 0, temp, 0, rbytes.length); temp[rbytes.length] = (byte) b; rbytes = temp; } fis.close(); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif.b64_out2"); Base64.OutputStream b64os = new Base64.OutputStream(fos, ENCODE); b64os.write(rbytes); b64os.close(); fis = new java.io.FileInputStream("test.gif.b64_out2"); byte[] rebytes = new byte[0]; b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rebytes.length + 1]; System.arraycopy(rebytes, 0, temp, 0, rebytes.length); temp[rebytes.length] = (byte) b; rebytes = temp; } fis.close(); String s = new String(rebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif.b64_out2"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.setVisible(true); fos = new java.io.FileOutputStream("test.gif_out2"); b64os = new Base64.OutputStream(fos, DECODE); b64os.write(rebytes); b64os.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon("test.gif_out2"); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif_out2", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); } { java.io.FileInputStream fis = new java.io.FileInputStream("D:\\temp\\testencoding.txt"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); java.io.FileOutputStream fos = new java.io.FileOutputStream("D:\\temp\\file.zip"); int b; while ((b = b64is.read()) >= 0) fos.write(b); fos.close(); b64is.close(); } } catch (Exception e) { e.printStackTrace(); } } | private void packageDestZip(File tmpFile) throws FileNotFoundException, IOException { log("Creating launch profile package " + destfile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destfile))); ZipEntry e = new ZipEntry(RESOURCE_JAR_FILENAME); e.setMethod(ZipEntry.STORED); e.setSize(tmpFile.length()); e.setCompressedSize(tmpFile.length()); e.setCrc(calcChecksum(tmpFile, new CRC32())); out.putNextEntry(e); InputStream in = new BufferedInputStream(new FileInputStream(tmpFile)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.closeEntry(); out.finish(); out.close(); } | 1,078 |
1 | private Document saveFile(Document document, File file) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { Preference preference = preferences.get(0); String repo = preference.getRepository(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(document.getLocation()); File folder = new File(sbRepo.append(sbFolder).toString()); log.info("Check in file ID [" + document.getId() + "] to " + folder.getAbsolutePath()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null, fcVersionDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append(".").append(document.getExt()); StringBuffer sbVersionFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append("_").append(document.getVersion().toString()).append(".").append(document.getExt()); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcVersionDest = new FileOutputStream(sbVersionFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); fcSource = new FileInputStream(file).getChannel(); fcVersionDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } if (fcVersionDest != null) { fcVersionDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return document; } | public void setContentAsStream(final InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { output.close(); } this.content = output.toByteArray(); } | 1,079 |
0 | public DatabaseDefinitionFactory(final DBIf db, final String adapter) throws IOException { _db = db; LOG.debug("Loading adapter: " + adapter); final URL url = getClass().getClassLoader().getResource("adapter/" + adapter + ".properties"); _props = new Properties(); _props.load(url.openStream()); if (adapter.equals("mysql")) { _modifier = new MySQLModifier(this); } else if (adapter.equals("postgresql")) { _modifier = new PostgresModifier(this); } else if (adapter.equals("hypersonic")) { _modifier = new HSQLModifier(this); } else if (adapter.equals("oracle")) { _modifier = new OracleModifier(this); } else if (adapter.equals("mssql")) { _modifier = new MSSQLModifier(this); } else { _modifier = null; } } | public static void copyFile(File src, File dest, boolean notifyUserOnError) { if (src.exists()) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } catch (IOException e) { String message = "Error while copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " : " + e.getMessage(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } } else { String message = "Unable to copy file: source does not exists: " + src.getAbsolutePath(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } } | 1,080 |
0 | @Override public InputStream getResourceAsStream(String path) { try { URL url = this.getResource(path); if (url == null) return null; return url.openStream(); } catch (Exception e) { log(e.getMessage(), e); return null; } } | 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(); } } | 1,081 |
0 | public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } | public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } | 1,082 |
1 | public static String encripty(String toEncripty) { if (toEncripty != null) { try { synchronized (toEncripty) { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(toEncripty.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); 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])); } toEncripty = hexString.toString(); } } catch (Exception e) { e.getMessage(); } } return toEncripty; } | @Override public final byte[] getDigest() { try { final MessageDigest hashing = MessageDigest.getInstance("SHA-256"); final Charset utf16 = Charset.forName("UTF-16"); for (final CollationKey wordKey : this.words) { hashing.update(wordKey.toByteArray()); } hashing.update(this.locale.toString().getBytes(utf16)); hashing.update(ByteUtils.toBytesLE(this.collator.getStrength())); hashing.update(ByteUtils.toBytesLE(this.collator.getDecomposition())); return hashing.digest(); } catch (final NoSuchAlgorithmException e) { FileBasedDictionary.LOG.severe(e.toString()); return new byte[0]; } } | 1,083 |
1 | private String fetchCompareContent() throws IOException { URL url = new URL(compareTo); StringWriter sw = new StringWriter(); IOUtils.copy(url.openStream(), sw); return sw.getBuffer().toString(); } | private void refreshCacheFile(RepositoryFile file, File cacheFile) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(cacheFile); InputStream is = file.getInputStream(); int count = IOUtils.copy(is, fos); logger.debug("===========================================================> wrote bytes to cache " + count); fos.flush(); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(file.getInputStream()); } | 1,084 |
0 | public void doNew(Vector userId, String shareFlag, String folderId) throws AddrException { DBOperation dbo = null; Connection connection = null; PreparedStatement ps = null; ResultSet rset = null; String sql = "insert into " + SHARE_TABLE + " values(?,?,?)"; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); for (int i = 0; i < userId.size(); i++) { String user = (String) userId.elementAt(i); ps = connection.prepareStatement(sql); ps.setInt(1, Integer.parseInt(folderId)); ps.setInt(2, Integer.parseInt(user)); ps.setString(3, shareFlag); int resultCount = ps.executeUpdate(); if (resultCount != 1) { throw new Exception("error"); } } connection.commit(); } catch (Exception ex) { if (connection != null) { try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } logger.error("���������ļ�����Ϣʧ��, " + ex.getMessage()); throw new AddrException("���������ļ�����Ϣʧ��,һ�������ļ���ֻ�ܹ����ͬһ�û�һ��!"); } finally { close(rset, null, ps, connection, dbo); } } | public static void upper() throws Exception { File input = new File("dateiname"); PostMethod post = new PostMethod("url"); post.setRequestBody(new FileInputStream(input)); if (input.length() < Integer.MAX_VALUE) post.setRequestContentLength((int) input.length()); else post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED); post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859�1"); HttpClient httpclient = new HttpClient(); httpclient.executeMethod(post); post.releaseConnection(); URL url = new URL("https://www.amazon.de/"); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); } | 1,085 |
0 | public static void printResponseHeaders(String address) { logger.info("Address: " + address); try { URL url = new URL(address); URLConnection conn = url.openConnection(); for (int i = 0; ; i++) { String headerName = conn.getHeaderFieldKey(i); String headerValue = conn.getHeaderField(i); if (headerName == null && headerValue == null) { break; } if (headerName == null) { logger.info(headerValue); continue; } logger.info(headerName + " " + headerValue); } } catch (Exception e) { logger.error("Exception Message: " + e.getMessage()); } } | public static void verifierSiDerniereVersionDesPluginsMenus(ControleurDeMenu i) { if (i.getURLFichierInfoDerniereVersion() == null || i.getURLFichierInfoDerniereVersion() == "") { System.err.println("Evenements.java:verifierSiDerniereVersionDesPluginsMenus impossible:\n" + "pour le plugin chargeur de menu :" + i.getNomPlugin()); } if (i.getVersionPlugin() == 0) { System.err.println("version non renseignee pour :" + i.getNomPlugin() + " on continue sur le plugin suivant"); return; } URL url; try { url = new URL(i.getURLFichierInfoDerniereVersion()); } catch (MalformedURLException e1) { System.err.println("impossible d'ouvrir l'URL (url mal formee)" + i.getURLFichierInfoDerniereVersion() + "\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } InputStream is; try { is = url.openStream(); } catch (IOException e1) { System.err.println("impossible d'ouvrir l'URL (destination inaccessible)" + i.getURLFichierInfoDerniereVersion() + "\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } File destination; try { destination = File.createTempFile("SimplexeReseau" + compteurDeFichiersTemporaires, ".buf"); } catch (IOException e1) { System.err.println("impossible de creer le fichier temporaire\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } compteurDeFichiersTemporaires++; destination.deleteOnExit(); java.io.InputStream sourceFile = null; java.io.FileOutputStream destinationFile = null; try { destination.createNewFile(); } catch (IOException e) { System.err.println("impossible de creer un fichier temporaire\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } sourceFile = is; try { destinationFile = new FileOutputStream(destination); } catch (FileNotFoundException e) { System.err.println("impossible d'ouvrir le flux reseau\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } byte buffer[] = new byte[512 * 1024]; int nbLecture; try { while ((nbLecture = sourceFile.read(buffer)) != -1) { destinationFile.write(buffer, 0, nbLecture); } } catch (IOException e) { System.err.println("impossible d'ecrire dans le fichier temporaire\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } try { sourceFile.close(); destinationFile.close(); } catch (IOException e) { System.err.println("impossible de fermer le fichier temporaire ou le flux reseau\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } BufferedReader lecteurAvecBuffer = null; String ligne; try { lecteurAvecBuffer = new BufferedReader(new FileReader(destination)); } catch (FileNotFoundException e) { System.err.println("impossible d'ouvrir le fichier temporaire apres sa creation (contacter un developpeur)\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } try { boolean estLaDerniereVersion = true; String URLRecupererDerniereVersion = null; while ((ligne = lecteurAvecBuffer.readLine()) != null) { if (ligne.startsWith("version:")) { if (ligne.equals("version:" + i.getVersionPlugin())) { } else { System.err.println("la version pour " + i.getNomPlugin() + " est depassee (" + i.getVersionPlugin() + " alors que la " + ligne + "est disponible)"); estLaDerniereVersion = false; } } if (ligne.startsWith("url:")) { URLRecupererDerniereVersion = ligne.substring(4, ligne.length()); } } if (!estLaDerniereVersion && URLRecupererDerniereVersion != null) { TelechargerPluginEtCharger(i, URLRecupererDerniereVersion); } else { System.out.println("on est a la derniere version du plugin " + i.getNomPlugin()); } } catch (IOException e) { System.err.println("impossible de lire le fichier temporaire apres sa creation\n lors de la recuperation des informations de version sur " + i.getNomPlugin()); return; } try { lecteurAvecBuffer.close(); } catch (IOException e) { return; } } | 1,086 |
1 | private void retrieveData() { StringBuffer obsBuf = new StringBuffer(); try { URL url = new URL(getProperty("sourceURL")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String lineIn = null; while ((lineIn = in.readLine()) != null) { if (GlobalProps.DEBUG) { logger.log(Level.FINE, "WebSource retrieveData: " + lineIn); } obsBuf.append(lineIn); } String fmt = getProperty("dataFormat"); if (GlobalProps.DEBUG) { logger.log(Level.FINE, "Raw: " + obsBuf.toString()); } if ("NWS XML".equals(fmt)) { obs = new NWSXmlObservation(obsBuf.toString()); } } catch (Exception e) { logger.log(Level.SEVERE, "Can't connect to: " + getProperty("sourceURL")); if (GlobalProps.DEBUG) { e.printStackTrace(); } } } | 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; } | 1,087 |
0 | public InputStream getDaoConfig(String connectionType) throws IOException { URL url = null; InputStream inStream = null; if (connectionType.equals(SQL.ORACLE)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("oracle.xml"); } else if (connectionType.equals(SQL.SQL2K)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("sql2k.xml"); } else if (connectionType.equals(SQL.CACHE)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("cache.xml"); } else if (connectionType.equals(SQL.DB2)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("db2.xml"); } else { Categories.dataXml().error("* Problem: Unknown connection type: " + connectionType); } try { inStream = url.openStream(); } catch (NullPointerException npe) { Categories.dataXml().error("* Problem: Undefined resource URL: " + npe.getMessage()); throw npe; } return inStream; } | private void copyFile(URL from, File to) { try { InputStream is = from.openStream(); IOUtils.copy(is, new FileOutputStream(to)); } catch (IOException e) { e.printStackTrace(); } } | 1,088 |
1 | private void performDownload() { List<String> selected = filesPane.getSelectedValuesList(); if (selected == null || selected.isEmpty() || selected.size() != 1) { JOptionPane.showMessageDialog(this, "Please select one path"); return; } RFile file = new RFile(selected.get(0)); if (!file.isFile()) { JOptionPane.showMessageDialog(this, "file does not exist anymore"); return; } chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), file.getName())); int ok = chooser.showSaveDialog(this); if (ok != JFileChooser.APPROVE_OPTION) { return; } FileOutputStream fout = null; RFileInputStream in = null; try { fout = new FileOutputStream(chooser.getSelectedFile()); in = new RFileInputStream(file); IOUtils.copy(in, fout); JOptionPane.showMessageDialog(this, "File downloaded to " + chooser.getSelectedFile(), "Download finished", JOptionPane.INFORMATION_MESSAGE); } catch (IOException iOException) { JOptionPane.showMessageDialog(this, "Error: " + iOException, "Error", JOptionPane.ERROR_MESSAGE); } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (fout != null) { try { fout.close(); } catch (Throwable t) { } } } } | public void save(InputStream is) throws IOException { File dest = Config.getDataFile(getInternalDate(), getPhysMessageID()); OutputStream os = null; try { os = new FileOutputStream(dest); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } } | 1,089 |
1 | private ArrayList<String> loadProperties(String filename) throws DevFailed, IOException { java.net.URL url = getClass().getResource(filename); if (url == null) { Except.throw_exception("LOAD_PROPERTY_FAILED", "URL for property file (" + filename + ") is null !", "PogoProperty.loadProperties()"); return null; } InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ArrayList<String> vs = new ArrayList<String>(); String str; while ((str = br.readLine()) != null) { str = str.trim(); if (!str.startsWith("#")) if (str.length() > 0) vs.add(str); } br.close(); return vs; } | public static String ReadURLString(String str) throws IOException { try { URL url = new URL(str); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader in = new BufferedReader(isr); String inputLine; String line = ""; int i = 0; while ((inputLine = in.readLine()) != null) { line += inputLine + "\n"; } is.close(); isr.close(); in.close(); return line; } catch (Exception e) { e.printStackTrace(); } return ""; } | 1,090 |
1 | public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } | public static void copyFile(File src, File dst) throws IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[1024]; int count = 0; while ((count = is.read(buf, 0, 1024)) != -1) os.write(buf, 0, count); is.close(); os.close(); } | 1,091 |
1 | public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); String year = req.getParameter("year").toString(); String round = req.getParameter("round").toString(); resp.getWriter().println("<html><body>"); resp.getWriter().println("Searching for : " + year + ", " + round + "<br/>"); StringBuffer sb = new StringBuffer("http://www.dfb.de/bliga/bundes/archiv/"); sb.append(year).append("/xml/blm_e_").append(round).append("_").append(year.substring(2, 4)).append(".xml"); resp.getWriter().println(sb.toString() + "<br/><br/>"); try { URL url = new URL(sb.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer xml = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { xml.append(line); } Document document = DocumentHelper.parseText(xml.toString()); List termine = document.selectNodes("//ergx/termin"); int index = 1; for (Object termin : termine) { Element terminNode = (Element) termin; resp.getWriter().println("Termin " + index + " : " + terminNode.element("datum").getText() + "<br/>"); resp.getWriter().println("Heim:" + terminNode.element("teama").getText() + "<br/>"); resp.getWriter().println("Gast:" + terminNode.element("teamb").getText() + "<br/>"); resp.getWriter().println("Ergebnis:" + terminNode.element("punkte_a").getText() + ":" + terminNode.element("punkte_b").getText() + "<br/>"); resp.getWriter().println("<br/>"); index++; } resp.getWriter().println(); resp.getWriter().println("</body></html>"); reader.close(); } catch (MalformedURLException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } catch (DocumentException ex) { throw new RuntimeException(ex); } } | String openUrlAsString(String address, int maxLines) { StringBuffer sb; try { URL url = new URL(address); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); sb = new StringBuffer(); int count = 0; String line; while ((line = br.readLine()) != null && count++ < maxLines) sb.append(line + "\n"); in.close(); } catch (IOException e) { sb = null; } return sb != null ? new String(sb) : null; } | 1,092 |
0 | public Document load(java.net.URL url) throws DOMTestLoadException { Document doc = null; try { java.io.InputStream stream = url.openStream(); Object tidyObj = tidyConstructor.newInstance(new Object[0]); doc = (Document) parseDOMMethod.invoke(tidyObj, new Object[] { stream, null }); } catch (InvocationTargetException ex) { throw new DOMTestLoadException(ex.getTargetException()); } catch (Exception ex) { throw new DOMTestLoadException(ex); } return doc; } | public String parseInOneLine() throws Exception { BufferedReader br = null; InputStream httpStream = null; if (url.startsWith("http")) { URL fileURL = new URL(url); URLConnection urlConnection = fileURL.openConnection(); httpStream = urlConnection.getInputStream(); br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); } else { br = new BufferedReader(new FileReader(url)); } StringBuffer sb = new StringBuffer(); StringBuffer sbAllDoc = new StringBuffer(); String ligne = null; boolean get = false; while ((ligne = br.readLine()) != null) { log.debug(ligne); sbAllDoc.append(ligne + " "); if (ligne.indexOf("<table") != -1) { get = true; } if (get) { sb.append(ligne + " "); } if (ligne.indexOf("</table") != -1 || ligne.indexOf("</tr></font><center><a href='affichaire.php") != -1 || ligne.indexOf("</font><center><a href='afficheregion.php") != -1) { get = false; break; } } oneLine = sb.toString(); allDocInOneLine = sbAllDoc.toString(); if (oneLine.indexOf("</table") != -1) { tableTab = new TableTag(oneLine.substring(oneLine.indexOf(">") + 1, oneLine.indexOf("</table"))); } else if (oneLine.indexOf("</font><center><a href='affichaire") != -1) { tableTab = new TableTag(oneLine.substring(oneLine.indexOf(">") + 1, oneLine.indexOf("</font><center><a href='affichaire"))); } else if (oneLine.indexOf("</font><center><a href='afficheregion.php") != -1) { tableTab = new TableTag(oneLine.substring(oneLine.indexOf(">") + 1, oneLine.indexOf("</font><center><a href='afficheregion.php"))); } else { log.error("La fin du fichier HTML n'a pas ete trouvee, ca va merder..."); } br.close(); if (httpStream != null) { httpStream.close(); } return allDocInOneLine; } | 1,093 |
0 | static final String md5(String text) throws RtmApiException { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RtmApiException("Md5 error: NoSuchAlgorithmException - " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RtmApiException("Md5 error: UnsupportedEncodingException - " + e.getMessage()); } } | public static GenericDocumentTransformer<? extends GenericDocument> getTranformer(URL url) throws IOException { setDefaultImplementation(); if ("text/xml".equals(url.openConnection().getContentType()) || "application/xml".equals(url.openConnection().getContentType())) { return null; } else if ("text/html".equals(url.openConnection().getContentType())) { return null; } return null; } | 1,094 |
0 | @Override public void alterar(QuestaoDiscursiva q) throws Exception { System.out.println("ALTERAR " + q.getIdQuestao()); PreparedStatement stmt = null; String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getDisciplina().getIdDisciplina()); stmt.setString(2, q.getEnunciado()); stmt.setString(3, q.getDificuldade().name()); stmt.setInt(4, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); alterarQuestaoDiscursiva(q); } catch (SQLException e) { conexao.rollback(); throw e; } } | private static void initMagicRules() { InputStream in = null; try { String fname = System.getProperty("magic-mime"); if (fname != null && fname.length() != 0) { in = new FileInputStream(fname); if (in != null) { parse("-Dmagic-mime=" + fname, new InputStreamReader(in)); } } } catch (Exception e) { log.error("Failed to parse custom magic mime file defined by system property -Dmagic-mime [" + System.getProperty("magic-mime") + "]. File will be ignored.", e); } finally { in = closeStream(in); } try { Enumeration en = MimeUtil.class.getClassLoader().getResources("magic.mime"); while (en.hasMoreElements()) { URL url = (URL) en.nextElement(); in = url.openStream(); if (in != null) { try { parse("classpath:[" + url + "]", new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse magic.mime rule file [" + url + "] on the classpath. File will be ignored.", ex); } } } } catch (Exception e) { log.error("Problem while processing magic.mime files from classpath. Files will be ignored.", e); } finally { in = closeStream(in); } try { File f = new File(System.getProperty("user.home") + File.separator + ".magic.mime"); if (f.exists()) { in = new FileInputStream(f); if (in != null) { try { parse(f.getAbsolutePath(), new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse .magic.mime file from the users home directory. File will be ignored.", ex); } } } } catch (Exception e) { log.error("Problem while processing .magic.mime file from the users home directory. File will be ignored.", e); } finally { in = closeStream(in); } try { String name = System.getProperty("MAGIC"); if (name != null && name.length() != 0) { if (name.indexOf('.') < 0) { name = name + ".mime"; } else { name = name.substring(0, name.indexOf('.') - 1) + "mime"; } File f = new File(name); if (f.exists()) { in = new FileInputStream(f); if (in != null) { try { parse(f.getAbsolutePath(), new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse magic.mime file from directory located by environment variable MAGIC. File will be ignored.", ex); } } } } } catch (Exception e) { log.error("Problem while processing magic.mime file from directory located by environment variable MAGIC. File will be ignored.", e); } finally { in = closeStream(in); } int mMagicMimeEntriesSizeBeforeReadingOS = mMagicMimeEntries.size(); Iterator it = magicMimeFileLocations.iterator(); while (it.hasNext()) { parseMagicMimeFileLocation((String) it.next()); } if (mMagicMimeEntriesSizeBeforeReadingOS == mMagicMimeEntries.size()) { try { String resource = "eu/medsea/mimeutil/magic.mime"; in = MimeUtil.class.getClassLoader().getResourceAsStream(resource); if (in != null) { try { parse("resource:" + resource, new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse internal magic.mime file.", ex); } } } catch (Exception e) { log.error("Problem while processing internal magic.mime file.", e); } finally { in = closeStream(in); } } } | 1,095 |
0 | @Override public void loadTest(StoryCardModel story) { String strUrl = story.getStoryCard().getAcceptanceTestUrl(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder loader; try { URL url = new URL(strUrl); loader = factory.newDocumentBuilder(); Document document; document = loader.parse(url.openStream()); this.numPass = Integer.parseInt(((Element) document.getElementsByTagName("num-pass").item(0)).getFirstChild().getNodeValue()); this.numFail = Integer.parseInt(((Element) document.getElementsByTagName("num-fail").item(0)).getFirstChild().getNodeValue()); this.numRuns = Integer.parseInt(((Element) document.getElementsByTagName("num-runs").item(0)).getFirstChild().getNodeValue()); this.numExceptions = Integer.parseInt(((Element) document.getElementsByTagName("num-exceptions").item(0)).getFirstChild().getNodeValue()); this.wikiText = ((Element) document.getElementsByTagName("wiki").item(0)).getFirstChild().getNodeValue(); } catch (Exception e) { util.Logger.singleton().error(e); } } | public boolean exists(String filename) { String localFileName = (java.io.File.separatorChar != '/') ? filename.replace('/', java.io.File.separatorChar) : filename; for (int i = 0; i < dirs.length; i++) { if (zipEntries[i] != null) { if (zipEntries[i].get(filename) != null) return true; String dir = ""; String name = filename; int index = filename.lastIndexOf('/'); if (index >= 0) { dir = filename.substring(0, index); name = filename.substring(index + 1); } Vector directory = (Vector) zipEntries[i].get(dir); if (directory != null && directory.contains(name)) return true; continue; } if (bases[i] != null) { try { URL url = new URL(bases[i], filename); URLConnection conn = url.openConnection(); conn.connect(); conn.getInputStream().close(); return true; } catch (IOException ex) { } continue; } if (dirs[i] == null) continue; if (zips[i] != null) { String fullname = zipDirs[i] != null ? zipDirs[i] + filename : filename; ZipEntry ze = zips[i].getEntry(fullname); if (ze != null) return true; } else { try { File f = new File(dirs[i], localFileName); if (f.exists()) return true; } catch (SecurityException ex) { } } } return false; } | 1,096 |
1 | public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } | public static void copyFile(File in, File out) { if (!in.exists() || !in.canRead()) { LOGGER.warn("Can't copy file : " + in); return; } if (!out.getParentFile().exists()) { if (!out.getParentFile().mkdirs()) { LOGGER.info("Didn't create parent directories : " + out.getParentFile().getAbsolutePath()); } } if (!out.exists()) { try { out.createNewFile(); } catch (IOException e) { LOGGER.error("Exception creating new file : " + out.getAbsolutePath(), e); } } LOGGER.debug("Copying file : " + in + ", to : " + out); FileChannel inChannel = null; FileChannel outChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(in); inChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(out); outChannel = fileOutputStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (Exception e) { LOGGER.error("Exception copying file : " + in + ", to : " + out, e); } finally { close(fileInputStream); close(fileOutputStream); if (inChannel != null) { try { inChannel.close(); } catch (Exception e) { LOGGER.error("Exception closing input channel : ", e); } } if (outChannel != null) { try { outChannel.close(); } catch (Exception e) { LOGGER.error("Exception closing output channel : ", e); } } } } | 1,097 |
1 | protected static final void copyFile(String from, String to) throws SeleniumException { try { java.io.File fileFrom = new File(from); java.io.File fileTo = new File(to); FileReader in = new FileReader(fileFrom); FileWriter out = new FileWriter(fileTo); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { throw new SeleniumException("Failed to copy new file : " + from + " to : " + to, e); } } | @Action(value = "ajaxFileUploads", results = { }) public void ajaxFileUploads() throws IOException { String extName = ""; String newFilename = ""; String nowTimeStr = ""; String realpath = ""; if (Validate.StrNotNull(this.getImgdirpath())) { realpath = "Uploads/" + this.getImgdirpath() + "/"; } else { realpath = this.isexistdir(); } SimpleDateFormat sDateFormat; Random r = new Random(); String savePath = ServletActionContext.getServletContext().getRealPath(""); savePath = savePath + realpath; HttpServletResponse response = ServletActionContext.getResponse(); int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000; sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); nowTimeStr = sDateFormat.format(new Date()); String filename = request.getHeader("X-File-Name"); if (filename.lastIndexOf(".") >= 0) { extName = filename.substring(filename.lastIndexOf(".")); } newFilename = nowTimeStr + rannum + extName; PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log.debug(ImgTAction.class.getName() + "has thrown an exception:" + ex.getMessage()); } try { is = request.getInputStream(); fos = new FileOutputStream(new File(savePath + newFilename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success:'" + realpath + newFilename + "'}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { this.setImgdirpath(null); fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } | 1,098 |
1 | public static void copyTo(File inFile, File outFile) throws IOException { char[] cbuff = new char[32768]; BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); int readedBytes = 0; long absWrittenBytes = 0; while ((readedBytes = reader.read(cbuff, 0, cbuff.length)) != -1) { writer.write(cbuff, 0, readedBytes); absWrittenBytes += readedBytes; } reader.close(); writer.close(); } | public static void makeLPKFile(String[] srcFilePath, String makeFilePath, LPKHeader header) { FileOutputStream os = null; DataOutputStream dos = null; try { LPKTable[] fileTable = new LPKTable[srcFilePath.length]; long fileOffset = outputOffset(header); for (int i = 0; i < srcFilePath.length; i++) { String sourceFileName = FileUtils.getFileName(srcFilePath[i]); long sourceFileSize = FileUtils.getFileSize(srcFilePath[i]); LPKTable ft = makeLPKTable(sourceFileName, sourceFileSize, fileOffset); fileOffset = outputNextOffset(sourceFileSize, fileOffset); fileTable[i] = ft; } File file = new File(makeFilePath); if (!file.exists()) { FileUtils.makedirs(file); } os = new FileOutputStream(file); dos = new DataOutputStream(os); dos.writeInt(header.getPAKIdentity()); writeByteArray(header.getPassword(), dos); dos.writeFloat(header.getVersion()); dos.writeLong(header.getTables()); for (int i = 0; i < fileTable.length; i++) { writeByteArray(fileTable[i].getFileName(), dos); dos.writeLong(fileTable[i].getFileSize()); dos.writeLong(fileTable[i].getOffSet()); } for (int i = 0; i < fileTable.length; i++) { File ftFile = new File(srcFilePath[i]); FileInputStream ftFis = new FileInputStream(ftFile); DataInputStream ftDis = new DataInputStream(ftFis); byte[] buff = new byte[256]; int readLength = 0; while ((readLength = ftDis.read(buff)) != -1) { makeBuffer(buff, readLength); dos.write(buff, 0, readLength); } ftDis.close(); ftFis.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (dos != null) { try { dos.close(); dos = null; } catch (IOException e) { } } } } | 1,099 |