label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
public static String httpGetJson(final List<NameValuePair> nameValuePairs) { HttpClient httpclient = null; String data = ""; URI uri = null; try { final String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); if (HTTPS) { final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final HttpParams params = new BasicHttpParams(); final SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry); httpclient = new DefaultHttpClient(mgr, params); uri = new URI(DEADDROPS_SERVER_URL_HTTPS + "?" + paramString); } else { httpclient = new DefaultHttpClient(); uri = new URI(DEADDROPS_SERVER_URL + "?" + paramString); } final HttpGet request = new HttpGet(); request.setURI(uri); final HttpResponse response = httpclient.execute(request); final BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) data += inputLine; in.close(); } catch (final URISyntaxException e) { e.printStackTrace(); return null; } catch (final ClientProtocolException e) { e.printStackTrace(); return null; } catch (final IOException e) { e.printStackTrace(); return null; } return data; }
Code Sample 2:
private String fetchLocalPage(String page) throws IOException { final String fullUrl = HOST + page; LOG.debug("Fetching local page: " + fullUrl); URL url = new URL(fullUrl); URLConnection connection = url.openConnection(); StringBuilder sb = new StringBuilder(); BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = input.readLine()) != null) { sb.append(line).append("\n"); } } finally { if (input != null) try { input.close(); } catch (IOException e) { LOG.error("Could not close reader!", e); } } return sb.toString(); }
|
00
|
Code Sample 1:
protected String getLibJSCode() throws IOException { if (cachedLibJSCode == null) { InputStream is = getClass().getResourceAsStream(JS_LIB_FILE); StringWriter output = new StringWriter(); IOUtils.copy(is, output); cachedLibJSCode = output.toString(); } return cachedLibJSCode; }
Code Sample 2:
public static String generateToken(ClientInfo clientInfo) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); Random rand = new Random(); String random = clientInfo.getIpAddress() + ":" + clientInfo.getPort() + ":" + rand.nextInt(); md5.update(random.getBytes()); String token = toHexString(md5.digest((new Date()).toString().getBytes())); clientInfo.setToken(token); return token; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
|
11
|
Code Sample 1:
private void processBasicContent() { String[] packageNames = sourceCollector.getPackageNames(); for (int i = 0; i < packageNames.length; i++) { XdcSource[] sources = sourceCollector.getXdcSources(packageNames[i]); File dir = new File(outputDir, packageNames[i]); dir.mkdirs(); Set pkgDirs = new HashSet(); for (int j = 0; j < sources.length; j++) { XdcSource source = sources[j]; Properties patterns = source.getPatterns(); if (patterns != null) { tables.put("patterns", patterns); } pkgDirs.add(source.getFile().getParentFile()); DialectHandler dialectHandler = source.getDialectHandler(); Writer out = null; try { String sourceFilePath = source.getFile().getAbsolutePath(); source.setProcessingProperties(baseProperties, j > 0 ? sources[j - 1].getFileName() : null, j < sources.length - 1 ? sources[j + 1].getFileName() : null); String rootComment = XslUtils.transformToString(sourceFilePath, XSL_PKG + "/source-header.xsl", tables); source.setRootComment(rootComment); Document htmlDoc = XslUtils.transform(sourceFilePath, encoding, dialectHandler.getXslResourcePath(), tables); if (LOG.isInfoEnabled()) { LOG.info("Processing source file " + sourceFilePath); } out = IOUtils.getWriter(new File(dir, source.getFile().getName() + ".html"), docencoding); XmlUtils.printHtml(out, htmlDoc); if (sourceProcessor != null) { sourceProcessor.processSource(source, encoding, docencoding); } XdcSource.clearProcessingProperties(baseProperties); } catch (XmlException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } for (Iterator iter = pkgDirs.iterator(); iter.hasNext(); ) { File docFilesDir = new File((File) iter.next(), "xdc-doc-files"); if (docFilesDir.exists() && docFilesDir.isDirectory()) { File targetDir = new File(dir, "xdc-doc-files"); targetDir.mkdirs(); try { IOUtils.copyTree(docFilesDir, targetDir); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } }
Code Sample 2:
@Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
|
00
|
Code Sample 1:
public void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public static void initStaticStuff() { Enumeration<URL> urls = null; try { urls = Play.class.getClassLoader().getResources("play.static"); } catch (Exception e) { } while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { try { Class.forName(line); } catch (Exception e) { System.out.println("! Cannot init static : " + line); } } } catch (Exception ex) { Logger.error(ex, "Cannot load %s", url); } } }
Code Sample 2:
public static String email_get_public_hash(String email) { try { if (email != null) { email = email.trim().toLowerCase(); CRC32 crc32 = new CRC32(); crc32.reset(); crc32.update(email.getBytes()); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); return crc32.getValue() + " " + new String(md5.digest(email.getBytes())); } } catch (Exception e) { } return ""; }
|
11
|
Code Sample 1:
public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }
Code Sample 2:
public long copyDirAllFilesToDirectoryRecursive(String baseDirStr, String destDirStr, boolean copyOutputsRtIDsDirs) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } if (entryFile.isDirectory()) { boolean enableCopyDir = false; if (copyOutputsRtIDsDirs) { enableCopyDir = true; } else { if (entryFile.getParentFile().getName().equals("outputs")) { enableCopyDir = false; } else { enableCopyDir = true; } } if (enableCopyDir) { plussQuotaSize += this.copyDirAllFilesToDirectoryRecursive(baseDirStr + sep + entryName, destDirStr + sep + entryName, copyOutputsRtIDsDirs); } } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; }
|
00
|
Code Sample 1:
public String getIpAddress() { try { URL url = new URL("http://checkip.dyndns.org"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String linha; String rtn = ""; while ((linha = in.readLine()) != null) rtn += linha; ; in.close(); return filtraRetorno(rtn); } catch (IOException ex) { Logger.getLogger(ExternalIp.class.getName()).log(Level.SEVERE, null, ex); return "ERRO."; } }
Code Sample 2:
private static String downloadMedia(String mediadir, URL remoteFile) throws Exception, InterruptedException { File tmpDir = new File(System.getProperty("java.io.tmpdir") + "org.ogre4j.examples/" + mediadir); if (!tmpDir.exists()) { tmpDir.mkdirs(); } URLConnection urlConnection = remoteFile.openConnection(); if (urlConnection.getConnectTimeout() != 0) { urlConnection.setConnectTimeout(0); } InputStream content = remoteFile.openStream(); BufferedInputStream bin = new BufferedInputStream(content); String downloaded = tmpDir.getCanonicalPath() + File.separatorChar + new File(remoteFile.getFile()).getName(); File file = new File(downloaded); BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file)); System.out.println("downloading file " + remoteFile + " ..."); for (long i = 0; i < urlConnection.getContentLength(); i++) { bout.write(bin.read()); } bout.close(); bout = null; bin.close(); return downloaded; }
|
00
|
Code Sample 1:
public static Pedido insert(Pedido objPedido) { final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; int result; if (c == null) { return null; } try { c.setAutoCommit(false); String sql = ""; int idPedido; idPedido = PedidoDAO.getLastCodigo(); if (idPedido < 1) { return null; } sql = "insert into pedido " + "(id_pedido, id_funcionario,data_pedido,valor) " + "values(?,?,now(),truncate(?,2))"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, objPedido.getFuncionario().getCodigo()); pst.setString(3, new DecimalFormat("#0.00").format(objPedido.getValor())); result = pst.executeUpdate(); pst = null; if (result > 0) { Iterator<ItemPedido> itItemPedido = (objPedido.getItemPedido()).iterator(); while ((itItemPedido != null) && (itItemPedido.hasNext())) { ItemPedido objItemPedido = (ItemPedido) itItemPedido.next(); sql = ""; sql = "insert into item_pedido " + "(id_pedido,id_produto,quantidade,subtotal) " + "values (?,?,?,truncate(?,2))"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, (objItemPedido.getProduto()).getCodigo()); pst.setInt(3, objItemPedido.getQuantidade()); pst.setString(4, new DecimalFormat("#0.00").format(objItemPedido.getSubtotal())); result = pst.executeUpdate(); } } pst = null; sql = ""; sql = "insert into pedido_situacao " + "(id_pedido,id_situacao, em, observacao, id_funcionario) " + "values (?,?,now(), ?, ?)"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, 1); pst.setString(3, "Inclus�o de pedido"); pst.setInt(4, objPedido.getFuncionario().getCodigo()); result = pst.executeUpdate(); pst = null; sql = ""; sql = "insert into tramitacao " + "(data_tramitacao, id_pedido, id_dep_origem, id_dep_destino) " + "values (now(),?,?, ?)"; pst = c.prepareStatement(sql); pst.setInt(1, idPedido); pst.setInt(2, 6); pst.setInt(3, 2); result = pst.executeUpdate(); c.commit(); objPedido.setCodigo(idPedido); } catch (final Exception e) { try { c.rollback(); } catch (final Exception e1) { System.out.println("[PedidoDAO.insert] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[PedidoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } return objPedido; }
Code Sample 2:
public static void main(String[] args) throws Exception { dataList = new ArrayList<String>(); System.setProperty("http.agent", Phex.getFullPhexVendor()); URL url = new URL(listUrl); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); readData(inputStream); System.out.println("Total data read: " + dataList.size()); inputStream.close(); writeToOutputFile(); }
|
00
|
Code Sample 1:
private static boolean prepareQualifyingFile(String completePath, String outputFile) { try { File inFile = new File(completePath + fSep + "qualifying.txt"); FileChannel inC = new FileInputStream(inFile).getChannel(); BufferedReader br = new BufferedReader(new FileReader(inFile)); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + outputFile); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); boolean endOfFile = true; short movieName = 0; int customer = 0; while (endOfFile) { String line = br.readLine(); if (line != null) { if (line.indexOf(":") >= 0) { movieName = new Short(line.substring(0, line.length() - 1)).shortValue(); } else { customer = new Integer(line.substring(0, line.indexOf(","))).intValue(); ByteBuffer outBuf = ByteBuffer.allocate(6); outBuf.putShort(movieName); outBuf.putInt(customer); outBuf.flip(); outC.write(outBuf); } } else endOfFile = false; } br.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
Code Sample 2:
public void testFileSystem() throws IOException { Fragment f = Fragment.EMPTY; Fragment g = f.plus(System.getProperty("java.io.tmpdir")); Fragment h = f.plus("april", "1971", "data.txt"); Fragment i = f.plus(g, h); InOutLocation iol = locs.fs.plus(i); PrintStream ps = new PrintStream(iol.openOutput()); List<String> expected = new ArrayList<String>(); expected.add("So I am stepping out this old brown shoe"); expected.add("Maybe I'm in love with you"); for (String s : expected) ps.println(s); ps.close(); InLocation inRoot = locs.fs; List<String> lst = read(inRoot.plus(i).openInput()); assertEquals(expected, lst); URL url = iol.toUrl(); lst = read(url.openStream()); assertEquals(expected, lst); }
|
11
|
Code Sample 1:
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()); } }
Code Sample 2:
public void save() { final JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileFilter() { public String getDescription() { return "PDF File"; } public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf"); } }); if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return; } File targetFile = fc.getSelectedFile(); if (!targetFile.getName().toLowerCase().endsWith(".pdf")) { targetFile = new File(targetFile.getParentFile(), targetFile.getName() + ".pdf"); } if (targetFile.exists()) { if (JOptionPane.showConfirmDialog(this, "Do you want to overwrite the file?") != JOptionPane.YES_OPTION) { return; } } try { final InputStream is = new FileInputStream(filename); try { final OutputStream os = new FileOutputStream(targetFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); } } finally { os.close(); } } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public void delete(String remoteFile) { String remotePath = connector.getRemoteDirectory(); remotePath += PATH_SEPARATOR + remoteFile; FTPClient ftp = new FTPClient(); try { String hostname = connector.getUrl().getHost(); ftp.connect(hostname); log.info("Connected to " + hostname); log.info(ftp.getReplyString()); boolean loggedIn = ftp.login(connector.getUsername(), connector.getPassword()); if (loggedIn) { ftp.deleteFile(remotePath); ftp.logout(); } ftp.disconnect(); } catch (SocketException e) { log.error("File chmod failed with message: " + e.getMessage()); } catch (IOException e) { log.error("File chmod failed with message: " + e.getMessage()); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } }
Code Sample 2:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) dir.mkdir(); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
00
|
Code Sample 1:
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); } }
Code Sample 2:
public static byte[] loadFile(File file) throws IOException { BufferedInputStream in = null; ByteArrayOutputStream sink = null; try { in = new BufferedInputStream(new FileInputStream(file)); sink = new ByteArrayOutputStream(); IOUtils.copy(in, sink); return sink.toByteArray(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(sink); } }
|
00
|
Code Sample 1:
private void loadTrustAnchors(final String keystoreLocation) { LOG.debug("keystore location: " + keystoreLocation); try { if (keystoreLocation == null) { throw new NullPointerException("No TrustAnchor KeyStore name is set"); } InputStream keyStoreStream = null; if (new File(keystoreLocation).exists()) { keyStoreStream = new FileInputStream(keystoreLocation); } else if (new File("../trust1.keystore").exists()) { keyStoreStream = new FileInputStream(new File("../trust1.keystore")); } else if (new File("trust1.keystore").exists()) { keyStoreStream = new FileInputStream(new File("../trust1.keystore")); } else { URL url = Thread.currentThread().getContextClassLoader().getResource("trust1.keystore"); if (url != null) keyStoreStream = new BufferedInputStream(url.openStream()); } KeyStore ks = KeyStore.getInstance(trustStoreType); ks.load(keyStoreStream, trustStorePassword.toCharArray()); Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); LOG.debug("inspecting alias " + alias); if (ks.entryInstanceOf(alias, KeyStore.TrustedCertificateEntry.class)) { LOG.debug("Adding TrustAnchor: " + ((X509Certificate) ks.getCertificate(alias)).getSubjectX500Principal().getName()); TrustAnchor ta = new TrustAnchor((X509Certificate) (ks.getCertificate(alias)), null); this.trustAnchors.add(ta); } } } catch (Exception ex) { LOG.error("Error loading TrustAnchors", ex); this.trustAnchors = null; } }
Code Sample 2:
public void deploy(final File extension) { log.info("Deploying new extension from {}", extension.getPath()); RequestContextHolder.setRequestContext(new RequestContext(SZoneConfig.getDefaultZoneName(), SZoneConfig.getAdminUserName(SZoneConfig.getDefaultZoneName()), new BaseSessionContext())); RequestContextHolder.getRequestContext().resolve(); JarInputStream warIn; try { warIn = new JarInputStream(new FileInputStream(extension), true); } catch (IOException e) { log.warn("Unable to open extension WAR at " + extension.getPath(), e); return; } SAXReader reader = new SAXReader(false); reader.setIncludeExternalDTDDeclarations(false); String extensionPrefix = extension.getName().substring(0, extension.getName().lastIndexOf(".")); File extensionDir = new File(extensionBaseDir, extensionPrefix); extensionDir.mkdirs(); File extensionWebDir = new File(this.extensionWebDir, extensionPrefix); extensionWebDir.mkdirs(); try { for (JarEntry entry = warIn.getNextJarEntry(); entry != null; entry = warIn.getNextJarEntry()) { File inflated = new File(entry.getName().startsWith(infPrefix) ? extensionDir : extensionWebDir, entry.getName()); if (entry.isDirectory()) { log.debug("Creating directory at {}", inflated.getPath()); inflated.mkdirs(); continue; } inflated.getParentFile().mkdirs(); FileOutputStream entryOut = new FileOutputStream(inflated); if (!entry.getName().endsWith(configurationFileExtension)) { log.debug("Inflating file resource to {}", inflated.getPath()); IOUtils.copy(warIn, entryOut); entryOut.close(); continue; } try { final Document document = reader.read(new TeeInputStream(new CloseShieldInputStream(warIn), entryOut, true)); Attribute schema = document.getRootElement().attribute(schemaAttribute); if (schema == null || StringUtils.isBlank(schema.getText())) { log.debug("Inflating XML with unrecognized schema to {}", inflated.getPath()); continue; } if (schema.getText().contains(definitionsSchemaNamespace)) { log.debug("Inflating and registering definition from {}", inflated.getPath()); document.getRootElement().add(new AbstractAttribute() { private static final long serialVersionUID = -7880537136055718310L; public QName getQName() { return new QName(extensionAttr, document.getRootElement().getNamespace()); } public String getValue() { return extension.getName().substring(0, extension.getName().lastIndexOf(".")); } }); definitionModule.addDefinition(document, true); continue; } if (schema.getText().contains(templateSchemaNamespace)) { log.debug("Inflating and registering template from {}", inflated.getPath()); templateService.addTemplate(document, true, zoneModule.getDefaultZone()); continue; } } catch (DocumentException e) { log.warn("Malformed XML file in extension war at " + extension.getPath(), e); return; } } } catch (IOException e) { log.warn("Malformed extension war at " + extension.getPath(), e); return; } finally { try { warIn.close(); } catch (IOException e) { log.warn("Unable to close extension war at " + extension.getPath(), e); return; } RequestContextHolder.clear(); } log.info("Extension deployed successfully from {}", extension.getPath()); }
|
00
|
Code Sample 1:
public byte[] getXQueryForWorkflow(String workflowURI, Log4JLogger log) throws MalformedURLException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (workflowURI == null) { throw new XQGeneratorException("Null workflow URI"); } URL url = new URL(workflowURI); URLConnection urlconn = url.openConnection(); urlconn.setAllowUserInteraction(false); urlconn.setDoInput(true); urlconn.setDoOutput(false); urlconn.setUseCaches(true); urlconn.connect(); InputStream is = urlconn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); TavXQueryGenerator generator = (TavXQueryGenerator) Class.forName(generatorClass).newInstance(); generator.setLogger(log); generator.setInputStream(is); generator.setOutputStream(baos); generator.generateXQuery(); is.close(); return baos.toByteArray(); }
Code Sample 2:
public static void main(String args[]) { if (args.length < 1) { System.err.println("usage: java copyURL URL [LocalFile]"); System.exit(1); } try { URL url = new URL(args[0]); System.out.println("Opening connection to " + args[0] + "..."); URLConnection urlC = url.openConnection(); InputStream is = url.openStream(); System.out.print("Copying resource (type: " + urlC.getContentType()); Date date = new Date(urlC.getLastModified()); System.out.flush(); FileOutputStream fos = null; if (args.length < 2) { String localFile = null; StringTokenizer st = new StringTokenizer(url.getFile(), "/"); while (st.hasMoreTokens()) localFile = st.nextToken(); fos = new FileOutputStream(localFile); } else fos = new FileOutputStream(args[1]); int oneChar, count = 0; while ((oneChar = is.read()) != -1) { fos.write(oneChar); count++; } is.close(); fos.close(); System.out.println(count + " byte(s) copied"); } catch (MalformedURLException e) { System.err.println(e.toString()); } catch (IOException e) { System.err.println(e.toString()); } }
|
00
|
Code Sample 1:
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(targetPath + filename)); IOUtils.copy(is, fos); response.setStatus(HttpServletResponse.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
Code Sample 2:
private void gerarComissao() { int opt = Funcoes.mensagemConfirma(null, "Confirma gerar comiss�es para o vendedor " + txtNomeVend.getVlrString().trim() + "?"); if (opt == JOptionPane.OK_OPTION) { StringBuilder insert = new StringBuilder(); insert.append("INSERT INTO RPCOMISSAO "); insert.append("(CODEMP, CODFILIAL, CODPED, CODITPED, "); insert.append("CODEMPVD, CODFILIALVD, CODVEND, VLRCOMISS ) "); insert.append("VALUES "); insert.append("(?,?,?,?,?,?,?,?)"); PreparedStatement ps; int parameterIndex; boolean gerou = false; try { for (int i = 0; i < tab.getNumLinhas(); i++) { if (((BigDecimal) tab.getValor(i, 8)).floatValue() > 0) { parameterIndex = 1; ps = con.prepareStatement(insert.toString()); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPCOMISSAO")); ps.setInt(parameterIndex++, txtCodPed.getVlrInteger()); ps.setInt(parameterIndex++, (Integer) tab.getValor(i, ETabNota.ITEM.ordinal())); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPVENDEDOR")); ps.setInt(parameterIndex++, txtCodVend.getVlrInteger()); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRCOMIS.ordinal())); ps.executeUpdate(); gerou = true; } } if (gerou) { Funcoes.mensagemInforma(null, "Comiss�o gerada para " + txtNomeVend.getVlrString().trim()); txtCodPed.setText("0"); lcPedido.carregaDados(); carregaTabela(); con.commit(); } else { Funcoes.mensagemInforma(null, "N�o foi possiv�l gerar comiss�o!\nVerifique os valores das comiss�es dos itens."); } } catch (Exception e) { e.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao gerar comiss�o!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } }
|
11
|
Code Sample 1:
@Override public JSONObject runCommand(JSONObject payload, HttpSession session) throws DefinedException { String sessionId = session.getId(); log.debug("Login -> runCommand SID: " + sessionId); JSONObject toReturn = new JSONObject(); boolean isOK = true; String username = null; try { username = payload.getString(ComConstants.LogIn.Request.USERNAME); } catch (JSONException e) { log.error("SessionId=" + sessionId + ", Missing username parameter", e); throw new DefinedException(StatusCodesV2.PARAMETER_ERROR); } String password = null; if (isOK) { try { password = payload.getString(ComConstants.LogIn.Request.PASSWORD); } catch (JSONException e) { log.error("SessionId=" + sessionId + ", Missing password parameter", e); throw new DefinedException(StatusCodesV2.PARAMETER_ERROR); } } if (isOK) { MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("SessionId=" + sessionId + ", MD5 algorithm does not exist", e); e.printStackTrace(); throw new DefinedException(StatusCodesV2.INTERNAL_SYSTEM_FAILURE); } m.update(password.getBytes(), 0, password.length()); password = new BigInteger(1, m.digest()).toString(16); UserSession userSession = pli.login(username, password); try { if (userSession != null) { session.setAttribute("user", userSession); toReturn.put(ComConstants.Response.STATUS_CODE, StatusCodesV2.LOGIN_OK.getStatusCode()); toReturn.put(ComConstants.Response.STATUS_MESSAGE, StatusCodesV2.LOGIN_OK.getStatusMessage()); } else { log.error("SessionId=" + sessionId + ", Login failed: username=" + username + " not found"); toReturn.put(ComConstants.Response.STATUS_CODE, StatusCodesV2.LOGIN_USER_OR_PASSWORD_INCORRECT.getStatusCode()); toReturn.put(ComConstants.Response.STATUS_MESSAGE, StatusCodesV2.LOGIN_USER_OR_PASSWORD_INCORRECT.getStatusMessage()); } } catch (JSONException e) { log.error("SessionId=" + sessionId + ", JSON exception occured in response", e); e.printStackTrace(); throw new DefinedException(StatusCodesV2.INTERNAL_SYSTEM_FAILURE); } } log.debug("Login <- runCommand SID: " + sessionId); return toReturn; }
Code Sample 2:
static void invalidSlave(String msg, Socket sock) throws IOException { BufferedReader _sinp = null; PrintWriter _sout = null; try { _sout = new PrintWriter(sock.getOutputStream(), true); _sinp = new BufferedReader(new InputStreamReader(sock.getInputStream())); _sout.println(msg); logger.info("NEW< " + msg); String txt = AsyncSlaveListener.readLine(_sinp, 30); String sname = ""; String spass = ""; String shash = ""; try { String[] items = txt.split(" "); sname = items[1].trim(); spass = items[2].trim(); shash = items[3].trim(); } catch (Exception e) { throw new IOException("Slave Inititalization Faailed"); } String pass = sname + spass + _pass; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(pass.getBytes()); String hash = AsyncSlaveListener.hash2hex(md5.digest()).toLowerCase(); if (!hash.equals(shash)) { throw new IOException("Slave Inititalization Faailed"); } } catch (Exception e) { } throw new IOException("Slave Inititalization Faailed"); }
|
11
|
Code Sample 1:
public String downloadToSdCard(String localFileName, String suffixFromHeader, String extension) { InputStream in = null; FileOutputStream fos = null; String absolutePath = null; try { Log.i(TAG, "Opening URL: " + url); StreamAndHeader inAndHeader = HTTPUtils.openWithHeader(url, suffixFromHeader); if (inAndHeader == null || inAndHeader.mStream == null) { return null; } in = inAndHeader.mStream; String sdcardpath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); String headerValue = suffixFromHeader == null || inAndHeader.mHeaderValue == null ? "" : inAndHeader.mHeaderValue; headerValue = headerValue.replaceAll("[-:]*\\s*", ""); String filename = sdcardpath + "/" + localFileName + headerValue + (extension == null ? "" : extension); mSize = in.available(); Log.i(TAG, "Downloading " + filename + ", size: " + mSize); fos = new FileOutputStream(new File(filename)); int buffersize = 1024; byte[] buffer = new byte[buffersize]; int readsize = buffersize; mCount = 0; while (readsize != -1) { readsize = in.read(buffer, 0, buffersize); if (readsize > 0) { Log.i(TAG, "Read " + readsize + " bytes..."); fos.write(buffer, 0, readsize); mCount += readsize; } } fos.flush(); fos.close(); FileInputStream controlIn = new FileInputStream(filename); mSavedSize = controlIn.available(); Log.v(TAG, "saved size: " + mSavedSize); mAbsolutePath = filename; done(); } catch (Exception e) { Log.e(TAG, "LoadingWorker.run", e); } finally { HTTPUtils.close(in); } return mAbsolutePath; }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public boolean connect() { if (connectStatus > -1) return (connectStatus == 1); connectStatus = 0; try { URL url = new URL(getURL()); m_connection = (HttpURLConnection) url.openConnection(); m_connection.connect(); processHeaders(); m_inputStream = m_connection.getInputStream(); } catch (MalformedURLException e) { newError("connect failed", e, true); } catch (IOException e) { newError("connect failed", e, true); } return (connectStatus == 1); }
Code Sample 2:
public BufferedImage processUsingTemp(InputStream input, DjatokaDecodeParam params) throws DjatokaException { File in; try { in = File.createTempFile("tmp", ".jp2"); FileOutputStream fos = new FileOutputStream(in); in.deleteOnExit(); IOUtils.copyStream(input, fos); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } BufferedImage bi = process(in.getAbsolutePath(), params); if (in != null) in.delete(); return bi; }
|
11
|
Code Sample 1:
public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } }
Code Sample 2:
static void reopen(MJIEnv env, int objref) throws IOException { int fd = env.getIntField(objref, "fd"); long off = env.getLongField(objref, "off"); if (content.get(fd) == null) { int mode = env.getIntField(objref, "mode"); int fnRef = env.getReferenceField(objref, "fileName"); String fname = env.getStringObject(fnRef); if (mode == FD_READ) { FileInputStream fis = new FileInputStream(fname); FileChannel fc = fis.getChannel(); fc.position(off); content.set(fd, fis); } else if (mode == FD_WRITE) { FileOutputStream fos = new FileOutputStream(fname); FileChannel fc = fos.getChannel(); fc.position(off); content.set(fd, fos); } else { env.throwException("java.io.IOException", "illegal mode: " + mode); } } }
|
00
|
Code Sample 1:
public static void main(String[] args) { try { String default_uri = "http://www.cs.nmsu.edu/~bchisham/cgi-bin/phylows/tree/Tree3099?format=graphml"; URL gurl = new URL(default_uri); InputStream is = gurl.openStream(); Scanner iscan = new Scanner(is); while (iscan.hasNext()) { System.out.println(iscan.next()); } } catch (MalformedURLException ex) { Logger.getLogger(GraphUrlLoader.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { } }
Code Sample 2:
public static void copyFile(final File source, final File target) throws FileNotFoundException, IOException { FileChannel in = new FileInputStream(source).getChannel(), out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } out.close(); in.close(); }
|
11
|
Code Sample 1:
public int addRecipe(Recipe recipe) throws Exception { PreparedStatement pst1 = null; PreparedStatement pst2 = null; ResultSet rs = null; int retVal = -1; try { conn = getConnection(); pst1 = conn.prepareStatement("INSERT INTO recipes (name, instructions, category_id) VALUES (?, ?, ?)"); pst1.setString(1, recipe.getName()); pst1.setString(2, recipe.getInstructions()); pst1.setInt(3, recipe.getCategoryId()); if (pst1.executeUpdate() > 0) { pst2 = conn.prepareStatement("SELECT recipe_id FROM recipes WHERE name = ? AND instructions = ? AND category_id = ?"); pst2.setString(1, recipe.getName()); pst2.setString(2, recipe.getInstructions()); pst2.setInt(3, recipe.getCategoryId()); rs = pst2.executeQuery(); conn.commit(); if (rs.next()) { int id = rs.getInt(1); addIngredients(recipe, id); MainFrame.recipePanel.update(); retVal = id; } else { retVal = -1; } } else { retVal = -1; } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add recipe, the exception was " + e.getMessage()); } finally { try { if (rs != null) rs.close(); rs = null; if (pst1 != null) pst1.close(); pst1 = null; if (pst2 != null) pst2.close(); pst2 = null; } catch (SQLException sqle) { MainFrame.appendStatusText("Can't close database connection."); } } return retVal; }
Code Sample 2:
protected Object insertSingle(Object name, Object fact) throws SQLException { DFAgentDescription dfd = (DFAgentDescription) fact; AID agentAID = dfd.getName(); String agentName = agentAID.getName(); DFAgentDescription dfdToReturn = null; String batchErrMsg = ""; Connection conn = getConnectionWrapper().getConnection(); PreparedStatements pss = getPreparedStatements(); try { dfdToReturn = (DFAgentDescription) removeSingle(dfd.getName()); Date leaseTime = dfd.getLeaseTime(); long lt = (leaseTime != null ? leaseTime.getTime() : -1); String descrId = getGUID(); pss.stm_insAgentDescr.setString(1, descrId); pss.stm_insAgentDescr.setString(2, agentName); pss.stm_insAgentDescr.setString(3, String.valueOf(lt)); pss.stm_insAgentDescr.executeUpdate(); saveAID(agentAID); Iterator iter = dfd.getAllLanguages(); if (iter.hasNext()) { pss.stm_insLanguage.clearBatch(); while (iter.hasNext()) { pss.stm_insLanguage.setString(1, descrId); pss.stm_insLanguage.setString(2, (String) iter.next()); pss.stm_insLanguage.addBatch(); } pss.stm_insLanguage.executeBatch(); } iter = dfd.getAllOntologies(); if (iter.hasNext()) { pss.stm_insOntology.clearBatch(); while (iter.hasNext()) { pss.stm_insOntology.setString(1, descrId); pss.stm_insOntology.setString(2, (String) iter.next()); pss.stm_insOntology.addBatch(); } pss.stm_insOntology.executeBatch(); } iter = dfd.getAllProtocols(); if (iter.hasNext()) { pss.stm_insProtocol.clearBatch(); while (iter.hasNext()) { pss.stm_insProtocol.setString(1, descrId); pss.stm_insProtocol.setString(2, (String) iter.next()); pss.stm_insProtocol.addBatch(); } pss.stm_insProtocol.executeBatch(); } saveServices(descrId, dfd.getAllServices()); regsCnt++; if (regsCnt > MAX_REGISTER_WITHOUT_CLEAN) { regsCnt = 0; clean(); } conn.commit(); } catch (SQLException sqle) { try { conn.rollback(); } catch (SQLException se) { logger.log(Logger.SEVERE, "Rollback for incomplete insertion of DFD for agent " + dfd.getName() + " failed.", se); } throw sqle; } return dfdToReturn; }
|
00
|
Code Sample 1:
public boolean refreshRequired() { boolean status = false; Set<String> urls = lastModifiedDates.keySet(); try { for (String urlPath : urls) { Long lastModifiedDate = lastModifiedDates.get(urlPath); URL url = new URL(urlPath); URLConnection connection = url.openConnection(); connection.connect(); long newModDate = connection.getLastModified(); if (newModDate != lastModifiedDate) { status = true; break; } } } catch (Exception e) { LOG.warn("Exception while monitoring update times.", e); return true; } return status; }
Code Sample 2:
public static Shader loadShader(String vspath, String fspath, int textureUnits, boolean separateCam, boolean fog) throws ShaderProgramProcessException { if (vspath == "" || fspath == "") return null; BufferedReader in; String vert = "", frag = ""; try { URL v_url = Graphics.class.getClass().getResource("/eu/cherrytree/paj/graphics/shaders/" + vspath); String v_path = AppDefinition.getDefaultDataPackagePath() + "/shaders/" + vspath; if (v_url != null) in = new BufferedReader(new InputStreamReader(v_url.openStream())); else in = new BufferedReader(new InputStreamReader(new FileReader(v_path).getInputStream())); boolean run = true; String str; while (run) { str = in.readLine(); if (str != null) vert += str + "\n"; else run = false; } in.close(); } catch (Exception e) { System.err.println("Couldn't read in vertex shader \"" + vspath + "\"."); throw new ShaderNotLoadedException(vspath, fspath); } try { URL f_url = Graphics.class.getClass().getResource("/eu/cherrytree/paj/graphics/shaders/" + fspath); String f_path = AppDefinition.getDefaultDataPackagePath() + "/shaders/" + fspath; if (f_url != null) in = new BufferedReader(new InputStreamReader(f_url.openStream())); else in = new BufferedReader(new InputStreamReader(new FileReader(f_path).getInputStream())); boolean run = true; String str; while (run) { str = in.readLine(); if (str != null) frag += str + "\n"; else run = false; } in.close(); } catch (Exception e) { System.err.println("Couldn't read in fragment shader \"" + fspath + "\"."); throw new ShaderNotLoadedException(vspath, fspath); } return loadShaderFromSource(vert, frag, textureUnits, separateCam, fog); }
|
00
|
Code Sample 1:
public RobotList<Location> sort_decr_Location(RobotList<Location> list, String field) { int length = list.size(); Index_value[] enemy_dist = new Index_value[length]; if (field.equals("") || field.equals("location")) { Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, distance(cur_loc, list.get(i))); } } else if (field.equals("x")) { for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, list.get(i).x); } } else if (field.equals("y")) { for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, list.get(i).y); } } else { say("impossible to sort list - nothing modified"); return list; } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (enemy_dist[i].value < enemy_dist[i + 1].value) { Index_value a = enemy_dist[i]; enemy_dist[i] = enemy_dist[i + 1]; enemy_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Location> new_location_list = new RobotList<Location>(Location.class); for (int i = 0; i < length; i++) { new_location_list.addLast(list.get(enemy_dist[i].index)); } return new_location_list; }
Code Sample 2:
public void removerQuestaoMultiplaEscolha(QuestaoMultiplaEscolha multiplaEscolha) throws ClassNotFoundException, SQLException { this.criaConexao(false); String sql = "DELETE FROM \"Disciplina\" " + " WHERE ID_Disciplina = ? )"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.executeUpdate(); connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } }
|
11
|
Code Sample 1:
private Face(String font) throws IOException { characterWidths = new double[256]; StringBuffer sb = new StringBuffer(); sb.append('/'); sb.append(Constants.FONTS_DIR); sb.append('/'); sb.append(font); sb.append(Constants.CHAR_WIDTHS_SUFFIX); String path = sb.toString(); URL url = getClass().getResource(path); InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); int pos = 0; String width = br.readLine(); while (width != null && pos < 256) { characterWidths[pos] = Double.parseDouble(width); pos++; width = br.readLine(); } }
Code Sample 2:
private String getLatestVersion(URL url) throws IOException { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream(con.getInputStream()))); String lines = ""; String line = null; while ((line = br.readLine()) != null) { lines += line; } con.disconnect(); return lines; }
|
11
|
Code Sample 1:
private String[] verifyConnection(Socket clientConnection) throws Exception { List<String> requestLines = new ArrayList<String>(); InputStream is = clientConnection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringTokenizer st = new StringTokenizer(in.readLine()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no method token in this connection"); } String method = st.nextToken(); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no URI token in this connection"); } String uri = decodePercent(st.nextToken()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no version token in this connection"); } String version = st.nextToken(); Properties parms = new Properties(); int qmi = uri.indexOf('?'); if (qmi >= 0) { decodeParms(uri.substring(qmi + 1), parms); uri = decodePercent(uri.substring(0, qmi)); } String params = ""; if (parms.size() > 0) { params = "?"; for (Object key : parms.keySet()) { params = params + key + "=" + parms.getProperty(((String) key)) + "&"; } params = params.substring(0, params.length() - 1).replace(" ", "%20"); } logger.debug("HTTP Request: " + method + " " + uri + params + " " + version); requestLines.add(method + " " + uri + params + " " + version); Properties headerVars = new Properties(); String line; String currentBoundary = null; Stack<String> boundaryStack = new Stack<String>(); boolean readingBoundary = false; String additionalData = ""; while (in.ready() && (line = in.readLine()) != null) { if (line.equals("") && (headerVars.get("Content-Type") == null || headerVars.get("Content-Length") == null)) { break; } logger.debug("HTTP Request Header: " + line); if (line.contains(": ")) { String vals[] = line.split(": "); headerVars.put(vals[0].trim(), vals[1].trim()); } if (!readingBoundary && line.contains(": ")) { if (line.contains("boundary=")) { currentBoundary = line.split("boundary=")[1].trim(); boundaryStack.push("--" + currentBoundary); } continue; } else if (line.equals("") && boundaryStack.isEmpty()) { int val = Integer.parseInt((String) headerVars.get("Content-Length")); if (headerVars.getProperty("Content-Type").contains("x-www-form-urlencoded")) { char buf[] = new char[val]; int read = in.read(buf); line = String.valueOf(buf, 0, read); additionalData = line; logger.debug("HTTP Request Header Form Parameters: " + line); } } else if (line.equals(boundaryStack.peek()) && !readingBoundary) { readingBoundary = true; } else if (line.equals(boundaryStack.peek()) && readingBoundary) { readingBoundary = false; } else if (line.contains(": ") && readingBoundary) { if (method.equalsIgnoreCase("PUT")) { if (line.contains("form-data; ")) { String formValues = line.split("form-data; ")[1]; for (String varValue : formValues.replace("\"", "").split("; ")) { String[] vV = varValue.split("="); vV[0] = decodePercent(vV[0]); vV[1] = decodePercent(vV[1]); headerVars.put(vV[0], vV[1]); } } } } else if (line.contains("") && readingBoundary && !boundaryStack.isEmpty() && headerVars.get("filename") != null) { int length = Integer.parseInt(headerVars.getProperty("Content-Length")); if (headerVars.getProperty("Content-Transfer-Encoding").contains("binary")) { File uploadFilePath = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory")); if (!uploadFilePath.exists()) { logger.error("Temporaty dir does not exist: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.isDirectory()) { logger.error("Temporary dir is not a directory: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.canWrite()) { logger.error("VOctopus Webserver doesn't have permissions to write on temporary dir: " + uploadFilePath.getCanonicalPath()); } FileOutputStream out = null; try { String putUploadPath = uploadFilePath.getAbsolutePath() + "/" + headerVars.getProperty("filename"); out = new FileOutputStream(putUploadPath); OutputStream outf = new BufferedOutputStream(out); int c; while (in.ready() && (c = in.read()) != -1 && length-- > 0) { outf.write(c); } } finally { if (out != null) { out.close(); } } File copied = new File(VOctopusConfigurationManager.getInstance().getDocumentRootPath() + uri + headerVars.get("filename")); File tempFile = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory") + "/" + headerVars.get("filename")); FileChannel ic = new FileInputStream(tempFile.getAbsolutePath()).getChannel(); FileChannel oc = new FileOutputStream(copied.getAbsolutePath()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } } } for (Object var : headerVars.keySet()) { requestLines.add(var + ": " + headerVars.get(var)); } if (!additionalData.equals("")) { requestLines.add("ADDITIONAL" + additionalData); } return requestLines.toArray(new String[requestLines.size()]); }
Code Sample 2:
private void copy(File source, File destination) throws PackageException { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(destination); byte[] buff = new byte[1024]; int len; while ((len = in.read(buff)) > 0) out.write(buff, 0, len); in.close(); out.close(); } catch (IOException e) { throw new PackageException("Unable to copy " + source.getPath() + " to " + destination.getPath() + " :: " + e.toString()); } }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void decompress(final File file, final File folder, final boolean deleteZipAfter) throws IOException { final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(file.getCanonicalFile()))); ZipEntry ze; try { while (null != (ze = zis.getNextEntry())) { final File f = new File(folder.getCanonicalPath(), ze.getName()); if (f.exists()) f.delete(); if (ze.isDirectory()) { f.mkdirs(); continue; } f.getParentFile().mkdirs(); final OutputStream fos = new BufferedOutputStream(new FileOutputStream(f)); try { try { final byte[] buf = new byte[8192]; int bytesRead; while (-1 != (bytesRead = zis.read(buf))) fos.write(buf, 0, bytesRead); } finally { fos.close(); } } catch (final IOException ioe) { f.delete(); throw ioe; } } } finally { zis.close(); } if (deleteZipAfter) file.delete(); }
|
00
|
Code Sample 1:
private void downloadPage(final URL url, final File file) { try { long size = 0; final byte[] buffer = new byte[BotUtil.BUFFER_SIZE]; final File tempFile = new File(file.getParentFile(), "temp.tmp"); int length; int lastUpdate = 0; FileOutputStream fos = new FileOutputStream(tempFile); final InputStream is = url.openStream(); do { length = is.read(buffer); if (length >= 0) { fos.write(buffer, 0, length); size += length; } if (lastUpdate > UPDATE_TIME) { report(0, (int) (size / Format.MEMORY_MEG), "Downloading... " + Format.formatMemory(size)); lastUpdate = 0; } lastUpdate++; } while (length >= 0); fos.close(); if (url.toString().toLowerCase().endsWith(".gz")) { final FileInputStream fis = new FileInputStream(tempFile); final GZIPInputStream gis = new GZIPInputStream(fis); fos = new FileOutputStream(file); size = 0; lastUpdate = 0; do { length = gis.read(buffer); if (length >= 0) { fos.write(buffer, 0, length); size += length; } if (lastUpdate > UPDATE_TIME) { report(0, (int) (size / Format.MEMORY_MEG), "Uncompressing... " + Format.formatMemory(size)); lastUpdate = 0; } lastUpdate++; } while (length >= 0); fos.close(); fis.close(); gis.close(); tempFile.delete(); } else { file.delete(); tempFile.renameTo(file); } } catch (final IOException e) { throw new AnalystError(e); } }
Code Sample 2:
public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private static void copyFile(File sourceFile, File destFile) { try { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } catch (Exception e) { throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
public static boolean insert(final Cargo cargo) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into cargo (nome) values (?)"; pst = c.prepareStatement(sql); pst.setString(1, cargo.getNome()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[CargoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public static String convertToSha1(final 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); }
Code Sample 2:
private static String createBoundary(int number) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } digest.update(String.valueOf(Math.random()).getBytes()); digest.update(String.valueOf(System.currentTimeMillis()).getBytes()); digest.update(String.valueOf(digest.hashCode()).getBytes()); byte[] bytes = digest.digest(); String paddedNumber = Integer.toString(number); paddedNumber = ("0000000000".substring(0, 10 - paddedNumber.length()) + paddedNumber); StringBuffer buffer = new StringBuffer(); buffer.append("---------------------------------=__"); for (int i = 0; i < 8; i++) { String hex = Integer.toHexString((bytes[i] & 0xff) + 0x100).substring(1); buffer.append(hex); } buffer.append('_'); buffer.append(paddedNumber); return buffer.toString(); }
|
00
|
Code Sample 1:
public String getMessageofTheDay(String id) { StringBuffer mod = new StringBuffer(); int serverModId = 0; int clientModId = 0; BufferedReader input = null; try { URL url = new URL(FlyShareApp.BASE_WEBSITE_URL + "/mod.txt"); input = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; inputLine = input.readLine(); try { clientModId = Integer.parseInt(id); serverModId = Integer.parseInt(inputLine); } catch (NumberFormatException e) { } if (clientModId < serverModId || clientModId == 0) { mod.append(serverModId); mod.append('|'); while ((inputLine = input.readLine()) != null) mod.append(inputLine); } } catch (MalformedURLException e) { } catch (IOException e) { } finally { try { input.close(); } catch (Exception e) { } } return mod.toString(); }
Code Sample 2:
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) { } } } }
|
00
|
Code Sample 1:
public void postProcess() throws StopWriterVisitorException { dxfWriter.postProcess(); try { FileChannel fcinDxf = new FileInputStream(fTemp).getChannel(); FileChannel fcoutDxf = new FileOutputStream(m_Fich).getChannel(); DriverUtilities.copy(fcinDxf, fcoutDxf); fTemp.delete(); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } }
Code Sample 2:
public String sendSMS(String destinationNumber, String txt, String id) throws IOException { String out = ""; String smsdata = ""; smsdata += URLEncoder.encode("id", enc) + "=" + URLEncoder.encode(id, enc); smsdata += "&" + URLEncoder.encode("phoneNumber", enc) + "=" + URLEncoder.encode(destinationNumber, enc); smsdata += "&" + URLEncoder.encode("conversationId", enc) + "=" + URLEncoder.encode(id, enc); smsdata += "&" + URLEncoder.encode("text", enc) + "=" + URLEncoder.encode(txt, enc); smsdata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc); System.out.println("smsdata: " + smsdata); URL smsurl = new URL("https://www.google.com/voice/b/0/sms/send/"); URLConnection smsconn = smsurl.openConnection(); smsconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); smsconn.setRequestProperty("User-agent", USER_AGENT); smsconn.setDoOutput(true); OutputStreamWriter callwr = new OutputStreamWriter(smsconn.getOutputStream()); callwr.write(smsdata); callwr.flush(); BufferedReader callrd = new BufferedReader(new InputStreamReader(smsconn.getInputStream())); String line; while ((line = callrd.readLine()) != null) { out += line + "\n\r"; } callwr.close(); callrd.close(); if (out.equals("")) { throw new IOException("No Response Data Received."); } return out; }
|
11
|
Code Sample 1:
private void btnOkActionPerformed(java.awt.event.ActionEvent evt) { try { int id = 0; String sql = "SELECT MAX(ID) as MAX_ID from CORE_USER_GROUPS"; PreparedStatement pStmt = Database.getMyConnection().prepareStatement(sql); ResultSet rs = pStmt.executeQuery(); if (rs.next()) { id = rs.getInt("MAX_ID") + 1; } else { id = 1; } Database.close(pStmt); sql = "INSERT INTO CORE_USER_GROUPS" + " (ID, GRP_NAME, GRP_DESC, DATE_INITIAL, DATE_FINAL, IND_STATUS)" + " VALUES (?, ?, ?, ?, ?, ?)"; pStmt = Database.getMyConnection().prepareStatement(sql); pStmt.setInt(1, id); pStmt.setString(2, txtGrpName.getText()); pStmt.setString(3, txtGrpDesc.getText()); pStmt.setDate(4, Utils.getTodaySql()); pStmt.setDate(5, Date.valueOf("9999-12-31")); pStmt.setString(6, "A"); pStmt.executeUpdate(); Database.getMyConnection().commit(); Database.close(pStmt); MessageBox.ok("New group added successfully", this); rs = getGroups(); tblGroups.setModel(new GroupsTableModel(rs)); Database.close(rs); } catch (SQLException e) { log.error("Failed with update operation \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } catch (IllegalArgumentException e) { log.error("Illegal argument for the DATE_FINAL \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } finally { txtGrpName.setEnabled(false); txtGrpDesc.setEnabled(false); btnOk.setEnabled(false); btnCancel.requestFocus(); } }
Code Sample 2:
public int deleteFile(Integer[] fileID) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; Connection conn = null; int nbrow = 0; try { DataSource ds = getDataSource(DEFAULT_DATASOURCE); conn = ds.getConnection(); conn.setAutoCommit(false); if (log.isDebugEnabled()) { log.debug("FileDAOImpl.deleteFile() " + DELETE_FILES_LOGIC); } for (int i = 0; i < fileID.length; i++) { pstmt = conn.prepareStatement(DELETE_FILES_LOGIC); pstmt.setInt(1, fileID[i].intValue()); nbrow = pstmt.executeUpdate(); } } catch (SQLException e) { conn.rollback(); log.error("FileDAOImpl.deleteFile() : erreur technique", e); throw e; } finally { conn.commit(); closeRessources(conn, pstmt, rs); } return nbrow; }
|
00
|
Code Sample 1:
public static synchronized void repartition(File[] sourceFiles, File targetDirectory, String prefix, long maxUnitBases, long maxUnitEntries) throws Exception { if (!targetDirectory.exists()) { if (!targetDirectory.mkdirs()) throw new Exception("Could not create directory " + targetDirectory.getAbsolutePath()); } File tmpFile = new File(targetDirectory, "tmp.fasta"); FileOutputStream fos = new FileOutputStream(tmpFile); FileChannel fco = fos.getChannel(); for (File file : sourceFiles) { FileInputStream fis = new FileInputStream(file); FileChannel fci = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(64000); while (fci.read(buffer) > 0) { buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); } fco.close(); FastaFile fastaFile = new FastaFile(tmpFile); fastaFile.split(targetDirectory, prefix, maxUnitBases, maxUnitEntries); tmpFile.delete(); }
Code Sample 2:
public static Properties load(URL url) { if (url == null) { return new Properties(); } InputStream in = null; try { in = url.openStream(); Properties ret = new Properties(); ret.load(in); return ret; } catch (IOException e) { throw new RuntimeException(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error("Error closing", e); } } } }
|
00
|
Code Sample 1:
public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); }
Code Sample 2:
public static String hash(String str) { MessageDigest summer; try { summer = MessageDigest.getInstance("md5"); summer.update(str.getBytes()); } catch (NoSuchAlgorithmException ex) { return null; } BigInteger hash = new BigInteger(1, summer.digest()); String hashword = hash.toString(16); return hashword; }
|
11
|
Code Sample 1:
public void run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); List<String> parts = header.getFilename().getSegments(); String filename; if (parts.size() > 0) filename = "dl-" + parts.get(parts.size() - 1); else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } }
Code Sample 2:
private void copyFile(File orig, File dest) { byte[] buffer = new byte[1024]; try { FileInputStream fis = new FileInputStream(orig); FileOutputStream fos = new FileOutputStream(dest, true); int readBytes = 0; do { readBytes = fis.read(buffer); if (readBytes > 0) fos.write(buffer, 0, readBytes); } while (readBytes > 0); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public void copyFile(String from, String to) throws IOException { FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
public static boolean copyFile(String src, String dst) { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(new File(src)).getChannel(); outChannel = new FileOutputStream(new File(dst)).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (FileNotFoundException e) { e.printStackTrace(); MessageGenerator.briefError("ERROR could not find/access file(s): " + src + " and/or " + dst); return false; } catch (IOException e) { MessageGenerator.briefError("ERROR copying file: " + src + " to " + dst); return false; } finally { try { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } catch (IOException e) { MessageGenerator.briefError("Error closing files involved in copying: " + src + " and " + dst); return false; } } return true; }
|
11
|
Code Sample 1:
public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) return; FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public void createZipCopy(IUIContext ui, final String zipFileName, final File[] filesToZip, final FilenameFilter fileFilter, Timestamp timestamp) { TestCase.assertNotNull(ui); TestCase.assertNotNull(zipFileName); TestCase.assertFalse(zipFileName.trim().length() == 0); TestCase.assertNotNull(filesToZip); TestCase.assertNotNull(timestamp); String nameCopy = zipFileName; if (nameCopy.endsWith(".zip")) { nameCopy = nameCopy.substring(0, zipFileName.length() - 4); } nameCopy = nameCopy + "_" + timestamp.toString() + ".zip"; final String finalZip = nameCopy; IWorkspaceRunnable noResourceChangedEventsRunner = new IWorkspaceRunnable() { public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } } }; try { IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.run(noResourceChangedEventsRunner, workspace.getRoot(), IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); } catch (CoreException ce) { PlatformActivator.logException(ce); } }
|
11
|
Code Sample 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(); } }
Code Sample 2:
public void run() { Vector<Update> updates = new Vector<Update>(); if (dic != null) updates.add(dic); if (gen != null) updates.add(gen); if (res != null) updates.add(res); if (help != null) updates.add(help); for (Iterator iterator = updates.iterator(); iterator.hasNext(); ) { Update update = (Update) iterator.next(); try { File temp = File.createTempFile("fm_" + update.getType(), ".jar"); temp.deleteOnExit(); FileOutputStream out = new FileOutputStream(temp); URL url = new URL(update.getAction()); URLConnection conn = url.openConnection(); com.diccionarioderimas.Utils.setupProxy(conn); InputStream in = conn.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; int total = 0; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); total += read; if (total > 10000) { progressBar.setValue(progressBar.getValue() + total); total = 0; } } out.close(); in.close(); String fileTo = basePath + "diccionariorimas.jar"; if (update.getType() == Update.GENERATOR) fileTo = basePath + "generador.jar"; else if (update.getType() == Update.RESBC) fileTo = basePath + "resbc.me"; else if (update.getType() == Update.HELP) fileTo = basePath + "help.html"; if (update.getType() == Update.RESBC) { Utils.unzip(temp, new File(fileTo)); } else { Utils.copyFile(new FileInputStream(temp), new File(fileTo)); } } catch (Exception e) { e.printStackTrace(); } } setVisible(false); if (gen != null || res != null) { try { new Main(null, basePath, false); } catch (Exception e) { new ErrorDialog(frame, e); } } String restart = ""; if (dic != null) restart += "\nAlgunas de ellas s�lo estar�n disponibles despu�s de reiniciar el diccionario."; JOptionPane.showMessageDialog(frame, "Se han terminado de realizar las actualizaciones." + restart, "Actualizaciones", JOptionPane.INFORMATION_MESSAGE); }
|
11
|
Code Sample 1:
private void appendAndDelete(FileOutputStream outstream, String file) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(file); byte[] buffer = new byte[65536]; int l; while ((l = input.read(buffer)) != -1) outstream.write(buffer, 0, l); input.close(); new File(file).delete(); }
Code Sample 2:
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(); } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); String text = "YUMyfj"; md.update(text.getBytes(), 0, text.length()); System.out.println(new BigInteger(1, md.digest()).toString(16).toString()); }
Code Sample 2:
@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]; } }
|
11
|
Code Sample 1:
public String getValidationKey(String transactionId, double transactionAmount) { try { java.security.MessageDigest d = java.security.MessageDigest.getInstance("MD5"); d.reset(); String value = this.getPostingKey() + transactionId + transactionAmount; d.update(value.getBytes()); byte[] buf = d.digest(); return Base64.encodeBytes(buf); } catch (java.security.NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
Code Sample 2:
public static String encrypt(String password) { String sign = password; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(sign.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])); } sign = hexString.toString(); } catch (Exception nsae) { nsae.printStackTrace(); } return sign; }
|
00
|
Code Sample 1:
public void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileOutputStream lfosTargetFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfosTargetFile = new FileOutputStream(mstrTargetDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrSourceDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrSourceDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.retrieveFile(mstrFilename, lfosTargetFile)) { throw new Exception("Unable to download [ " + mstrSourceDirectory + "/" + mstrFilename + " to " + mstrTargetDirectory + File.separator + mstrFilename + " ] from server [ " + mstrRemoteServer + " ]"); } lfosTargetFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfosTargetFile != null) { try { lfosTargetFile.close(); } catch (Exception e) { } } } }
Code Sample 2:
public static String MD5(String str) { try { MessageDigest md5 = MessageDigest.getInstance("md5"); md5.update(str.getBytes(), 0, str.length()); String sig = new BigInteger(1, md5.digest()).toString(); return sig; } catch (NoSuchAlgorithmException e) { System.err.println("Can not use md5 algorithm"); } return null; }
|
00
|
Code Sample 1:
private FeedIF retrieveFeed(String uri) throws FeedManagerException { try { URL urlToRetrieve = new URL(uri); URLConnection conn = null; try { conn = urlToRetrieve.openConnection(); if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setInstanceFollowRedirects(true); HttpHeaderUtils.setUserAgent(httpConn, "Informa Java API"); logger.debug("retr feed at url " + uri + ": ETag" + HttpHeaderUtils.getETagValue(httpConn) + " if-modified :" + HttpHeaderUtils.getLastModified(httpConn)); this.httpHeaders.setETag(HttpHeaderUtils.getETagValue(httpConn)); this.httpHeaders.setIfModifiedSince(HttpHeaderUtils.getLastModified(httpConn)); } } catch (java.lang.ClassCastException e) { conn = null; logger.warn("problem cast to HttpURLConnection " + uri, e); throw new FeedManagerException(e); } catch (NullPointerException e) { logger.error("problem NPE " + uri + " conn=" + conn, e); conn = null; throw new FeedManagerException(e); } ChannelIF channel = null; channel = FeedParser.parse(getChannelBuilder(), conn.getInputStream()); this.timeToExpire = getTimeToExpire(channel); this.feed = new Feed(channel); Date currDate = new Date(); this.feed.setLastUpdated(currDate); this.feed.setDateFound(currDate); this.feed.setLocation(urlToRetrieve); logger.info("feed retrieved " + uri); } catch (IOException e) { logger.error("IOException " + feedUri + " e=" + e); e.printStackTrace(); throw new FeedManagerException(e); } catch (ParseException e) { e.printStackTrace(); throw new FeedManagerException(e); } return this.feed; }
Code Sample 2:
public static String openldapDigestMd5(final String password) { String base64; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); base64 = fr.cnes.sitools.util.Base64.encodeBytes(digest.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return OPENLDAP_MD5_PREFIX + base64; }
|
00
|
Code Sample 1:
public void delete(int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt); if ((row < 1) || (row > max)) throw new IllegalArgumentException("Row number not between 1 and " + max); stmt.executeUpdate("delete from WordClassifications where Rank = " + row); for (int i = row; i < max; ++i) stmt.executeUpdate("update WordClassifications set Rank = " + i + " where Rank = " + (i + 1)); 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); } }
Code Sample 2:
private void chooseGame(DefaultHttpClient httpclient) throws IOException, ClientProtocolException { HttpGet httpget = new HttpGet(Constants.STRATEGICDOMINATION_URL + "/gameboard.cgi?gameid=" + 1687); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("cg form get: " + response.getStatusLine()); if (entity != null) { InputStream inStream = entity.getContent(); IOUtils.copy(inStream, System.out); } System.out.println("cg set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } }
|
00
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public static Map putFile(DispatchContext dctx, Map context) { Debug.logInfo("[putFile] starting...", module); InputStream localFile = null; try { localFile = new FileInputStream((String) context.get("localFilename")); } catch (IOException ioe) { Debug.logError(ioe, "[putFile] Problem opening local file", module); return ServiceUtil.returnError("ERROR: Could not open local file"); } List errorList = new ArrayList(); FTPClient ftp = new FTPClient(); try { Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module); ftp.connect((String) context.get("hostname")); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { Debug.logInfo("[putFile] Server refused connection", module); errorList.add("connection refused"); } else { String username = (String) context.get("username"); String password = (String) context.get("password"); Debug.logInfo("[putFile] logging in: username=" + username + ", password=" + password, module); if (!ftp.login(username, password)) { Debug.logInfo("[putFile] login failed", module); errorList.add("Login failed (" + username + ", " + password + ")"); } else { Boolean binaryTransfer = (Boolean) context.get("binaryTransfer"); boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue(); if (binary) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } Boolean passiveMode = (Boolean) context.get("passiveMode"); boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue(); if (passive) { ftp.enterLocalPassiveMode(); } Debug.logInfo("[putFile] storing local file remotely as: " + context.get("remoteFilename"), module); if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) { Debug.logInfo("[putFile] store was unsuccessful", module); errorList.add("File not sent succesfully: " + ftp.getReplyString()); } else { Debug.logInfo("[putFile] store was successful", module); List siteCommands = (List) context.get("siteCommands"); if (siteCommands != null) { Iterator ci = siteCommands.iterator(); while (ci.hasNext()) { String command = (String) ci.next(); Debug.logInfo("[putFile] sending SITE command: " + command, module); if (!ftp.sendSiteCommand(command)) { errorList.add("SITE command (" + command + ") failed: " + ftp.getReplyString()); } } } } } ftp.logout(); } } catch (IOException ioe) { Debug.log(ioe, "[putFile] caught exception: " + ioe.getMessage(), module); errorList.add("Problem with FTP transfer: " + ioe.getMessage()); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException dce) { Debug.logWarning(dce, "[putFile] Problem with FTP disconnect", module); } } } try { localFile.close(); } catch (IOException ce) { Debug.logWarning(ce, "[putFile] Problem closing local file", module); } if (errorList.size() > 0) { Debug.logError("[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module); return ServiceUtil.returnError(errorList); } Debug.logInfo("[putFile] finished successfully", module); return ServiceUtil.returnSuccess(); }
|
00
|
Code Sample 1:
public void initGet() throws Exception { URL url = new URL(getURL()); con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Accept", "*/*"); con.setRequestProperty("Range", "bytes=" + getPosition() + "-" + getRangeEnd()); con.setUseCaches(false); con.connect(); setInputStream(con.getInputStream()); }
Code Sample 2:
public static String createHash(String seed) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Can't happen!", e); } try { md.update(seed.getBytes(CHARSET)); md.update(String.valueOf(System.currentTimeMillis()).getBytes(CHARSET)); return toHexString(md.digest()); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Can't happen!", e); } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public static synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new Base64(-1).encodeToString(raw); }
Code Sample 2:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
11
|
Code Sample 1:
private void copy(File in, File out) { log.info("Copying yam file from: " + in.getName() + " to: " + out.getName()); try { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (IOException ioe) { fail("Failed testing while copying modified file: " + ioe.getMessage()); } }
Code Sample 2:
@Override public void execute(String[] args) throws Exception { Options cmdLineOptions = getCommandOptions(); try { GnuParser parser = new GnuParser(); CommandLine commandLine = parser.parse(cmdLineOptions, TolvenPlugin.getInitArgs()); String srcRepositoryURLString = commandLine.getOptionValue(CMD_LINE_SRC_REPOSITORYURL_OPTION); Plugins libraryPlugins = RepositoryMetadata.getRepositoryPlugins(new URL(srcRepositoryURLString)); String srcPluginId = commandLine.getOptionValue(CMD_LINE_SRC_PLUGIN_ID_OPTION); PluginDetail plugin = RepositoryMetadata.getPluginDetail(srcPluginId, libraryPlugins); if (plugin == null) { throw new RuntimeException("Could not locate plugin: " + srcPluginId + " in repository: " + srcRepositoryURLString); } String srcPluginVersionString = commandLine.getOptionValue(CMD_LINE_SRC_PLUGIN_VERSION_OPTION); PluginVersionDetail srcPluginVersion = null; if (srcPluginVersion == null) { srcPluginVersion = RepositoryMetadata.getLatestVersion(plugin); } else { srcPluginVersion = RepositoryMetadata.getPluginVersionDetail(srcPluginVersionString, plugin); } if (plugin == null) { throw new RuntimeException("Could not find a plugin version for: " + srcPluginId + " in repository: " + srcRepositoryURLString); } String destPluginId = commandLine.getOptionValue(CMD_LINE_DEST_PLUGIN_ID_OPTION); FileUtils.deleteDirectory(getPluginTmpDir()); URL srcURL = new URL(srcPluginVersion.getUri()); File newPluginDir = new File(getPluginTmpDir(), destPluginId); try { InputStream in = null; FileOutputStream out = null; File tmpZip = new File(getPluginTmpDir(), new File(srcURL.getFile()).getName()); try { in = srcURL.openStream(); out = new FileOutputStream(tmpZip); IOUtils.copy(in, out); TolvenZip.unzip(tmpZip, newPluginDir); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (tmpZip != null) { tmpZip.delete(); } } File pluginManifestFile = new File(newPluginDir, "tolven-plugin.xml"); if (!pluginManifestFile.exists()) { throw new RuntimeException(srcURL.toExternalForm() + "has no plugin manifest"); } Plugin pluginManifest = RepositoryMetadata.getPlugin(pluginManifestFile.toURI().toURL()); pluginManifest.setId(destPluginId); String destPluginVersion = commandLine.getOptionValue(CMD_LINE_DEST_PLUGIN_VERSION_OPTION); if (destPluginVersion == null) { destPluginVersion = DEFAULT_DEST_VERSION; } pluginManifest.setVersion(destPluginVersion); String pluginManifestXML = RepositoryMetadata.getPluginManifest(pluginManifest); FileUtils.writeStringToFile(pluginManifestFile, pluginManifestXML); File pluginFragmentManifestFile = new File(newPluginDir, "tolven-plugin-fragment.xml"); if (pluginFragmentManifestFile.exists()) { PluginFragment pluginManifestFragment = RepositoryMetadata.getPluginFragment(pluginFragmentManifestFile.toURI().toURL()); Requires requires = pluginManifestFragment.getRequires(); if (requires == null) { throw new RuntimeException("No <requires> detected for plugin fragment in: " + srcURL.toExternalForm()); } if (requires.getImport().size() != 1) { throw new RuntimeException("There should be only one import for plugin fragment in: " + srcURL.toExternalForm()); } requires.getImport().get(0).setPluginId(destPluginId); requires.getImport().get(0).setPluginVersion(destPluginVersion); String pluginFragmentManifestXML = RepositoryMetadata.getPluginFragmentManifest(pluginManifestFragment); FileUtils.writeStringToFile(pluginFragmentManifestFile, pluginFragmentManifestXML); } String destDirname = commandLine.getOptionValue(CMD_LINE_DEST_DIR_OPTION); File destDir = new File(destDirname); File destZip = new File(destDir, destPluginId + "-" + destPluginVersion + ".zip"); destDir.mkdirs(); TolvenZip.zip(newPluginDir, destZip); } finally { if (newPluginDir != null) { FileUtils.deleteDirectory(newPluginDir); } } } catch (ParseException ex) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(getClass().getName(), cmdLineOptions); throw new RuntimeException("Could not parse command line for: " + getClass().getName(), ex); } }
|
00
|
Code Sample 1:
public boolean verify(String digest, String password) throws NoSuchAlgorithmException { String alg = null; int size = 0; if (digest.regionMatches(true, 0, "{CRYPT}", 0, 7)) { digest = digest.substring(7); return UnixCrypt.matches(digest, password); } else if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) { digest = digest.substring(5); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) { digest = digest.substring(6); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) { digest = digest.substring(5); alg = "MD5"; size = 16; } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) { digest = digest.substring(6); alg = "MD5"; size = 16; } MessageDigest msgDigest = MessageDigest.getInstance(alg); byte[][] hs = split(Base64.decode(digest.toCharArray()), size); byte[] hash = hs[0]; byte[] salt = hs[1]; msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); return msgDigest.isEqual(hash, pwhash); }
Code Sample 2:
private ShaderProgram loadShaderProgram() { ShaderProgram sp = null; String vertexProgram = null; String fragmentProgram = null; Shader[] shaders = new Shader[2]; try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/simple.vert"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/simple.vert"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/simple.vert"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); vertexProgram = new String(buffer); vertexProgram = vertexProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load simple.vert"); e.printStackTrace(); } try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/simple.frag"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/simple.frag"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/simple.frag"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); fragmentProgram = new String(buffer); fragmentProgram = fragmentProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load simple.frag"); e.printStackTrace(); } if (vertexProgram != null && fragmentProgram != null) { shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); sp = new GLSLShaderProgram(); sp.setShaders(shaders); } return sp; }
|
00
|
Code Sample 1:
@Override public RoleItem addUserRole(RoleItem role, long userId) throws DatabaseException { if (role == null) throw new NullPointerException("role"); if (role.getName() == null || "".equals(role.getName())) throw new NullPointerException("role.getName()"); if (hasRole(role.getName(), userId)) { return new RoleItem(role.getName(), "", "exist"); } RoleItem defaultRole = new RoleItem(role.getName(), "", "exist"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } String retID = "exist"; String roleDesc = ""; PreparedStatement seqSt = null, roleDescSt = null; try { int modified = 0; PreparedStatement insSt = getConnection().prepareStatement(INSERT_USER_IN_ROLE_STATEMENT); insSt.setLong(1, userId); insSt.setString(2, role.getName()); modified = insSt.executeUpdate(); seqSt = getConnection().prepareStatement(USER_ROLE_VALUE); ResultSet rs = seqSt.executeQuery(); while (rs.next()) { retID = rs.getString(1); } roleDescSt = getConnection().prepareStatement(SELECT_ROLE_DESCRIPTION); roleDescSt.setString(1, role.getName()); ResultSet rs2 = roleDescSt.executeQuery(); while (rs2.next()) { roleDesc = rs2.getString(1); } if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + roleDescSt + "\""); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Queries: \"" + seqSt + "\" and \"" + roleDescSt + "\""); retID = "error"; } } catch (SQLException e) { LOGGER.error(e); retID = "error"; } finally { closeConnection(); } defaultRole.setId(retID); defaultRole.setDescription(roleDesc); return defaultRole; }
Code Sample 2:
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; }
|
11
|
Code Sample 1:
private static void copyImage(String srcImg, String destImg) { try { FileChannel srcChannel = new FileInputStream(srcImg).getChannel(); FileChannel dstChannel = new FileOutputStream(destImg).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
@SuppressWarnings("static-access") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { filename = URLDecoder.decode(filename, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { is = request.getInputStream(); File newFile = new File(realPath + filename); if (!newFile.exists()) { fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true,detailMsg}"); } else { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false,detailMsg:'文件已经存在!请重命名后上传!'}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + filename + " has existed!"); } } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
|
00
|
Code Sample 1:
public static byte[] ComputeForBinary(String ThisString) throws Exception { byte[] Result; MessageDigest MD5Hasher; MD5Hasher = MessageDigest.getInstance("MD5"); MD5Hasher.update(ThisString.getBytes("iso-8859-1")); Result = MD5Hasher.digest(); return Result; }
Code Sample 2:
@Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { in = LOADER.getResourceAsStream(RES_PKG + filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
|
11
|
Code Sample 1:
public void writeValue(Value v) throws IOException, SQLException { int type = v.getType(); writeInt(type); switch(type) { case Value.NULL: break; case Value.BYTES: case Value.JAVA_OBJECT: writeBytes(v.getBytesNoCopy()); break; case Value.UUID: { ValueUuid uuid = (ValueUuid) v; writeLong(uuid.getHigh()); writeLong(uuid.getLow()); break; } case Value.BOOLEAN: writeBoolean(v.getBoolean().booleanValue()); break; case Value.BYTE: writeByte(v.getByte()); break; case Value.TIME: writeLong(v.getTimeNoCopy().getTime()); break; case Value.DATE: writeLong(v.getDateNoCopy().getTime()); break; case Value.TIMESTAMP: { Timestamp ts = v.getTimestampNoCopy(); writeLong(ts.getTime()); writeInt(ts.getNanos()); break; } case Value.DECIMAL: writeString(v.getString()); break; case Value.DOUBLE: writeDouble(v.getDouble()); break; case Value.FLOAT: writeFloat(v.getFloat()); break; case Value.INT: writeInt(v.getInt()); break; case Value.LONG: writeLong(v.getLong()); break; case Value.SHORT: writeInt(v.getShort()); break; case Value.STRING: case Value.STRING_IGNORECASE: case Value.STRING_FIXED: writeString(v.getString()); break; case Value.BLOB: { long length = v.getPrecision(); if (SysProperties.CHECK && length < 0) { Message.throwInternalError("length: " + length); } writeLong(length); InputStream in = v.getInputStream(); long written = IOUtils.copyAndCloseInput(in, out); if (SysProperties.CHECK && written != length) { Message.throwInternalError("length:" + length + " written:" + written); } writeInt(LOB_MAGIC); break; } case Value.CLOB: { long length = v.getPrecision(); if (SysProperties.CHECK && length < 0) { Message.throwInternalError("length: " + length); } writeLong(length); Reader reader = v.getReader(); java.io.OutputStream out2 = new java.io.FilterOutputStream(out) { public void flush() { } }; Writer writer = new BufferedWriter(new OutputStreamWriter(out2, Constants.UTF8)); long written = IOUtils.copyAndCloseInput(reader, writer); if (SysProperties.CHECK && written != length) { Message.throwInternalError("length:" + length + " written:" + written); } writer.flush(); writeInt(LOB_MAGIC); break; } case Value.ARRAY: { Value[] list = ((ValueArray) v).getList(); writeInt(list.length); for (Value value : list) { writeValue(value); } break; } case Value.RESULT_SET: { ResultSet rs = ((ValueResultSet) v).getResultSet(); rs.beforeFirst(); ResultSetMetaData meta = rs.getMetaData(); int columnCount = meta.getColumnCount(); writeInt(columnCount); for (int i = 0; i < columnCount; i++) { writeString(meta.getColumnName(i + 1)); writeInt(meta.getColumnType(i + 1)); writeInt(meta.getPrecision(i + 1)); writeInt(meta.getScale(i + 1)); } while (rs.next()) { writeBoolean(true); for (int i = 0; i < columnCount; i++) { int t = DataType.convertSQLTypeToValueType(meta.getColumnType(i + 1)); Value val = DataType.readValue(session, rs, i + 1, t); writeValue(val); } } writeBoolean(false); rs.beforeFirst(); break; } default: Message.throwInternalError("type=" + type); } }
Code Sample 2:
static void copyFile(File file, File destDir) { File destFile = new File(destDir, file.getName()); if (destFile.exists() && (!destFile.canWrite())) { throw new SyncException("Cannot overwrite " + destFile + " because " + "it is read-only"); } try { FileInputStream in = new FileInputStream(file); try { FileOutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new SyncException("I/O error copying " + file + " to " + destDir + " (message: " + e.getMessage() + ")", e); } if (!destFile.setLastModified(file.lastModified())) { throw new SyncException("Could not set last modified timestamp " + "of " + destFile); } }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public static String downloadWebpage2(String address) throws MalformedURLException, IOException { URL url = new URL(address); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); String encoding = conn.getContentEncoding(); InputStream is = null; if(encoding != null && encoding.equalsIgnoreCase("gzip")) { is = new GZIPInputStream(conn.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { is = new InflaterInputStream(conn.getInputStream()); } else { is = conn.getInputStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; String page = ""; while((line = br.readLine()) != null) { page += line + "\n"; } br.close(); return page; }
|
00
|
Code Sample 1:
static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
Code Sample 2:
public static Properties load(URL url) { if (url == null) { return new Properties(); } InputStream in = null; try { in = url.openStream(); Properties ret = new Properties(); ret.load(in); return ret; } catch (IOException e) { throw new RuntimeException(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error("Error closing", e); } } } }
|
00
|
Code Sample 1:
public static void main(String[] args) { try { File fichierXSD = new File("D:/Users/Balley/données/gml/commune.xsd"); URL urlFichierXSD = fichierXSD.toURI().toURL(); InputStream isXSD = urlFichierXSD.openStream(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbFactory.newDocumentBuilder(); Document documentXSD = (builder.parse(isXSD)); ChargeurGMLSchema chargeur = new ChargeurGMLSchema(documentXSD); SchemaConceptuelJeu sc = chargeur.gmlSchema2schemaConceptuel(documentXSD); System.out.println(sc.getFeatureTypes().size()); for (int i = 0; i < sc.getFeatureTypes().size(); i++) { System.out.println(sc.getFeatureTypes().get(i).getTypeName()); for (int j = 0; j < sc.getFeatureTypes().get(i).getFeatureAttributes().size(); j++) { System.out.println(" " + sc.getFeatureTypes().get(i).getFeatureAttributes().get(j).getMemberName() + " : " + sc.getFeatureTypes().get(i).getFeatureAttributes().get(j).getValueType()); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } }
Code Sample 2:
private static FTPClient getFtpClient(String ftpHost, String ftpUsername, String ftpPassword) throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.connect(ftpHost); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return null; } if (!ftp.login(ftpUsername, ftpPassword)) { return null; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
|
00
|
Code Sample 1:
public static String rename_tag(String sessionid, String originalTag, String newTagName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_tag"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_tag")); nameValuePairs.add(new BasicNameValuePair("new_tag_name", newTagName)); nameValuePairs.add(new BasicNameValuePair("absolute_tag", originalTag)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
Code Sample 2:
public static LinkedList Import(String url) throws Exception { LinkedList data = new LinkedList(); BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String csvLine; while ((csvLine = in.readLine()) != null) { StringTokenizer st = new StringTokenizer(csvLine, ","); CSVData cd = new CSVData(); st.nextToken(); st.nextToken(); cd.matrNumber = Integer.parseInt(st.nextToken().trim()); cd.fName = st.nextToken().trim(); cd.lName = st.nextToken().trim(); cd.email = st.nextToken().trim(); cd.stdyPath = st.nextToken().trim(); cd.sem = Integer.parseInt(st.nextToken().trim()); data.add(cd); } in.close(); return data; }
|
00
|
Code Sample 1:
protected void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(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(); } } }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
00
|
Code Sample 1:
public static String obterConteudoSite(String u) { URL url; try { url = new URL(u); URLConnection conn = null; if (proxy != null) conn = url.openConnection(proxy.getProxy()); else conn = url.openConnection(); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8"))); String line; StringBuilder resultado = new StringBuilder(); while ((line = rd.readLine()) != null) { resultado.append(line); resultado.append("\n"); } rd.close(); return resultado.toString(); } catch (MalformedURLException e) { throw new AlfredException("Não foi possível obter contato com o site " + u, e); } catch (IOException e) { throw new AlfredException("Não foi possível obter contato com o site " + u, e); } }
Code Sample 2:
public static String do_checksum(String data) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); StringBuffer strbuf = new StringBuffer(); md5.update(data.getBytes(), 0, data.length()); byte[] digest = md5.digest(); for (int i = 0; i < digest.length; i++) { strbuf.append(toHexString(digest[i])); } return strbuf.toString(); }
|
00
|
Code Sample 1:
private static void loadPluginsFromClassLoader(ClassLoader classLoader) throws IOException { Enumeration res = classLoader.getResources("META-INF/services/" + GDSFactoryPlugin.class.getName()); while (res.hasMoreElements()) { URL url = (URL) res.nextElement(); InputStreamReader rin = new InputStreamReader(url.openStream()); BufferedReader bin = new BufferedReader(rin); while (bin.ready()) { String className = bin.readLine(); try { Class clazz = Class.forName(className); GDSFactoryPlugin plugin = (GDSFactoryPlugin) clazz.newInstance(); registerPlugin(plugin); } catch (ClassNotFoundException ex) { if (log != null) log.error("Can't register plugin" + className, ex); } catch (IllegalAccessException ex) { if (log != null) log.error("Can't register plugin" + className, ex); } catch (InstantiationException ex) { if (log != null) log.error("Can't register plugin" + className, ex); } } } }
Code Sample 2:
public InputPort getInputPort(String file) throws IOException { if (file.equals("/dev/null")) { return new StreamInputPort(new NullInputStream(), file); } URL url = Util.tryURL(file); if (url != null) { return new StreamInputPort(url.openStream(), url.toExternalForm()); } else return new FileInputPort(getFile(file)); }
|
00
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } }
Code Sample 2:
private void initBanner() { for (int k = 0; k < 3; k++) { if (bannerImg == null) { int i = getRandomId(); imageURL = NbBundle.getMessage(BottomContent.class, "URL_BannerImageLink", Integer.toString(i)); bannerURL = NbBundle.getMessage(BottomContent.class, "URL_BannerLink", Integer.toString(i)); HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet method = new HttpGet(imageURL); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); if (entity != null) { bannerImg = new ImageIcon(ImageIO.read(entity.getContent())); EntityUtils.consume(entity); } } catch (IOException ex) { bannerImg = null; } finally { method.abort(); } } else { break; } } if (bannerImg == null) { NotifyUtil.error("Banner Error", "Application could not get banner image. Please check your internet connection.", false); } }
|
00
|
Code Sample 1:
private void weightAndPlaceClasses() { int rows = getRows(); for (int curRow = _maxPackageRank; curRow < rows; curRow++) { xPos = getHGap() / 2; ClassdiagramNode[] rowObject = getObjectsInRow(curRow); for (int i = 0; i < rowObject.length; i++) { if (curRow == _maxPackageRank) { int nDownlinks = rowObject[i].getDownlinks().size(); rowObject[i].setWeight((nDownlinks > 0) ? (1 / nDownlinks) : 2); } else { Vector uplinks = rowObject[i].getUplinks(); int nUplinks = uplinks.size(); if (nUplinks > 0) { float average_col = 0; for (int j = 0; j < uplinks.size(); j++) { average_col += ((ClassdiagramNode) (uplinks.elementAt(j))).getColumn(); } average_col /= nUplinks; rowObject[i].setWeight(average_col); } else { rowObject[i].setWeight(1000); } } } int[] pos = new int[rowObject.length]; for (int i = 0; i < pos.length; i++) { pos[i] = i; } boolean swapped = true; while (swapped) { swapped = false; for (int i = 0; i < pos.length - 1; i++) { if (rowObject[pos[i]].getWeight() > rowObject[pos[i + 1]].getWeight()) { int temp = pos[i]; pos[i] = pos[i + 1]; pos[i + 1] = temp; swapped = true; } } } for (int i = 0; i < pos.length; i++) { rowObject[pos[i]].setColumn(i); if ((i > _vMax) && (rowObject[pos[i]].getUplinks().size() == 0) && (rowObject[pos[i]].getDownlinks().size() == 0)) { if (getColumns(rows - 1) > _vMax) { rows++; } rowObject[pos[i]].setRank(rows - 1); } else { rowObject[pos[i]].setLocation(new Point(xPos, yPos)); xPos += rowObject[pos[i]].getSize().getWidth() + getHGap(); } } yPos += getRowHeight(curRow) + getVGap(); } }
Code Sample 2:
private InputStream callService(String text) { InputStream in = null; try { URL url = new URL(SERVLET_URL); URLConnection conn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("POST"); httpConn.setDoInput(true); httpConn.setDoOutput(true); httpConn.connect(); DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream()); dataStream.writeBytes(text); dataStream.flush(); dataStream.close(); int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { ex.printStackTrace(); } return in; }
|
11
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException 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); } }
Code Sample 2:
private String getAuthUrlString(String account, String password) throws IOException, NoSuchAlgorithmException { Map<String, String> dict = retrieveLoginPage(); if (dict == null) { return null; } StringBuilder url = new StringBuilder("/config/login?login="); url.append(account); url.append("&passwd="); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); byte[] result = md5.digest(); for (int i = 0; i < 16; i++) { url.append(StringUtil.toHex2(result[i])); } String md5chal = dict.get(".challenge"); md5 = MessageDigest.getInstance("MD5"); md5.update(md5chal.getBytes(), 0, md5chal.length()); result = md5.digest(); for (int i = 0; i < 16; i++) { url.append(StringUtil.toHex2(result[i])); } Iterator<String> j = dict.keySet().iterator(); while (j.hasNext()) { String key = j.next(); String value = dict.get(key); if (!key.equals("passwd")) { if (key.equals(".save") || key.equals(".js")) { url.append("&" + key + "=1"); } else if (key.equals(".challenge")) { url.append("&" + key + "=" + value); } else { String u = URLEncoder.encode(value, "UTF-8"); url.append("&" + key + "=" + u); } } } url.append("&"); url.append(".hash=1"); url.append("&"); url.append(".md5=1"); return url.toString(); }
|
00
|
Code Sample 1:
private void verifyAvailability() { for (int i = 0; i < servers.size(); i++) { String hostEntry = (String) servers.get(i); String hostString = hostEntry.substring(0, hostEntry.indexOf(":")); String portString = hostEntry.substring(hostEntry.indexOf(":") + 1); String urlLocation = "http://" + hostString + ":" + portString + "/"; String urlData = null; String urlMatch = null; long startTime = System.currentTimeMillis(); URL url = null; HttpURLConnection conn = null; InputStream istream = null; if (serverRequests.get(hostEntry) != null) { String requestData = (String) serverRequests.get(hostEntry); urlData = requestData.substring(0, requestData.indexOf("\t")); try { urlMatch = requestData.substring(requestData.indexOf("\t") + 1); } catch (Exception e) { urlMatch = null; } urlLocation = "http://" + hostString + ":" + portString + "/" + urlData; } try { url = new URL(urlLocation); conn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e.getMessage()); serverTimes.put(hostEntry, "0"); continue; } try { istream = conn.getInputStream(); } catch (Exception e) { try { if (conn.getResponseCode() != 401) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception ee) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } int response = 501; try { response = conn.getResponseCode(); if (response != 200 && response != 401) { System.err.println("*** Warning: Connection to host '" + hostEntry + "' returns response: " + response); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostString + "' on port '" + portString + "'"); serverTimes.put(hostEntry, "0"); continue; } if (response != 401) { int contentLength = conn.getContentLength(); if (contentLength == -1) { contentLength = 4096; } byte data[] = new byte[contentLength]; int curPos = 0; try { int dataRead = 0; while ((dataRead = istream.read(data, curPos, contentLength - curPos)) != -1) { if (dataRead == 0) { break; } curPos += dataRead; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': Cannot read response from site."); serverTimes.put(hostEntry, "0"); continue; } if (urlMatch != null) { String urlContents = new String(data); data = null; if (urlContents.indexOf(urlMatch) == -1) { System.err.println("*** Warning: Host '" + hostEntry + "' does not match search string. Reports '" + urlContents + "'"); try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverTimes.put(hostEntry, "0"); continue; } } } try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverStatus.put(hostEntry, "1"); String timeResponse = Long.toString(System.currentTimeMillis() - startTime); Debug.log("Response time for '" + hostEntry + "' is " + timeResponse + " ms."); serverTimes.put(hostEntry, timeResponse); } }
Code Sample 2:
public static boolean joinFiles(File dest, Collection<File> sources) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fos = new FileOutputStream(dest); for (File source : sources) { fis = new FileInputStream(source); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; } fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("error joining files to " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
|
11
|
Code Sample 1:
public void deletePortletName(PortletNameBean portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portletNameBean.getPortletId() == null) throw new IllegalArgumentException("portletNameId is null"); String sql = "delete from WM_PORTAL_PORTLET_NAME " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
Code Sample 2:
public EFaxResult sendFax(ototype.SendFaxWrapper parameters) { EFaxResult efr = new EFaxResult(); if (!validFaxUser(parameters.getUserID(), parameters.getPassWord())) { efr.setResultCode(211); return efr; } Connection conn = null; String faxKey = getSegquence("t_fax_send") + ""; String sql = "insert into t_fax_send(faxKey,userID,appcode,sendername," + "sendernumber,sendercompany,sendtime,accountId, userId2, PID, moduleId, CDRType) values(?,?,?,?,?,?,?,?,?,?,?,?)"; Fax fax = parameters.getFax(); FaxContactor sender = fax.getSender(); FaxContactor[] receiver = fax.getReceiver(); try { conn = this.getJdbcTemplate().getDataSource().getConnection(); conn.setAutoCommit(false); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, faxKey); pstmt.setString(2, parameters.getUserID()); pstmt.setString(3, parameters.getAppCode()); pstmt.setString(4, sender.getContactor()); pstmt.setString(5, sender.getFaxNumber()); pstmt.setString(6, sender.getCompany()); pstmt.setString(7, fax.getSendTime()); pstmt.setString(8, parameters.getAccountId()); pstmt.setString(9, parameters.getUserId()); pstmt.setString(10, parameters.getPID()); pstmt.setInt(11, parameters.getModuleId()); pstmt.setInt(12, parameters.getCDRType()); pstmt.executeUpdate(); sql = "insert into t_fax_contactor(faxKey,contactorID,contactor,faxnumber,company) values(?,?,?,?,?)"; pstmt = conn.prepareStatement(sql); for (int k = 0; k < receiver.length; k++) { pstmt.setString(1, faxKey); pstmt.setString(2, receiver[k].getContactorID()); pstmt.setString(3, receiver[k].getContactor()); pstmt.setString(4, receiver[k].getFaxNumber()); pstmt.setString(5, receiver[k].getCompany()); pstmt.addBatch(); } pstmt.executeBatch(); sql = "insert into t_fax_file(faxKey,fileID,filename,filetype,fileurl,faxpages) values(?,?,?,?,?,?)"; pstmt = conn.prepareStatement(sql); FaxFile[] files = fax.getFiles(); for (int h = 0; h < files.length; h++) { String fileID = getSegquence("t_Fax_file") + ""; pstmt.setString(1, faxKey); pstmt.setString(2, fileID); pstmt.setString(3, files[h].getFileName()); pstmt.setString(4, files[h].getFileType()); pstmt.setString(5, files[h].getFileURL()); pstmt.setInt(6, files[h].getFaxPages()); Service.writeByteFile(files[h].getFile(), fileID); pstmt.addBatch(); } pstmt.executeBatch(); conn.commit(); efr.setResultCode(100); efr.setResultInfo(faxKey); } catch (SQLException e) { efr.setResultCode(200); try { conn.rollback(); } catch (Exception e1) { logger.error("Error validFaxUser", e1); } logger.error("Error validFaxUser", e); } catch (IOException e) { efr.setResultCode(200); logger.error("Error write file on sendfax", e); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { logger.error("Error sendFax on close conn", e); } } } return efr; }
|
00
|
Code Sample 1:
@TestTargetNew(level = TestLevel.COMPLETE, notes = "Test fails: IOException expected but IllegalStateException is thrown: ticket 128", method = "getInputStream", args = { }) public void test_getInputStream_DeleteJarFileUsingURLConnection() throws Exception { String jarFileName = ""; String entry = "text.txt"; String cts = System.getProperty("java.io.tmpdir"); File tmpDir = new File(cts); File jarFile = tmpDir.createTempFile("file", ".jar", tmpDir); jarFileName = jarFile.getPath(); FileOutputStream jarFileOutputStream = new FileOutputStream(jarFileName); JarOutputStream out = new JarOutputStream(new BufferedOutputStream(jarFileOutputStream)); JarEntry jarEntry = new JarEntry(entry); out.putNextEntry(jarEntry); out.write(new byte[] { 'a', 'b', 'c' }); out.close(); URL url = new URL("jar:file:" + jarFileName + "!/" + entry); URLConnection conn = url.openConnection(); conn.setUseCaches(false); InputStream is = conn.getInputStream(); is.close(); assertTrue(jarFile.delete()); }
Code Sample 2:
public void run() { try { String data = URLEncoder.encode("send_id", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8"); data += "&" + URLEncoder.encode("author", "UTF-8") + "=" + URLEncoder.encode(name.getText(), "UTF-8"); data += "&" + URLEncoder.encode("location", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("user.language"), "UTF-8"); data += "&" + URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(email.getText(), "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(comment.getText(), "UTF-8"); data += "&" + URLEncoder.encode("rate", "UTF-8") + "=" + URLEncoder.encode(rate.getSelectedItem().toString(), "UTF-8"); System.out.println(data); URL url = new URL("http://javablock.sourceforge.net/book/index.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String address = rd.readLine(); JPanel panel = new JPanel(); panel.add(new JLabel("Comment added")); panel.add(new JTextArea("visit: http://javablock.sourceforge.net/")); JOptionPane.showMessageDialog(null, new JLabel("Comment sended correctly!")); wr.close(); rd.close(); hide(); } catch (IOException ex) { Logger.getLogger(guestBook.class.getName()).log(Level.SEVERE, null, ex); } }
|
00
|
Code Sample 1:
public String ask(String s) { System.out.println("asking ---> " + s); try { String result = null; URL url = new URL("http://www.google.com/search?hl=en&rls=GGLR,GGLR:2005-50,GGLR:en&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=" + URLEncoder.encode(s, "UTF-8")); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(false); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String inputLine; while ((inputLine = in.readLine()) != null) { int textPos = inputLine.indexOf("Web definitions for "); if (textPos >= 0) { int ltrPos = inputLine.indexOf("<font size=-1>", textPos + 18); if (ltrPos >= 0) { int closePos = inputLine.indexOf("<", ltrPos + 14); if (closePos >= 0) { result = inputLine.substring(ltrPos + 14, closePos); } } } else { int ltrPos = inputLine.indexOf("— Location: "); if (ltrPos >= 0) { int closePos = inputLine.indexOf("<br", ltrPos + 18); if (closePos >= 0) { result = inputLine.substring(ltrPos + 18, closePos); } } } } in.close(); if (result != null) { result = result.replaceAll("<b>", ""); result = result.replaceAll("</b>", ""); result = result.replaceAll("("|')", "'"); System.out.println("result ---> " + result); } else { System.out.println("result ---> none!"); String ss = s.toUpperCase(); if (ss.startsWith("WHAT IS ")) { String toSearch = ss.substring(8).trim(); try { String str = getResultStr("http://www.google.com/search?hl=en&q=define%3A" + toSearch); str = cutAfter(str, "on the Web"); str = cutAfter(str, "<li>"); str = getBefore(str, "<br>"); result = str.replaceAll("\n", ""); } catch (Exception ee) { } } } return result; } catch (Exception e) { e.printStackTrace(); } return null; }
Code Sample 2:
public static void copyDirectory(File sourceDirectory, File targetDirectory) throws IOException { File[] sourceFiles = sourceDirectory.listFiles(FILE_FILTER); File[] sourceDirectories = sourceDirectory.listFiles(DIRECTORY_FILTER); targetDirectory.mkdirs(); if (sourceFiles != null && sourceFiles.length > 0) { for (int i = 0; i < sourceFiles.length; i++) { File sourceFile = sourceFiles[i]; FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetDirectory + File.separator + sourceFile.getName()); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(8192); long size = fcin.size(); long n = 0; while (n < size) { buf.clear(); if (fcin.read(buf) < 0) { break; } buf.flip(); n += fcout.write(buf); } fcin.close(); fcout.close(); fis.close(); fos.close(); } } if (sourceDirectories != null && sourceDirectories.length > 0) { for (int i = 0; i < sourceDirectories.length; i++) { File directory = sourceDirectories[i]; File newTargetDirectory = new File(targetDirectory, directory.getName()); copyDirectory(directory, newTargetDirectory); } } }
|
00
|
Code Sample 1:
@Test public void test20_badSmtp() throws Exception { Db db = DbConnection.defaultCieDbRW(); try { db.begin(); oldSmtp = Config.getProperty(db, "com.entelience.mail.MailHelper.hostName", "localhost"); oldSupport = Config.getProperty(db, "com.entelience.esis.feature.SupportNotifier", false); Config.setProperty(db, "com.entelience.mail.MailHelper.hostName", "127.0.10.1", 1); Config.setProperty(db, "com.entelience.esis.feature.SupportNotifier", "true", 1); PreparedStatement pst = db.prepareStatement("DELETE FROM t_client_errors"); db.executeUpdate(pst); db.commit(); } catch (Exception e) { db.rollback(); } finally { db.safeClose(); } }
Code Sample 2:
public void search() throws Exception { URL searchurl = new URL("" + "http://www.ncbi.nlm.nih.gov/blast/Blast.cgi" + "?CMD=Put" + "&DATABASE=" + this.database + "&PROGRAM=" + this.program + "&QUERY=" + this.sequence.seqString()); BufferedReader reader = new BufferedReader(new InputStreamReader(searchurl.openStream(), "UTF-8")); String line = ""; while ((line = reader.readLine()) != null) { if (line.contains("Request ID")) this.rid += line.substring(70, 81); } reader.close(); }
|
11
|
Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </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()); }
Code Sample 2:
public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws IOException { File fileIn = new File("D:\\zz_c\\study2\\src\\study\\io\\A.java"); InputStream fin = new FileInputStream(fileIn); PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(); pout.connect(pin); IoRead i = new IoRead(); i.setIn(pin); File fileOU1 = new File("D:\\zz_c\\study2\\src\\study\\io\\A1.java"); File fileOU2 = new File("D:\\zz_c\\study2\\src\\study\\io\\A2.java"); File fileOU3 = new File("D:\\zz_c\\study2\\src\\study\\io\\A3.java"); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU1))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU2))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU3))); PipedInputStream pin2 = new PipedInputStream(); PipedOutputStream pout2 = new PipedOutputStream(); i.addOut(pout2); pout2.connect(pin2); i.start(); int read; try { read = fin.read(); while (read != -1) { pout.write(read); read = fin.read(); } fin.close(); pout.close(); } catch (IOException e) { e.printStackTrace(); } int c = pin2.read(); while (c != -1) { System.out.print((char) c); c = pin2.read(); } pin2.close(); }
Code Sample 2:
public void insertRight(final String right) throws IOException { try { Connection conn = null; boolean autoCommit = false; try { conn = pool.getConnection(); autoCommit = conn.getAutoCommit(); conn.setAutoCommit(true); final PreparedStatement insert = conn.prepareStatement("insert into rights (name) values (?)"); insert.setString(1, right); insert.executeUpdate(); } catch (Throwable t) { if (conn != null) conn.rollback(); throw new SQLException(t.toString()); } finally { if (conn != null) { conn.setAutoCommit(autoCommit); conn.close(); } } } catch (final SQLException sqle) { log.log(Level.SEVERE, sqle.toString(), sqle); throw new IOException(sqle.toString()); } }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { try { FileReader inf = new FileReader(in); OutputStreamWriter outf = new OutputStreamWriter(new FileOutputStream(out), "UTF-8"); int c; while ((c = inf.read()) != -1) outf.write(c); inf.close(); outf.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static Boolean decompress(File source, File destination) { FileOutputStream outputStream; ZipInputStream inputStream; try { outputStream = null; inputStream = new ZipInputStream(new FileInputStream(source)); int read; byte buffer[] = new byte[BUFFER_SIZE]; ZipEntry zipEntry; while ((zipEntry = inputStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) new File(destination, zipEntry.getName()).mkdirs(); else { File fileEntry = new File(destination, zipEntry.getName()); fileEntry.getParentFile().mkdirs(); outputStream = new FileOutputStream(fileEntry); while ((read = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) { outputStream.write(buffer, 0, read); } outputStream.flush(); outputStream.close(); } } inputStream.close(); } catch (Exception oException) { return false; } return true; }
|
00
|
Code Sample 1:
protected String getHashCode(String value) { if (log.isDebugEnabled()) log.debug("getHashCode(...) -> begin"); String retVal = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(value.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < digest.length; i++) { sb.append(this.toHexString(digest[i])); } retVal = sb.toString(); if (log.isDebugEnabled()) log.debug("getHashCode(...) -> hashcode = " + retVal); } catch (Exception e) { log.error("getHashCode(...) -> error occured generating hashcode ", e); } if (log.isDebugEnabled()) log.debug("getHashCode(...) -> end"); return retVal; }
Code Sample 2:
public void launchJob(final String workingDir, final AppConfigType appConfig) throws FaultType { logger.info("called for job: " + jobID); MessageContext mc = MessageContext.getCurrentContext(); HttpServletRequest req = (HttpServletRequest) mc.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); String clientDN = (String) req.getAttribute(GSIConstants.GSI_USER_DN); if (clientDN != null) { logger.info("Client's DN: " + clientDN); } else { clientDN = "Unknown client"; } String remoteIP = req.getRemoteAddr(); SOAPService service = mc.getService(); String serviceName = service.getName(); if (serviceName == null) { serviceName = "Unknown service"; } if (appConfig.isParallel()) { if (AppServiceImpl.drmaaInUse) { if (AppServiceImpl.drmaaPE == null) { logger.error("drmaa.pe property must be specified in opal.properties " + "for parallel execution using DRMAA"); throw new FaultType("drmaa.pe property must be specified in opal.properties " + "for parallel execution using DRMAA"); } if (AppServiceImpl.mpiRun == null) { logger.error("mpi.run property must be specified in opal.properties " + "for parallel execution using DRMAA"); throw new FaultType("mpi.run property must be specified in " + "opal.properties for parallel execution " + "using DRMAA"); } } else if (!AppServiceImpl.globusInUse) { if (AppServiceImpl.mpiRun == null) { logger.error("mpi.run property must be specified in opal.properties " + "for parallel execution without using Globus"); throw new FaultType("mpi.run property must be specified in " + "opal.properties for parallel execution " + "without using Globus"); } } if (jobIn.getNumProcs() == null) { logger.error("Number of processes unspecified for parallel job"); throw new FaultType("Number of processes unspecified for parallel job"); } else if (jobIn.getNumProcs().intValue() > AppServiceImpl.numProcs) { logger.error("Processors required - " + jobIn.getNumProcs() + ", available - " + AppServiceImpl.numProcs); throw new FaultType("Processors required - " + jobIn.getNumProcs() + ", available - " + AppServiceImpl.numProcs); } } try { status.setCode(GramJob.STATUS_PENDING); status.setMessage("Launching executable"); status.setBaseURL(new URI(AppServiceImpl.tomcatURL + jobID)); } catch (MalformedURIException mue) { logger.error("Cannot convert base_url string to URI - " + mue.getMessage()); throw new FaultType("Cannot convert base_url string to URI - " + mue.getMessage()); } if (!AppServiceImpl.dbInUse) { AppServiceImpl.statusTable.put(jobID, status); } else { Connection conn = null; try { conn = DriverManager.getConnection(AppServiceImpl.dbUrl, AppServiceImpl.dbUser, AppServiceImpl.dbPasswd); } catch (SQLException e) { logger.error("Cannot connect to database - " + e.getMessage()); throw new FaultType("Cannot connect to database - " + e.getMessage()); } String time = new SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.US).format(new Date()); String sqlStmt = "insert into job_status(job_id, code, message, base_url, " + "client_dn, client_ip, service_name, start_time, last_update) " + "values ('" + jobID + "', " + status.getCode() + ", " + "'" + status.getMessage() + "', " + "'" + status.getBaseURL() + "', " + "'" + clientDN + "', " + "'" + remoteIP + "', " + "'" + serviceName + "', " + "'" + time + "', " + "'" + time + "');"; try { Statement stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); conn.close(); } catch (SQLException e) { logger.error("Cannot insert job status into database - " + e.getMessage()); throw new FaultType("Cannot insert job status into database - " + e.getMessage()); } } String args = appConfig.getDefaultArgs(); if (args == null) { args = jobIn.getArgList(); } else { String userArgs = jobIn.getArgList(); if (userArgs != null) args += " " + userArgs; } if (args != null) { args = args.trim(); } logger.debug("Argument list: " + args); if (AppServiceImpl.drmaaInUse) { String cmd = null; String[] argsArray = null; if (appConfig.isParallel()) { cmd = "/bin/sh"; String newArgs = AppServiceImpl.mpiRun + " -machinefile $TMPDIR/machines" + " -np " + jobIn.getNumProcs() + " " + appConfig.getBinaryLocation(); if (args != null) { args = newArgs + " " + args; } else { args = newArgs; } logger.debug("CMD: " + args); argsArray = new String[] { "-c", args }; } else { cmd = appConfig.getBinaryLocation(); if (args == null) args = ""; logger.debug("CMD: " + cmd + " " + args); argsArray = args.split(" "); } try { logger.debug("Working directory: " + workingDir); JobTemplate jt = session.createJobTemplate(); if (appConfig.isParallel()) jt.setNativeSpecification("-pe " + AppServiceImpl.drmaaPE + " " + jobIn.getNumProcs()); jt.setRemoteCommand(cmd); jt.setArgs(argsArray); jt.setJobName(jobID); jt.setWorkingDirectory(workingDir); jt.setErrorPath(":" + workingDir + "/stderr.txt"); jt.setOutputPath(":" + workingDir + "/stdout.txt"); drmaaJobID = session.runJob(jt); logger.info("DRMAA job has been submitted with id " + drmaaJobID); session.deleteJobTemplate(jt); } catch (Exception ex) { logger.error(ex); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via DRMAA - " + ex.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } status.setCode(GramJob.STATUS_ACTIVE); status.setMessage("Execution in progress"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } } else if (AppServiceImpl.globusInUse) { String rsl = null; if (appConfig.isParallel()) { rsl = "&(directory=" + workingDir + ")" + "(executable=" + appConfig.getBinaryLocation() + ")" + "(count=" + jobIn.getNumProcs() + ")" + "(jobtype=mpi)" + "(stdout=stdout.txt)" + "(stderr=stderr.txt)"; } else { rsl = "&(directory=" + workingDir + ")" + "(executable=" + appConfig.getBinaryLocation() + ")" + "(stdout=stdout.txt)" + "(stderr=stderr.txt)"; } if (args != null) { args = "\"" + args + "\""; args = args.replaceAll("[\\s]+", "\" \""); rsl += "(arguments=" + args + ")"; } logger.debug("RSL: " + rsl); try { job = new GramJob(rsl); GlobusCredential globusCred = new GlobusCredential(AppServiceImpl.serviceCertPath, AppServiceImpl.serviceKeyPath); GSSCredential gssCred = new GlobusGSSCredentialImpl(globusCred, GSSCredential.INITIATE_AND_ACCEPT); job.setCredentials(gssCred); job.addListener(this); job.request(AppServiceImpl.gatekeeperContact); } catch (Exception ge) { logger.error(ge); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via Globus - " + ge.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } } else { String cmd = null; if (appConfig.isParallel()) { cmd = new String(AppServiceImpl.mpiRun + " " + "-np " + jobIn.getNumProcs() + " " + appConfig.getBinaryLocation()); } else { cmd = new String(appConfig.getBinaryLocation()); } if (args != null) { cmd += " " + args; } logger.debug("CMD: " + cmd); try { logger.debug("Working directory: " + workingDir); proc = Runtime.getRuntime().exec(cmd, null, new File(workingDir)); stdoutThread = writeStdOut(proc, workingDir); stderrThread = writeStdErr(proc, workingDir); } catch (IOException ioe) { logger.error(ioe); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via fork - " + ioe.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } status.setCode(GramJob.STATUS_ACTIVE); status.setMessage("Execution in progress"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } } new Thread() { public void run() { try { waitForCompletion(); } catch (FaultType f) { logger.error(f); synchronized (status) { status.notifyAll(); } return; } if (AppServiceImpl.drmaaInUse || !AppServiceImpl.globusInUse) { done = true; status.setCode(GramJob.STATUS_STAGE_OUT); status.setMessage("Writing output metadata"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update status database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } } } try { if (!AppServiceImpl.drmaaInUse && !AppServiceImpl.globusInUse) { try { logger.debug("Waiting for all outputs to be written out"); stdoutThread.join(); stderrThread.join(); logger.debug("All outputs successfully written out"); } catch (InterruptedException ignore) { } } File stdOutFile = new File(workingDir + File.separator + "stdout.txt"); if (!stdOutFile.exists()) { throw new IOException("Standard output missing for execution"); } File stdErrFile = new File(workingDir + File.separator + "stderr.txt"); if (!stdErrFile.exists()) { throw new IOException("Standard error missing for execution"); } if (AppServiceImpl.archiveData) { logger.debug("Archiving output files"); File f = new File(workingDir); File[] outputFiles = f.listFiles(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(workingDir + File.separator + jobID + ".zip")); byte[] buf = new byte[1024]; try { for (int i = 0; i < outputFiles.length; i++) { FileInputStream in = new FileInputStream(outputFiles[i]); out.putNextEntry(new ZipEntry(outputFiles[i].getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); } catch (IOException e) { logger.error(e); logger.error("Error not fatal - moving on"); } } File f = new File(workingDir); File[] outputFiles = f.listFiles(); OutputFileType[] outputFileObj = new OutputFileType[outputFiles.length - 2]; int j = 0; for (int i = 0; i < outputFiles.length; i++) { if (outputFiles[i].getName().equals("stdout.txt")) { outputs.setStdOut(new URI(AppServiceImpl.tomcatURL + jobID + "/stdout.txt")); } else if (outputFiles[i].getName().equals("stderr.txt")) { outputs.setStdErr(new URI(AppServiceImpl.tomcatURL + jobID + "/stderr.txt")); } else { OutputFileType next = new OutputFileType(); next.setName(outputFiles[i].getName()); next.setUrl(new URI(AppServiceImpl.tomcatURL + jobID + "/" + outputFiles[i].getName())); outputFileObj[j++] = next; } } outputs.setOutputFile(outputFileObj); } catch (IOException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot retrieve outputs after finish - " + e.getMessage()); logger.error(e); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } } synchronized (status) { status.notifyAll(); } return; } if (!AppServiceImpl.dbInUse) { AppServiceImpl.outputTable.put(jobID, outputs); } else { Connection conn = null; try { conn = DriverManager.getConnection(AppServiceImpl.dbUrl, AppServiceImpl.dbUser, AppServiceImpl.dbPasswd); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot connect to database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } String sqlStmt = "insert into job_output(job_id, std_out, std_err) " + "values ('" + jobID + "', " + "'" + outputs.getStdOut().toString() + "', " + "'" + outputs.getStdErr().toString() + "');"; Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update job output database after finish - " + e.getMessage()); logger.error(e); try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } synchronized (status) { status.notifyAll(); } return; } OutputFileType[] outputFile = outputs.getOutputFile(); for (int i = 0; i < outputFile.length; i++) { sqlStmt = "insert into output_file(job_id, name, url) " + "values ('" + jobID + "', " + "'" + outputFile[i].getName() + "', " + "'" + outputFile[i].getUrl().toString() + "');"; try { stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update output_file DB after finish - " + e.getMessage()); logger.error(e); try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } synchronized (status) { status.notifyAll(); } return; } } } if (terminatedOK()) { status.setCode(GramJob.STATUS_DONE); status.setMessage("Execution complete - " + "check outputs to verify successful execution"); } else { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Execution failed"); } if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update status database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } } AppServiceImpl.jobTable.remove(jobID); synchronized (status) { status.notifyAll(); } logger.info("Execution complete for job: " + jobID); } }.start(); }
|
00
|
Code Sample 1:
public void run() { URLConnection con = null; try { con = url.openConnection(); if ("HTTPS".equalsIgnoreCase(url.getProtocol())) { HttpsURLConnection scon = (HttpsURLConnection) con; try { scon.setSSLSocketFactory(SSLUtil.getSSLSocketFactory(clientCertAlias)); HostnameVerifier hv = SSLUtil.getHostnameVerifier(hostCertLevel); if (hv != null) { scon.setHostnameVerifier(hv); } } catch (GeneralSecurityException e) { Debug.logError(e, module); } catch (GenericConfigException e) { Debug.logError(e, module); } } } catch (IOException e) { Debug.logError(e, module); } synchronized (URLConnector.this) { if (timedOut && con != null) { close(con); } else { connection = con; URLConnector.this.notify(); } } }
Code Sample 2:
public void playSIDFromHVSC(String name) { player.reset(); player.setStatus("Loading song: " + name); URL url; try { if (name.startsWith("/")) { name = name.substring(1); } url = getResource(hvscBase + name); if (player.readSID(url.openConnection().getInputStream())) { player.playSID(); } } catch (IOException ioe) { System.out.println("Could not load: "); ioe.printStackTrace(); player.setStatus("Could not load SID: " + ioe.getMessage()); } }
|
00
|
Code Sample 1:
private String getTextResponse(String address) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); BufferedReader in = null; try { con.connect(); assertEquals(HttpURLConnection.HTTP_OK, con.getResponseCode()); in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder builder = new StringBuilder(); String inputLine = null; while ((inputLine = in.readLine()) != null) { builder.append(inputLine); } return builder.toString(); } finally { if (in != null) { in.close(); } con.disconnect(); } }
Code Sample 2:
public String merge(int width, int height) throws Exception { htErrors.clear(); sendGetImageRequests(width, height); Vector files = new Vector(); ConcurrentHTTPTransactionHandler c = new ConcurrentHTTPTransactionHandler(); c.setCache(cache); c.checkIfModified(false); for (int i = 0; i < vImageUrls.size(); i++) { if ((String) vImageUrls.get(i) != null) { c.register((String) vImageUrls.get(i)); } else { } } c.doTransactions(); vTransparency = new Vector(); for (int i = 0; i < vImageUrls.size(); i++) { if (vImageUrls.get(i) != null) { String path = c.getResponseFilePath((String) vImageUrls.get(i)); if (path != null) { String contentType = c.getHeaderValue((String) vImageUrls.get(i), "content-type"); if (contentType.startsWith("image")) { files.add(path); vTransparency.add(htTransparency.get(vRank.get(i))); } } } } if (files.size() > 1) { File output = TempFiles.getFile(); String path = output.getPath(); ImageMerger.mergeAndSave(files, vTransparency, path, ImageMerger.GIF); imageName = output.getName(); imagePath = output.getPath(); return (imageName); } else if (files.size() == 1) { File f = new File((String) files.get(0)); File out = TempFiles.getFile(); BufferedInputStream is = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(out)); byte buf[] = new byte[1024]; for (int nRead; (nRead = is.read(buf, 0, 1024)) > 0; os.write(buf, 0, nRead)) ; os.flush(); os.close(); is.close(); imageName = out.getName(); return imageName; } else return ""; }
|
11
|
Code Sample 1:
public static void copyFile(File source, File target) throws Exception { if (source == null || target == null) { throw new IllegalArgumentException("The arguments may not be null."); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dtnChannel = new FileOutputStream(target).getChannel(); srcChannel.transferTo(0, srcChannel.size(), dtnChannel); srcChannel.close(); dtnChannel.close(); } catch (Exception e) { String message = "Unable to copy file '" + source.getName() + "' to '" + target.getName() + "'."; logger.error(message, e); throw new Exception(message, e); } }
Code Sample 2:
public static void copyURLToFile(URL source, File destination) throws IOException { if (destination.getParentFile() != null && !destination.getParentFile().exists()) { destination.getParentFile().mkdirs(); } if (destination.exists() && !destination.canWrite()) { String message = "Unable to open file " + destination + " for writing."; throw new IOException(message); } InputStream input = source.openStream(); try { FileOutputStream output = new FileOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
|
00
|
Code Sample 1:
private FTPClient getClient() throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.setDefaultPort(getPort()); ftp.connect(getIp()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.warn("FTP server refused connection: {}", getIp()); ftp.disconnect(); return null; } if (!ftp.login(getUsername(), getPassword())) { log.warn("FTP server refused login: {}, user: {}", getIp(), getUsername()); ftp.logout(); ftp.disconnect(); return null; } ftp.setControlEncoding(getEncoding()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
Code Sample 2:
private static PointGeomReader[] loadResourceList(final String resourceName, ClassLoader loader) { if (loader == null) loader = ClassLoader.getSystemClassLoader(); final FastSet<PointGeomReader> result = FastSet.newInstance(); try { final Enumeration<URL> resources = loader.getResources(resourceName); if (resources != null) { while (resources.hasMoreElements()) { final URL url = resources.nextElement(); final Properties mapping; InputStream urlIn = null; try { urlIn = url.openStream(); mapping = new Properties(); mapping.load(urlIn); } catch (IOException ioe) { continue; } finally { if (urlIn != null) try { urlIn.close(); } catch (Exception ignore) { } } for (Enumeration keys = mapping.propertyNames(); keys.hasMoreElements(); ) { final String format = (String) keys.nextElement(); final String implClassName = mapping.getProperty(format); result.add(loadResource(implClassName, loader)); } } } } catch (IOException ignore) { } PointGeomReader[] resultArr = result.toArray(new PointGeomReader[result.size()]); Arrays.sort(resultArr, FastComparator.DEFAULT); FastSet.recycle(result); return resultArr; }
|
00
|
Code Sample 1:
public String fetchContent(PathObject file) throws NetworkException { if (file.isFetched()) { return file.getContent(); } if (!"f".equals(file.getType())) { return null; } HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_ANC + file.getPath()); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); Document doc = XmlOperator.readDocument(entity.getContent()); return BBSBodyParseHelper.parsePathContent(doc, file); } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } }
Code Sample 2:
public void download(RequestContext ctx) throws IOException { if (ctx.isRobot()) { ctx.forbidden(); return; } long id = ctx.id(); File bean = File.INSTANCE.Get(id); if (bean == null) { ctx.not_found(); return; } String f_ident = ctx.param("fn", ""); if (id >= 100 && !StringUtils.equals(f_ident, bean.getIdent())) { ctx.not_found(); return; } if (bean.IsLoginRequired() && ctx.user() == null) { StringBuilder login = new StringBuilder(LinkTool.home("home/login?goto_page=")); ctx.redirect(login.toString()); return; } FileInputStream fis = null; try { java.io.File file = StorageService.FILES.readFile(bean.getPath()); fis = new FileInputStream(file); ctx.response().setContentLength((int) file.length()); String ext = FilenameUtils.getExtension(bean.getPath()); String mine_type = Multimedia.mime_types.get(ext); if (mine_type != null) ctx.response().setContentType(mine_type); String ua = ctx.header("user-agent"); if (ua != null && ua.indexOf("Firefox") >= 0) ctx.header("Content-Disposition", "attachment; filename*=\"utf8''" + LinkTool.encode_url(bean.getName()) + "." + ext + "\""); else ctx.header("Content-Disposition", "attachment; filename=" + LinkTool.encode_url(bean.getName() + "." + ext)); IOUtils.copy(fis, ctx.response().getOutputStream()); bean.IncDownloadCount(1); } finally { IOUtils.closeQuietly(fis); } }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } }
|
11
|
Code Sample 1:
@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(); }
Code Sample 2:
public static void copyResourceFileTo(String destFileName, String resourceFileName) { if (destFileName == null || resourceFileName == null) throw new IllegalArgumentException("Argument cannot be null."); try { FileInputStream in = null; FileOutputStream out = null; URL url = HelperMethods.class.getResource(resourceFileName); if (url == null) { System.out.println("URL " + resourceFileName + " cannot be created."); return; } String fileName = url.getFile(); fileName = fileName.replaceAll("%20", " "); File resourceFile = new File(fileName); if (!resourceFile.isFile()) { System.out.println(fileName + " cannot be opened."); return; } in = new FileInputStream(resourceFile); out = new FileOutputStream(new File(destFileName)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ex) { ex.printStackTrace(); } }
|
00
|
Code Sample 1:
public static String createHash(String seed) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Can't happen!", e); } try { md.update(seed.getBytes(CHARSET)); md.update(String.valueOf(System.currentTimeMillis()).getBytes(CHARSET)); return toHexString(md.digest()); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Can't happen!", e); } }
Code Sample 2:
@Override protected String doInBackground(String... params) { HttpURLConnection conn = null; String localFilePath = params[0]; if (localFilePath == null) { return null; } try { URL url = new URL(ConnectionHandler.getServerURL() + ":" + ConnectionHandler.getServerPort() + "/"); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); DataInputStream fileReader = new DataInputStream(new FileInputStream(localFilePath)); dos.write(toByte(twoHyphens + boundary + lineEnd)); dos.write(toByte("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"redpinfile\"" + lineEnd)); dos.write(toByte("Content-Type: application/octet-stream" + lineEnd)); dos.write(toByte("Content-Length: " + fileReader.available() + lineEnd)); dos.write(toByte(lineEnd)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileReader.read(buffer)) != -1) { dos.write(buffer, 0, bytesRead); } dos.write(toByte(lineEnd)); dos.write(toByte(twoHyphens + boundary + twoHyphens + lineEnd)); dos.flush(); dos.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } return b.toString(); } } catch (MalformedURLException ex) { Log.w(TAG, "error: " + ex.getMessage(), ex); } catch (IOException ioe) { Log.w(TAG, "error: " + ioe.getMessage(), ioe); } finally { if (conn != null) { conn.disconnect(); } } return null; }
|
00
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public boolean validateLogin(String username, String password) { boolean user_exists = false; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); statement = connect.prepareStatement("SELECT id from toepen.users WHERE username = ? AND password = ?"); statement.setString(1, username); statement.setString(2, password_hash); resultSet = statement.executeQuery(); while (resultSet.next()) { user_exists = true; } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_exists; } }
|
00
|
Code Sample 1:
private static byte[] getLoginHashSHA(final char[] password, final int seed) throws GGException { try { final MessageDigest hash = MessageDigest.getInstance("SHA1"); hash.update(new String(password).getBytes()); hash.update(GGUtils.intToByte(seed)); return hash.digest(); } catch (final NoSuchAlgorithmException e) { LOG.error("SHA1 algorithm not usable", e); throw new GGException("SHA1 algorithm not usable!", e); } }
Code Sample 2:
public RandomAccessFileOrArray(URL url) throws IOException { InputStream is = url.openStream(); try { this.arrayIn = InputStreamToArray(is); } finally { try { is.close(); } catch (IOException ioe) { } } }
|
00
|
Code Sample 1:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session == null) { log.warn("HttpProxyServlet: no session"); response.setStatus(404); return; } User user = (User) session.getAttribute("user"); if (user == null) { log.warn("HttpProxyServlet: user not logged in"); response.setStatus(404); return; } String target = null; if (request.getPathInfo() != null && !request.getPathInfo().equals("")) { target = "http:/" + request.getPathInfo() + "?" + request.getQueryString(); log.info("HttpProxyServlet: target=" + target); } else { log.warn("HttpProxyServlet: missing pathInfo"); response.setStatus(404); return; } InputStream is = null; ServletOutputStream out = null; try { URL url = new URL(target); URLConnection uc = url.openConnection(); response.setContentType(uc.getContentType()); is = uc.getInputStream(); out = response.getOutputStream(); byte[] buf = new byte[4096]; int bytesRead; while ((bytesRead = is.read(buf)) != -1) { out.write(buf, 0, bytesRead); } } catch (MalformedURLException e) { log.warn("HttpProxyServlet: malformed URL"); response.setStatus(404); } catch (IOException e) { log.warn("HttpProxyServlet: I/O exception"); response.setStatus(404); } finally { if (is != null) { is.close(); } if (out != null) { out.close(); } } }
Code Sample 2:
private void setup() { env = new EnvAdvanced(); try { URL url = Sysutil.getURL("world.env"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { String[] fields = line.split(","); if (fields[0].equalsIgnoreCase("skybox")) { env.setRoom(new EnvSkyRoom(fields[1])); } else if (fields[0].equalsIgnoreCase("camera")) { env.setCameraXYZ(Double.parseDouble(fields[1]), Double.parseDouble(fields[2]), Double.parseDouble(fields[3])); env.setCameraYaw(Double.parseDouble(fields[4])); env.setCameraPitch(Double.parseDouble(fields[5])); } else if (fields[0].equalsIgnoreCase("terrain")) { terrain = new EnvTerrain(fields[1]); terrain.setTexture(fields[2]); env.addObject(terrain); } else if (fields[0].equalsIgnoreCase("object")) { GameObject n = (GameObject) Class.forName(fields[10]).newInstance(); n.setX(Double.parseDouble(fields[1])); n.setY(Double.parseDouble(fields[2])); n.setZ(Double.parseDouble(fields[3])); n.setScale(Double.parseDouble(fields[4])); n.setRotateX(Double.parseDouble(fields[5])); n.setRotateY(Double.parseDouble(fields[6])); n.setRotateZ(Double.parseDouble(fields[7])); n.setTexture(fields[9]); n.setModel(fields[8]); n.setEnv(env); env.addObject(n); } } } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile, boolean overwrite) throws IOException, DirNotFoundException, FileNotFoundException, FileExistsAlreadyException { File destDir = new File(destFile.getParent()); if (!destDir.exists()) { throw new DirNotFoundException(destDir.getAbsolutePath()); } if (!sourceFile.exists()) { throw new FileNotFoundException(sourceFile.getAbsolutePath()); } if (!overwrite && destFile.exists()) { throw new FileExistsAlreadyException(destFile.getAbsolutePath()); } FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[8 * 1024]; int count = 0; do { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); in.close(); out.close(); }
Code Sample 2:
public static void main(String[] args) { try { String user = "techbeherca"; String targetUrl = "http://api.fanfou.com/statuses/user_timeline.xml?id=" + user; URL url = new URL(targetUrl); InputStream in = url.openStream(); ArrayList<MessageObj> list; if (in != null) { MessageListDOMParser parser = new MessageListDOMParser(); list = (ArrayList<MessageObj>) parser.parseXML(in); TransactionDAO dao = new TransactionDAO(); dao.insert(list); } } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void main(String args[]) { try { URL url = new URL("http://dev.activeanalytics.ca/piwik.php?url=http%3a%2f%2flyricscatcher.sourceforge.net%2fpiwik.php&action_name=&idsite=1&res=1440x900&h=17&m=2&s=16&fla=1&dir=1&qt=1&realp=1&pdf=1&wma=1&java=1&cookie=0&title=JAVAACCESS&urlref=http%3a%2f%2flyricscatcher.sourceforge.net%2fcomputeraccespage.html"); InputStream ist = url.openStream(); InputStreamReader isr = new InputStreamReader(ist); BufferedReader in = new BufferedReader(isr); String line = ""; String inputline = ""; while ((inputline = in.readLine()) != null) { line += inputline + "\n"; } System.out.println("finished: length=" + line.length() + "line=" + line); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { URL url = new URL("http://apps.sourceforge.net/piwik/lyricscatcher/piwik.php?url=http%3a%2f%2flyricscatcher.sourceforge.net%2fpiwik.php&action_name=&idsite=1&res=1440x900&h=0&m=22&s=1&fla=1&dir=1&qt=1&realp=1&pdf=1&wma=1&java=1&cookie=0&title=JAVAACCESS&urlref=http%3a%2f%2flyricscatcher.sourceforge.net%2fcomputeraccespage.html"); InputStream ist = url.openStream(); InputStreamReader isr = new InputStreamReader(ist); BufferedReader in = new BufferedReader(isr); String line = ""; String inputline = ""; while ((inputline = in.readLine()) != null) { line += inputline + "\n"; } System.out.println("finished: length=" + line.length() + "line=" + line); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { URL url = new URL("http://apps.sourceforge.net/piwik/lyricscatcher/piwik.php?url=http%3A%2F%2Flyricscatcher.sourceforge.net%2Fcomputeracces.html&action_name=&idsite=1&res=1440x900&h=0&m=28&s=36&fla=1&dir=1&qt=1&realp=0&pdf=1&wma=1&java=1&cookie=1&title=&urlref="); InputStream ist = url.openStream(); InputStreamReader isr = new InputStreamReader(ist); BufferedReader in = new BufferedReader(isr); String line = ""; String inputline = ""; while ((inputline = in.readLine()) != null) { line += inputline + "\n"; } System.out.println("finished: length=" + line.length() + "line=" + line); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public boolean validateZipFile(File zipFile) { String tempdir = Config.CONTEXT.getRealPath(getBackupTempFilePath()); try { deleteTempFiles(); File ftempDir = new File(tempdir); ftempDir.mkdirs(); File tempZip = new File(tempdir + File.separator + zipFile.getName()); tempZip.createNewFile(); FileChannel ic = new FileInputStream(zipFile).getChannel(); FileChannel oc = new FileOutputStream(tempZip).getChannel(); for (long i = 0; i <= ic.size(); i++) { ic.transferTo(0, 1000000, oc); i = i + 999999; } ic.close(); oc.close(); if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) { ZipFile z = new ZipFile(zipFile); ZipUtil.extract(z, new File(Config.CONTEXT.getRealPath(backupTempFilePath))); } return true; } catch (Exception e) { Logger.error(this, "Error with file", e); return false; } }
|
11
|
Code Sample 1:
private byte[] getMD5(String string) throws IMException { byte[] buffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(string.getBytes("utf-8")); buffer = md.digest(); buffer = getHexString(buffer); } catch (NoSuchAlgorithmException e) { throw new IMException(e); } catch (UnsupportedEncodingException ue) { throw new IMException(ue); } return buffer; }
Code Sample 2:
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); } }
|
11
|
Code Sample 1:
public static void copy(File srcDir, File dstDir) throws IOException { if (srcDir.isDirectory()) { if (!dstDir.exists()) dstDir.mkdir(); String[] children = srcDir.list(); for (int i = 0; i < children.length; i++) copy(new File(srcDir, children[i]), new File(dstDir, children[i])); } else { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(srcDir); out = new FileOutputStream(dstDir); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } } }
Code Sample 2:
private static void copyFile(File sourceFile, File destFile) { try { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } catch (Exception e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
Code Sample 2:
public static void main(String[] a) { ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); try { FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
private static String readUrl(String filePath, String charCoding, boolean urlIsFile) throws IOException { int chunkLength; InputStream is = null; try { if (!urlIsFile) { URL urlObj = new URL(filePath); URLConnection uc = urlObj.openConnection(); is = uc.getInputStream(); chunkLength = uc.getContentLength(); if (chunkLength <= 0) chunkLength = 1024; if (charCoding == null) { String type = uc.getContentType(); if (type != null) { charCoding = getCharCodingFromType(type); } } } else { if (registeredStreams.containsKey(filePath)) { is = registeredStreams.get(filePath); chunkLength = 4096; } else { File f = new File(filePath); long length = f.length(); chunkLength = (int) length; if (chunkLength != length) throw new IOException("Too big file size: " + length); if (chunkLength == 0) { return ""; } is = new FileInputStream(f); } } Reader r; if (charCoding == null) { r = new InputStreamReader(is); } else { r = new InputStreamReader(is, charCoding); } return readReader(r, chunkLength); } finally { if (is != null) is.close(); } }
Code Sample 2:
public void truncateLog(long finalZxid) throws IOException { long highestZxid = 0; for (File f : dataDir.listFiles()) { long zxid = isValidSnapshot(f); if (zxid == -1) { LOG.warn("Skipping " + f); continue; } if (zxid > highestZxid) { highestZxid = zxid; } } File[] files = getLogFiles(dataLogDir.listFiles(), highestZxid); boolean truncated = false; for (File f : files) { FileInputStream fin = new FileInputStream(f); InputArchive ia = BinaryInputArchive.getArchive(fin); FileChannel fchan = fin.getChannel(); try { while (true) { byte[] bytes = ia.readBuffer("txtEntry"); if (bytes.length == 0) { throw new EOFException(); } InputArchive iab = BinaryInputArchive.getArchive(new ByteArrayInputStream(bytes)); TxnHeader hdr = new TxnHeader(); deserializeTxn(iab, hdr); if (ia.readByte("EOF") != 'B') { throw new EOFException(); } if (hdr.getZxid() == finalZxid) { long pos = fchan.position(); fin.close(); FileOutputStream fout = new FileOutputStream(f); FileChannel fchanOut = fout.getChannel(); fchanOut.truncate(pos); truncated = true; break; } } } catch (EOFException eof) { } if (truncated == true) { break; } } if (truncated == false) { LOG.error("Not able to truncate the log " + Long.toHexString(finalZxid)); System.exit(13); } }
|
11
|
Code Sample 1:
public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
Code Sample 2:
public void includeJs(Group group, Writer out, PageContext pageContext) throws IOException { includeResource(pageContext, out, RetentionHelper.buildRootRetentionFilePath(group, ".js"), JS_BEGIN_TAG, JS_END_TAG); ByteArrayOutputStream outtmp = new ByteArrayOutputStream(); if (AbstractGroupBuilder.getInstance().buildGroupJsIfNeeded(group, outtmp, pageContext.getServletContext())) { FileOutputStream fileStream = new FileOutputStream(new File(RetentionHelper.buildFullRetentionFilePath(group, ".js"))); IOUtils.copy(new ByteArrayInputStream(outtmp.toByteArray()), fileStream); fileStream.close(); } }
|
00
|
Code Sample 1:
public RespID(PublicKey key) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance("SHA1"); ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString keyHash = new DEROctetString(digest.digest()); this.id = new ResponderID(keyHash); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } }
Code Sample 2:
public static Book GetReviewsForBook(String bookId, int page, int rating) throws Exception { Uri.Builder builder = new Uri.Builder(); builder.scheme("http"); builder.authority("www.goodreads.com"); builder.path("book/show"); builder.appendQueryParameter("key", _ConsumerKey); builder.appendQueryParameter("page", Integer.toString(page)); builder.appendQueryParameter("rating", Integer.toString(rating)); builder.appendQueryParameter("id", bookId); HttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(builder.build().toString()); if (get_IsAuthenticated()) { _Consumer.sign(getRequest); } HttpResponse response = httpClient.execute(getRequest); Response responseData = ResponseParser.parse(response.getEntity().getContent()); return responseData.get_Book(); }
|
11
|
Code Sample 1:
public void moveMessage(DBMimeMessage oSrcMsg) throws MessagingException { if (DebugFile.trace) { DebugFile.writeln("Begin DBFolder.moveMessage()"); DebugFile.incIdent(); } JDCConnection oConn = null; PreparedStatement oStmt = null; ResultSet oRSet = null; BigDecimal oPg = null; BigDecimal oPos = null; int iLen = 0; try { oConn = ((DBStore) getStore()).getConnection(); oStmt = oConn.prepareStatement("SELECT " + DB.pg_message + "," + DB.nu_position + "," + DB.len_mimemsg + " FROM " + DB.k_mime_msgs + " WHERE " + DB.gu_mimemsg + "=?"); oStmt.setString(1, oSrcMsg.getMessageGuid()); oRSet = oStmt.executeQuery(); if (oRSet.next()) { oPg = oRSet.getBigDecimal(1); oPos = oRSet.getBigDecimal(2); iLen = oRSet.getInt(3); } oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; oConn.setAutoCommit(false); oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "-" + String.valueOf(iLen) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, ((DBFolder) (oSrcMsg.getFolder())).getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "+" + String.valueOf(iLen) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oConn.commit(); } catch (SQLException sqle) { if (null != oRSet) { try { oRSet.close(); } catch (Exception ignore) { } } if (null != oStmt) { try { oStmt.close(); } catch (Exception ignore) { } } if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } throw new MessagingException(sqle.getMessage(), sqle); } if (null == oPg) throw new MessagingException("Source message not found"); if (null == oPos) throw new MessagingException("Source message position is not valid"); DBFolder oSrcFldr = (DBFolder) oSrcMsg.getFolder(); MboxFile oMboxSrc = null, oMboxThis = null; try { oMboxSrc = new MboxFile(oSrcFldr.getFile(), MboxFile.READ_WRITE); oMboxThis = new MboxFile(oSrcFldr.getFile(), MboxFile.READ_WRITE); oMboxThis.appendMessage(oMboxSrc, oPos.longValue(), iLen); oMboxThis.close(); oMboxThis = null; oMboxSrc.purge(new int[] { oPg.intValue() }); oMboxSrc.close(); oMboxSrc = null; } catch (Exception e) { if (oMboxThis != null) { try { oMboxThis.close(); } catch (Exception ignore) { } } if (oMboxSrc != null) { try { oMboxSrc.close(); } catch (Exception ignore) { } } throw new MessagingException(e.getMessage(), e); } try { oConn = ((DBStore) getStore()).getConnection(); BigDecimal dNext = getNextMessage(); String sCatGuid = getCategory().getString(DB.gu_category); oStmt = oConn.prepareStatement("UPDATE " + DB.k_mime_msgs + " SET " + DB.gu_category + "=?," + DB.pg_message + "=? WHERE " + DB.gu_mimemsg + "=?"); oStmt.setString(1, sCatGuid); oStmt.setBigDecimal(2, dNext); oStmt.setString(3, oSrcMsg.getMessageGuid()); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oConn.commit(); } catch (SQLException sqle) { if (null != oStmt) { try { oStmt.close(); } catch (Exception ignore) { } } if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } throw new MessagingException(sqle.getMessage(), sqle); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBFolder.moveMessage()"); } }
Code Sample 2:
private static boolean insereTutorial(final Connection con, final Tutorial tut, final Autor aut, final Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodTutorial(con, tut); String titulo = tut.getTitulo().replaceAll("['\"]", ""); String coment = tut.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO tutorial VALUES(" + tut.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO tut_aut VALUES(" + tut.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "TUTORIAL: Database error", JOptionPane.ERROR_MESSAGE); System.out.print(e.getMessage()); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } }
|
00
|
Code Sample 1:
static void test() throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); st = conn.createStatement(); String sql = "update user set money=money-10 where id=15"; st.executeUpdate(sql); sql = "select money from user where id=13"; rs = st.executeQuery(sql); float money = 0.0f; while (rs.next()) { money = rs.getFloat("money"); } if (money > 1000) throw new RuntimeException("�Ѿ��������ֵ��"); sql = "update user set money=money+10 where id=13"; st.executeUpdate(sql); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { JdbcUtils.free(rs, st, conn); } }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
11
|
Code Sample 1:
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(); } }
Code Sample 2:
public boolean validateZipFile(File zipFile) { String tempdir = Config.CONTEXT.getRealPath(getBackupTempFilePath()); try { deleteTempFiles(); File ftempDir = new File(tempdir); ftempDir.mkdirs(); File tempZip = new File(tempdir + File.separator + zipFile.getName()); tempZip.createNewFile(); FileChannel ic = new FileInputStream(zipFile).getChannel(); FileChannel oc = new FileOutputStream(tempZip).getChannel(); for (long i = 0; i <= ic.size(); i++) { ic.transferTo(0, 1000000, oc); i = i + 999999; } ic.close(); oc.close(); if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) { ZipFile z = new ZipFile(zipFile); ZipUtil.extract(z, new File(Config.CONTEXT.getRealPath(backupTempFilePath))); } return true; } catch (Exception e) { Logger.error(this, "Error with file", e); return false; } }
|
00
|
Code Sample 1:
static byte[] getPassword(final String name, final String password) { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(name.getBytes()); messageDigest.update(password.getBytes()); return messageDigest.digest(); } catch (final NoSuchAlgorithmException e) { throw new JobException(e); } }
Code Sample 2:
private void prepareJobFile(ZipEntryRef zer, String nodeDir, String reportDir, Set<ZipEntryRef> statusZers) throws Exception { String jobDir = nodeDir + File.separator + "job_" + zer.getUri(); if (!isWorkingDirectoryValid(jobDir)) { throw new Exception("Cannot acces to " + jobDir); } File f = new File(jobDir + File.separator + "result.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to result file " + f.getAbsolutePath()); } String fcopyName = reportDir + File.separator + zer.getName() + ".xml"; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); zer.setUri(fcopyName); f = new File(jobDir + File.separator + "status.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to status file " + f.getAbsolutePath()); } fcopyName = reportDir + File.separator + zer.getName() + "_status.xml"; bis = new BufferedInputStream(new FileInputStream(f)); bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); statusZers.add(new ZipEntryRef(ZipEntryRef.JOB, zer.getName(), fcopyName)); }
|
11
|
Code Sample 1:
public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static void copier(final File pFichierSource, final File pFichierDest) { FileChannel vIn = null; FileChannel vOut = null; try { vIn = new FileInputStream(pFichierSource).getChannel(); vOut = new FileOutputStream(pFichierDest).getChannel(); vIn.transferTo(0, vIn.size(), vOut); } catch (Exception e) { e.printStackTrace(); } finally { if (vIn != null) { try { vIn.close(); } catch (IOException e) { } } if (vOut != null) { try { vOut.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
public CopyAllDataToOtherFolderResponse CopyAllDataToOtherFolder(DPWSContext context, CopyAllDataToOtherFolder CopyAllDataInps) throws DPWSException { CopyAllDataToOtherFolderResponse cpyRp = new CopyAllDataToOtherFolderResponseImpl(); int hany = 0; String errorMsg = null; try { if ((rootDir == null) || (rootDir.length() == (-1))) { errorMsg = LocalStorVerify.ISNT_ROOTFLD; } else { String sourceN = CopyAllDataInps.getSourceName(); String targetN = CopyAllDataInps.getTargetName(); if (LocalStorVerify.isValid(sourceN) && LocalStorVerify.isValid(targetN)) { String srcDir = rootDir + File.separator + sourceN; String trgDir = rootDir + File.separator + targetN; if (LocalStorVerify.isLength(srcDir) && LocalStorVerify.isLength(trgDir)) { for (File fs : new File(srcDir).listFiles()) { File ft = new File(trgDir + '\\' + fs.getName()); FileChannel in = null, out = null; try { in = new FileInputStream(fs).getChannel(); out = new FileOutputStream(ft).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(); hany++; } } } else { errorMsg = LocalStorVerify.FLD_TOOLNG; } } else { errorMsg = LocalStorVerify.ISNT_VALID; } } } catch (Throwable tr) { tr.printStackTrace(); errorMsg = tr.getMessage(); hany = (-1); } if (errorMsg != null) { } cpyRp.setNum(hany); return cpyRp; }
Code Sample 2:
@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]; } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.