label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
|
Code Sample 1:
public static void executeUpdate(Database db, String... statements) throws SQLException { Connection con = null; Statement stmt = null; try { con = getConnection(db); con.setAutoCommit(false); stmt = con.createStatement(); for (String statement : statements) { stmt.executeUpdate(statement); } con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { } throw e; } finally { closeStatement(stmt); closeConnection(con); } }
Code Sample 2:
public String getPloidy(String source) { StringBuilder ploidyHtml = new StringBuilder(); String hyperdiploidyUrl = customParameters.getHyperdiploidyUrl(); String urlString = hyperdiploidyUrl + "?source=" + source; URL url = null; try { url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; while ((line = in.readLine()) != null) { ploidyHtml.append(line); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ploidyHtml.toString(); }
|
00
|
Code Sample 1:
public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
Code Sample 2:
public void getFile(OutputStream output, Fragment fragment) throws Exception { Assert.Arg.notNull(output, "output"); Assert.Arg.notNull(fragment, "fragment"); Assert.Arg.notNull(fragment.getId(), "fragment.getId()"); if (this.delegate != null) { this.delegate.getFile(output, fragment); return; } ensureBaseDirectoryCreated(); File filePath = getFragmentFilePath(fragment); InputStream input = FileUtils.openInputStream(filePath); try { IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(input); } }
|
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 CMLUnitList createUnitList(URL url) throws IOException, CMLException { Document dictDoc = null; InputStream in = null; try { in = url.openStream(); dictDoc = new CMLBuilder().build(in); } catch (NullPointerException e) { e.printStackTrace(); throw new CMLException("NULL " + e.getMessage() + S_SLASH + e.getCause() + " in " + url); } catch (ValidityException e) { throw new CMLException(S_EMPTY + e.getMessage() + S_SLASH + e.getCause() + " in " + url); } catch (ParsingException e) { e.printStackTrace(); throw new CMLException(e, " in " + url); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } CMLUnitList dt = null; if (dictDoc != null) { Element root = dictDoc.getRootElement(); if (root instanceof CMLUnitList) { dt = new CMLUnitList((CMLUnitList) root); } else { } } if (dt != null) { dt.indexEntries(); } return dt; }
|
00
|
Code Sample 1:
public void xtestFile2() throws Exception { InputStream inputStream = new FileInputStream(IOTest.FILE); OutputStream outputStream = new FileOutputStream("C:/Temp/testFile2.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }
Code Sample 2:
public static void main(String argv[]) { try { if (argv.length != 1 && argv.length != 3) { usage(); System.exit(1); } URL url = new URL(argv[0]); URLConnection conn; conn = url.openConnection(); if (conn.getHeaderField("WWW-Authenticate") != null) { auth(conn, argv[1], argv[2]); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) System.out.println(line); } } catch (Exception ex) { ex.printStackTrace(); } }
|
00
|
Code Sample 1:
protected void addAssetResources(MimeMultipart pkg, MarinerPageContext context) throws PackagingException { boolean includeFullyQualifiedURLs = context.getBooleanDevicePolicyValue("protocol.mime.fully.qualified.urls"); MarinerRequestContext requestContext = context.getRequestContext(); ApplicationContext ac = ContextInternals.getApplicationContext(requestContext); PackageResources pr = ac.getPackageResources(); List encodedURLs = pr.getEncodedURLs(); Map assetURLMap = pr.getAssetURLMap(); Iterator iterator; String encodedURL; PackageResources.Asset asset; String assetURL = null; BodyPart assetPart; if (encodedURLs != null) { iterator = encodedURLs.iterator(); } else { iterator = assetURLMap.keySet().iterator(); } while (iterator.hasNext()) { encodedURL = (String) iterator.next(); asset = (PackageResources.Asset) assetURLMap.get(encodedURL); assetURL = asset.getValue(); if (includeFullyQualifiedURLs || !isFullyQualifiedURL(assetURL)) { if (isToBeAdded(assetURL, context)) { assetPart = new MimeBodyPart(); try { if (!asset.getOnClientSide()) { URL url = null; URLConnection connection; try { url = context.getAbsoluteURL(new MarinerURL(assetURL)); connection = url.openConnection(); if (connection != null) { connection.setDoInput(true); connection.setDoOutput(false); connection.setAllowUserInteraction(false); connection.connect(); connection.getInputStream(); assetPart.setDataHandler(new DataHandler(url)); assetPart.setHeader("Content-Location", assetURL); pkg.addBodyPart(assetPart); } } catch (MalformedURLException e) { if (logger.isDebugEnabled()) { logger.debug("Ignoring asset with malformed URL: " + url.toString()); } } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug("Ignoring asset with URL that doesn't " + "exist: " + assetURL + " (" + url.toString() + ")"); } } } else { assetPart.setHeader("Content-Location", "file://" + assetURL); } } catch (MessagingException e) { throw new PackagingException(exceptionLocalizer.format("could-not-add-asset", encodedURL), e); } } } } }
Code Sample 2:
private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0 && !stopped) outFile.write(buf, 0, read); inFile.close(); }
|
11
|
Code Sample 1:
private void copyFile(String sourceFilename, String targetFilename) throws IOException { File source = new File(sourceFilename); File target = new File(targetFilename); InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(target); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
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 final File getFile(final URL url) throws IOException { final File shortcutFile; final File currentFile = files.get(url); if (currentFile == null || !currentFile.exists()) { shortcutFile = File.createTempFile("windowsIsLame", ".vbs"); shortcutFile.deleteOnExit(); files.put(url, shortcutFile); final InputStream stream = url.openStream(); final FileOutputStream out = new FileOutputStream(shortcutFile); try { StreamUtils.copy(stream, out); } finally { out.close(); stream.close(); } } else shortcutFile = currentFile; return shortcutFile; }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
|
11
|
Code Sample 1:
public static void copyFile(String inputFile, String outputFile) throws IOException { FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); for (int b = fis.read(); b != -1; b = fis.read()) fos.write(b); fos.close(); fis.close(); }
Code Sample 2:
public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); }
|
00
|
Code Sample 1:
public static String Sha1(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = new byte[40]; md.update(s.getBytes("iso-8859-1"), 0, s.length()); hash = md.digest(); return toHex(hash); } catch (Exception e) { e.printStackTrace(); return null; } }
Code Sample 2:
protected static void clearTables() throws SQLException { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); ClearData.clearTables(stmt); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (2, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (3, '')"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } }
|
11
|
Code Sample 1:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); sql = "DELETE FROM usuario WHERE cod_usuario =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
Code Sample 2:
public static void updateTableData(Connection dest, TableMetaData tableMetaData, Row r) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "UPDATE " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " SET "; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + " = ? ,"; } sql = sql.substring(0, sql.length() - 1); sql += " WHERE "; for (String pkColumnName : tableMetaData.getPkColumns()) { sql += pkColumnName + " = ? AND "; } sql = sql.substring(0, sql.length() - 4); System.out.println("UPDATE: " + sql); ps = dest.prepareStatement(sql); int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { ps.setObject(param, r.getRowData().get(columnName)); } param++; } for (String pkColumnName : tableMetaData.getPkColumns()) { ps.setObject(param, r.getRowData().get(pkColumnName)); param++; } if (ps.executeUpdate() != 1) { dest.rollback(); throw new Exception("Erro no update"); } ps.clearParameters(); dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } }
|
11
|
Code Sample 1:
public void xtest2() throws Exception { InputStream input1 = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream input2 = new FileInputStream("C:/Documentos/j931_02.pdf"); InputStream tmp = new ITextManager().merge(new InputStream[] { input1, input2 }); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input1.close(); input2.close(); tmp.close(); output.close(); }
Code Sample 2:
public void run() { try { textUpdater.start(); int cnt; byte[] buf = new byte[4096]; File file = null; ZipInputStream zis = new ZipInputStream(new FileInputStream(new File(filename))); ZipEntry ze = zis.getNextEntry(); FileOutputStream fos; while (ze != null) { if (ze.isDirectory()) { file = new File(ze.getName()); if (!file.exists()) { textUpdater.appendText("Creating directory: " + ze.getName() + "\n"); file.mkdirs(); } } else { textUpdater.appendText("Extracting file: " + ze.getName() + "\n"); fos = new FileOutputStream(dstdir + File.separator + ze.getName()); while ((cnt = zis.read(buf, 0, buf.length)) != -1) fos.write(buf, 0, cnt); fos.close(); } zis.closeEntry(); ze = zis.getNextEntry(); } zis.close(); if (complete != null) textUpdater.appendText(complete + "\n"); } catch (Exception e) { e.printStackTrace(); } textUpdater.setFinished(true); }
|
00
|
Code Sample 1:
public static RecordResponse loadRecord(RecordRequest recordRequest) { RecordResponse recordResponse = new RecordResponse(); try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(recordRequest.isContact() ? URL_RECORD_CONTACT : URL_RECORD_COMPANY); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6); nameValuePairs.add(new BasicNameValuePair("format", "xml")); nameValuePairs.add(new BasicNameValuePair("token", recordRequest.getToken())); nameValuePairs.add(new BasicNameValuePair("id", recordRequest.getId())); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); String line = EntityUtils.toString(response.getEntity()); Document document = XMLfunctions.XMLfromString(line); NodeList nodes = document.getElementsByTagName("response"); Element e = (Element) nodes.item(0); String Name__Last__First_ = XMLfunctions.getValue(e, recordRequest.isContact() ? "Name__Last__First_" : "Name"); String phone = ""; if (!recordRequest.isContact()) phone = XMLfunctions.getValue(e, "Phone"); String Email1 = XMLfunctions.getValue(e, recordRequest.isContact() ? "Personal_Email" : "Email"); String Home_Fax = XMLfunctions.getValue(e, recordRequest.isContact() ? "Home_Fax" : "Fax1"); String Address1 = XMLfunctions.getValue(e, "Address1"); String Address2 = XMLfunctions.getValue(e, "Address2"); String City = XMLfunctions.getValue(e, "City"); String State = XMLfunctions.getValue(e, "State"); String Zip = XMLfunctions.getValue(e, "Zip"); String Country = XMLfunctions.getValue(e, "Country"); String Profile = XMLfunctions.getValue(e, "Profile"); String success = XMLfunctions.getValue(e, "success"); String error = XMLfunctions.getValue(e, "error"); recordResponse.setName(Name__Last__First_); recordResponse.setPhone(phone); recordResponse.setEmail(Email1); recordResponse.setHomeFax(Home_Fax); recordResponse.setAddress1(Address1); recordResponse.setAddress2(Address2); recordResponse.setCity(City); recordResponse.setState(State); recordResponse.setZip(Zip); recordResponse.setProfile(Profile); recordResponse.setCountry(Country); recordResponse.setSuccess(success); recordResponse.setError(error); } catch (Exception e) { } return recordResponse; }
Code Sample 2:
private void copy(File src, File dest, String name) { File srcFile = new File(src, name); File destFile = new File(dest, name); if (destFile.exists()) { if (destFile.lastModified() == srcFile.lastModified()) return; destFile.delete(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(srcFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); } catch (IOException e) { } try { if (out != null) out.close(); } catch (IOException e) { } } destFile.setLastModified(srcFile.lastModified()); }
|
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 version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
private void loadMap(URI uri) throws IOException { BufferedReader reader = null; InputStream stream = null; try { URL url = uri.toURL(); stream = url.openStream(); if (url.getFile().endsWith(".gz")) { stream = new GZIPInputStream(stream); } reader = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { String[] parts = line.split(" "); if (parts.length == 2) { pinyinZhuyinMap.put(parts[0], parts[1]); zhuyinPinyinMap.put(parts[1], parts[0]); } } } } finally { if (reader != null) { reader.close(); } } }
|
11
|
Code Sample 1:
private static void unpackEntry(File destinationFile, ZipInputStream zin, ZipEntry entry) throws Exception { if (!entry.isDirectory()) { createFolders(destinationFile.getParentFile()); FileOutputStream fis = new FileOutputStream(destinationFile); try { IOUtils.copy(zin, fis); } finally { zin.closeEntry(); fis.close(); } } else { createFolders(destinationFile); } }
Code Sample 2:
private static void copy(String sourceName, String destName) throws IOException { File source = new File(sourceName); File dest = new File(destName); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
00
|
Code Sample 1:
private void copyXsl(File aTargetLogDir) { Trace.println(Trace.LEVEL.UTIL, "copyXsl( " + aTargetLogDir.getName() + " )", true); if (myXslSourceDir == null) { return; } File[] files = myXslSourceDir.listFiles(); for (int i = 0; i < files.length; i++) { File srcFile = files[i]; if (!srcFile.isDirectory()) { File tgtFile = new File(aTargetLogDir + File.separator + srcFile.getName()); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(srcFile).getChannel(); outChannel = new FileOutputStream(tgtFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new IOError(e); } finally { if (inChannel != null) try { inChannel.close(); } catch (IOException exc) { throw new IOError(exc); } if (outChannel != null) try { outChannel.close(); } catch (IOException exc) { throw new IOError(exc); } } } } }
Code Sample 2:
public String descargarArchivo(String miArchivo, String nUsuario) { try { URL url = new URL(conf.Conf.descarga + nUsuario + "/" + miArchivo); URLConnection urlCon = url.openConnection(); System.out.println(urlCon.getContentType()); InputStream is = urlCon.getInputStream(); FileOutputStream fos = new FileOutputStream("D:/" + miArchivo); byte[] array = new byte[1000]; int leido = is.read(array); while (leido > 0) { fos.write(array, 0, leido); leido = is.read(array); } is.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } return "llego"; }
|
00
|
Code Sample 1:
public static String post(String strUrl, String data) throws Exception { URL url = new URL(strUrl); final String method = "POST"; final String host = url.getHost(); final String contentType = "application/x-www-form-urlencoded"; final int contentLength = getContentLength(data); final String encoding = "UTF-8"; final String connection = "Close"; Config.log(DEBUG, "Sending data to: " + url + " (host=" + host + ", encoding=" + encoding + ", method=" + method + ", Content-Type=" + contentType + ", Content-Length=" + contentLength + ", Connection=" + connection + "):" + "\r\n" + data); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(method); conn.setRequestProperty("host", host); conn.setRequestProperty("content-type", contentType); conn.setRequestProperty("Content-Encoding", encoding); conn.setRequestProperty("content-length", contentLength + ""); conn.setRequestProperty("connection", connection); if (tools.valid(Config.JSON_RPC_WEBSERVER_USERNAME) && tools.valid(Config.JSON_RPC_WEBSERVER_PASSWORD)) { String authString = Config.JSON_RPC_WEBSERVER_USERNAME + ":" + Config.JSON_RPC_WEBSERVER_PASSWORD; String authStringEnc = new sun.misc.BASE64Encoder().encode(authString.getBytes()); conn.setRequestProperty("Authorization", "Basic " + authStringEnc); } conn.setReadTimeout((int) (Config.JSON_RPC_TIMEOUT_SECONDS * 1000)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); writer.close(); int responseCode = 400; try { responseCode = conn.getResponseCode(); } catch (Exception x) { Config.log(ERROR, "Failed to get response code from HTTP Server. Check your URL and username/password.", x); } String response = readStream(responseCode == 200 ? conn.getInputStream() : conn.getErrorStream()); if (response == null) { return null; } Config.log(DEBUG, "Raw response from POST. Response Code = " + conn.getResponseCode() + " (" + conn.getResponseMessage() + "):\r\n" + response); return response.toString(); }
Code Sample 2:
private static Long statusSWGCraftTime() { long current = System.currentTimeMillis() / 1000L; if (current < (previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY)) return previousStatusTime; URL url = null; try { synchronized (previousStatusTime) { if (current >= previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY) { url = SWGCraft.getStatusTextURL(); String statusTime = ZReader.read(url.openStream()); previousStatusTime = Long.valueOf(statusTime); previousStatusCheck = current; } return previousStatusTime; } } catch (UnknownHostException e) { SWGCraft.showUnknownHostDialog(url, e); } catch (Throwable e) { SWGAide.printDebug("cmgr", 1, "SWGResourceManager:statusSWGCraftTime:", e.toString()); } return Long.valueOf(0); }
|
11
|
Code Sample 1:
public void xtest1() throws Exception { InputStream input = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream tmp = new ITextManager().cut(input, 3, 8); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input.close(); tmp.close(); output.close(); }
Code Sample 2:
public void write(File file) throws Exception { if (medooFile != null) { if (!medooFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(medooFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } }
|
11
|
Code Sample 1:
public static byte[] expandPasswordToKeySSHCom(String password, int keyLen) { try { if (password == null) { password = ""; } MessageDigest md5 = MessageDigest.getInstance("MD5"); int digLen = md5.getDigestLength(); byte[] buf = new byte[((keyLen + digLen) / digLen) * digLen]; int cnt = 0; while (cnt < keyLen) { md5.update(password.getBytes()); if (cnt > 0) { md5.update(buf, 0, cnt); } md5.digest(buf, cnt, digLen); cnt += digLen; } byte[] key = new byte[keyLen]; System.arraycopy(buf, 0, key, 0, keyLen); return key; } catch (Exception e) { throw new Error("Error in SSH2KeyPairFile.expandPasswordToKeySSHCom: " + e); } }
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 String createMD5(String str) { String sig = null; String strSalt = str + sSalt; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(strSalt.getBytes(), 0, strSalt.length()); byte byteData[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } sig = sb.toString(); } catch (NoSuchAlgorithmException e) { System.err.println("Can not use md5 algorithm"); } return sig; }
Code Sample 2:
public String digest(String algorithm, String text) { MessageDigest digester = null; try { digester = MessageDigest.getInstance(algorithm); digester.update(text.getBytes(Digester.ENCODING)); } catch (NoSuchAlgorithmException nsae) { _log.error(nsae, nsae); } catch (UnsupportedEncodingException uee) { _log.error(uee, uee); } byte[] bytes = digester.digest(); if (_BASE_64) { return Base64.encode(bytes); } else { return new String(Hex.encodeHex(bytes)); } }
|
11
|
Code Sample 1:
public String getResourceAsString(String name) throws IOException { String content = null; InputStream stream = aClass.getResourceAsStream(name); if (stream != null) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copyAndClose(stream, buffer); content = buffer.toString(); } else { Assert.fail("Resource not available: " + name); } return content; }
Code Sample 2:
public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } }
|
11
|
Code Sample 1:
public void testMemberSeek() throws IOException { GZIPMembersInputStream gzin = new GZIPMembersInputStream(new ByteArrayInputStream(allfour_gz)); gzin.setEofEachMember(true); gzin.compressedSeek(noise1k_gz.length + noise32k_gz.length); int count2 = IOUtils.copy(gzin, new NullOutputStream()); assertEquals("wrong 1-byte member count", 1, count2); assertEquals("wrong Member2 start", noise1k_gz.length + noise32k_gz.length, gzin.getCurrentMemberStart()); assertEquals("wrong Member2 end", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberEnd()); gzin.nextMember(); int count3 = IOUtils.copy(gzin, new NullOutputStream()); assertEquals("wrong 5-byte member count", 5, count3); assertEquals("wrong Member3 start", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberStart()); assertEquals("wrong Member3 end", noise1k_gz.length + noise32k_gz.length + a_gz.length + hello_gz.length, gzin.getCurrentMemberEnd()); gzin.nextMember(); int countEnd = IOUtils.copy(gzin, new NullOutputStream()); assertEquals("wrong eof count", 0, countEnd); }
Code Sample 2:
public void run() { XmlFilesFilter filter = new XmlFilesFilter(); String pathTemp = Settings.get("vo_store.databaseMetaCollection"); String sectionName = pathTemp.substring(1, pathTemp.indexOf("/", 2)); String templateName = VOAccess.getElementByName(settingsDB, "TEMPLATE", sectionName); String schemaName = VOAccess.getElementByName(settingsDB, "SCHEMA", sectionName); byte[] buf = new byte[1024]; Hashtable templateElements = null; try { URL xmlTemplateUrl = new URL(httpURI + settingsDB + "/" + templateName); URL getDocPathsAndValuesXslUrl = new URL(httpURI + settingsDB + "/" + "getDocPathsValuesAndDisplays.xsl"); org.w3c.dom.Document curTemplateXml = VOAccess.readDocument(xmlTemplateUrl); DOMResult templateResult = new DOMResult(); InputStream tempInput = getDocPathsAndValuesXslUrl.openStream(); javax.xml.transform.sax.SAXSource tempXslSource = new javax.xml.transform.sax.SAXSource(new org.xml.sax.InputSource(tempInput)); Transformer trans = TransformerFactory.newInstance().newTransformer(tempXslSource); trans.setParameter("schemaUrl", httpURI + settingsDB + "/" + schemaName); trans.transform(new javax.xml.transform.dom.DOMSource(curTemplateXml), templateResult); tempInput.close(); templateElements = VOAccess.displaysToHashtable(templateResult); ((CollectionManagementService) CollectionsManager.getService(xmldbURI + rootDB, false, "CollectionManager")).createCollection(rootDB + pathTemp); } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); } while (true) { File[] fileList = sourceMetaFilesDir.listFiles(filter); for (int i = 0; i < Math.min(fileList.length, 500); i++) { File newFile = fileList[i]; try { Document metaDoc = build.build(newFile); Element metaElm = metaDoc.getRootElement(); String dataFileName = metaElm.getChildText("Content"), previewFileName = metaElm.getChildText("Preview"); String objId = VOAccess.getUniqueId(); metaElm.getChild("Content").setText("videostore?type=doc&objId=" + objId); metaElm.getChild("Preview").setText("videostore?type=preview&objId=" + objId); boolean found = false; for (Iterator it = sourceDataFilesDirs.iterator(); it.hasNext() && !found; ) { String sourceDataFilesDir = (String) it.next(); File dataInput = new File(sourceDataFilesDir + "/" + dataFileName); if (dataInput.exists()) { found = true; BufferedInputStream inp = new BufferedInputStream(new FileInputStream(dataInput)); FileOutputStream outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".dat")); int read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); dataInput = new File(sourceDataFilesDir + "/" + previewFileName); inp = new BufferedInputStream(new FileInputStream(dataInput)); outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".jpg")); read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); curDirWriteTo++; if (curDirWriteTo >= targetDataFilesDirs.size()) { curDirWriteTo = 0; } } } if (!found) { newFile.renameTo(new File(newFile.getAbsolutePath() + ".not_found")); } else { String title = getValueByPath((String) templateElements.get("title"), metaDoc.getRootElement()); String description = getValueByPath((String) templateElements.get("description"), metaDoc.getRootElement()); String onlink = ""; if (null != templateElements.get("onlink")) { onlink = getValueByPath((String) templateElements.get("onlink"), metaDoc.getRootElement()); } String ncover = ""; if (null != templateElements.get("ncover")) { ncover = getValueByPath((String) templateElements.get("ncover"), metaDoc.getRootElement()); } String wcover = ""; if (null != templateElements.get("wcover")) { wcover = getValueByPath((String) templateElements.get("wcover"), metaDoc.getRootElement()); } String ecover = ""; if (null != templateElements.get("ecover")) { ecover = getValueByPath((String) templateElements.get("ecover"), metaDoc.getRootElement()); } String scover = ""; if (null != templateElements.get("scover")) { scover = getValueByPath((String) templateElements.get("scover"), metaDoc.getRootElement()); } String datefrom = ""; if (null != templateElements.get("datefrom")) { datefrom = getValueByPath((String) templateElements.get("datefrom"), metaDoc.getRootElement()); } String dateto = ""; if (null != templateElements.get("dateto")) { dateto = getValueByPath((String) templateElements.get("dateto"), metaDoc.getRootElement()); } String previewimg = ""; if (null != templateElements.get("previewimg")) { previewimg = getValueByPath((String) templateElements.get("previewimg"), metaDoc.getRootElement()); } String discRestr = "false"; String votingRestr = "false"; datefrom = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); dateto = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); Hashtable discussionFields = new Hashtable(); discussionFields.put("OBJECT_ID", objId); discussionFields.put("AUTHOR_ID", "auto"); discussionFields.put("AUTHOR_NAME", "auto"); discussionFields.put("OBJECT_SECTION", sectionName); discussionFields.put("OBJECT_PATH", pathTemp); discussionFields.put("FILE_PATH", ""); discussionFields.put("TITLE", title); discussionFields.put("DESCRIPTION", description); discussionFields.put("ONLINK", onlink); discussionFields.put("NCOVER", ncover); discussionFields.put("ECOVER", ecover); discussionFields.put("SCOVER", scover); discussionFields.put("WCOVER", wcover); discussionFields.put("PERIOD_START", datefrom); discussionFields.put("PERIOD_END", dateto); discussionFields.put("PREVIEW_IMG", previewimg); discussionFields.put("DISCUSSRESTRICTION", discRestr); discussionFields.put("VOTINGRESTRICTION", votingRestr); VOAccess.createDiscussionFile(discussionFields); VOAccess.updateLastItem(objId, sectionName); Collection col = CollectionsManager.getCollection(rootDB + pathTemp, true); XMLResource document = (XMLResource) col.createResource(objId + ".xml", XMLResource.RESOURCE_TYPE); document.setContent(outXml.outputString(metaElm)); col.storeResource(document); Indexer.index(objId); newFile.delete(); } } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); newFile.renameTo(new File(newFile.getAbsolutePath() + ".bad")); } } try { this.sleep(600000); } catch (InterruptedException ex1) { ex1.printStackTrace(); } } }
|
11
|
Code Sample 1:
@Override protected void copy(InputStream inputs, OutputStream outputs) throws IOException { if (outputs == null) { throw new NullPointerException(); } if (inputs == null) { throw new NullPointerException(); } ZipOutputStream zipoutputs = null; try { zipoutputs = new ZipOutputStream(outputs); zipoutputs.putNextEntry(new ZipEntry("default")); IOUtils.copy(inputs, zipoutputs); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (zipoutputs != null) { zipoutputs.close(); } if (inputs != null) { inputs.close(); } } }
Code Sample 2:
public static void copy(File src, File dst) throws IOException { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { srcChannel.close(); } finally { dstChannel.close(); } } }
|
00
|
Code Sample 1:
public boolean processFtp(String serverIp, int port, String user, String password, String synchrnPath, String filePath, File[] uploadFile) throws Exception { boolean upload = false; try { FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("euc-kr"); if (!EgovWebUtil.isIPAddress(serverIp)) { throw new RuntimeException("IP is needed. (" + serverIp + ")"); } InetAddress host = InetAddress.getByName(serverIp); ftpClient.connect(host, port); if (!ftpClient.login(user, password)) throw new Exception("FTP Client Login Error : \n"); if (synchrnPath.length() != 0) ftpClient.changeWorkingDirectory(synchrnPath); FTPFile[] fTPFile = ftpClient.listFiles(synchrnPath); FileInputStream fis = null; try { for (int i = 0; i < uploadFile.length; i++) { if (uploadFile[i].isFile()) { if (!isExist(fTPFile, uploadFile[i])) { fis = new FileInputStream(uploadFile[i]); ftpClient.storeFile(synchrnPath + uploadFile[i].getName(), fis); } if (fis != null) { fis.close(); } } } fTPFile = ftpClient.listFiles(synchrnPath); deleteFtpFile(ftpClient, fTPFile, uploadFile); upload = true; } catch (IOException ex) { System.out.println(ex); } finally { if (fis != null) try { fis.close(); } catch (IOException ignore) { System.out.println("IGNORE: " + ignore); } } ftpClient.logout(); } catch (Exception e) { System.out.println(e); upload = false; } return upload; }
Code Sample 2:
private void retrieveClasses(URL url, Map<String, T> cmds) { try { String resource = URLDecoder.decode(url.getPath(), "UTF-8"); File directory = new File(resource); if (directory.exists()) { String[] files = directory.list(); for (String file : files) { if (file.endsWith(".class")) { addInstanceIfCommand(pckgname + '.' + file.substring(0, file.length() - 6), cmds); } } } else { JarURLConnection con = (JarURLConnection) url.openConnection(); String starts = con.getEntryName(); Enumeration<JarEntry> entriesEnum = con.getJarFile().entries(); while (entriesEnum.hasMoreElements()) { ZipEntry entry = (ZipEntry) entriesEnum.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) { classname = classname.substring(1); } classname = classname.replace('/', '.'); addInstanceIfCommand(classname, cmds); } } } } catch (IOException ioe) { LOG.warning("couldn't retrieve classes of " + url + ". Reason: " + ioe); } }
|
00
|
Code Sample 1:
public static boolean downloadFile(String url, String destination) throws Exception { BufferedInputStream bi = null; BufferedOutputStream bo = null; File destfile; byte BUFFER[] = new byte[100]; java.net.URL fileurl; URLConnection conn; fileurl = new java.net.URL(url); conn = fileurl.openConnection(); long fullsize = conn.getContentLength(); long onepercent = fullsize / 100; MessageFrame.setTotalDownloadSize(fullsize); bi = new BufferedInputStream(conn.getInputStream()); destfile = new File(destination); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); int read = 0; int sum = 0; long i = 0; while ((read = bi.read(BUFFER)) != -1) { bo.write(BUFFER, 0, read); sum += read; i += read; if (i > onepercent) { i = 0; MessageFrame.setDownloadProgress(sum); } } bi.close(); bo.close(); MessageFrame.setDownloadProgress(fullsize); return true; }
Code Sample 2:
public void readURL(URL url) throws IOException, ParserConfigurationException, SAXException { URLConnection connection; if (proxy == null) { connection = url.openConnection(); } else { connection = url.openConnection(proxy); } connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); connection.connect(); InputStream in = connection.getInputStream(); readInputStream(in); }
|
00
|
Code Sample 1:
public void testLocalUserAccountLocalRemoteRoles() throws SQLException { Statement st = null; Connection authedCon = null; try { saSt.executeUpdate("CREATE USER tlualrr PASSWORD 'wontuse'"); saSt.executeUpdate("GRANT role3 TO tlualrr"); saSt.executeUpdate("GRANT role4 TO tlualrr"); saSt.executeUpdate("SET DATABASE AUTHENTICATION FUNCTION EXTERNAL NAME " + "'CLASSPATH:" + getClass().getName() + ".twoRolesFn'"); try { authedCon = DriverManager.getConnection(jdbcUrl, "TLUALRR", "unusedPassword"); } catch (SQLException se) { fail("Access with 'twoRolesFn' failed"); } st = authedCon.createStatement(); assertFalse("Positive test #1 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t1 VALUES(1)")); assertFalse("Positive test #2 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t2 VALUES(2)")); assertTrue("Negative test #3 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t3 VALUES(3)")); assertTrue("Negative test #4 failed", AuthFunctionUtils.updateDoesThrow(st, "INSERT INTO t4 VALUES(4)")); assertEquals(twoRolesSet, AuthUtils.getEnabledRoles(authedCon)); } finally { if (st != null) try { st.close(); } catch (SQLException se) { logger.error("Close of Statement failed:" + se); } finally { st = null; } if (authedCon != null) try { authedCon.rollback(); authedCon.close(); } catch (SQLException se) { logger.error("Close of Authed Conn. failed:" + se); } finally { authedCon = null; } } }
Code Sample 2:
private HttpsURLConnection setUpConnection(URL url) throws NoSuchAlgorithmException, KeyManagementException, IOException { HttpsURLConnection openConnection = (HttpsURLConnection) url.openConnection(); openConnection.setAllowUserInteraction(true); openConnection.setUseCaches(false); openConnection.setDoInput(true); openConnection.setDoOutput(true); SSLContext sc = SSLContext.getInstance(SSL_PROTOCOL); sc.init(new KeyManager[] { new MyKeyManager() }, new TrustManager[] { new BypassTrustManager() }, null); openConnection.setSSLSocketFactory(sc.getSocketFactory()); return openConnection; }
|
11
|
Code Sample 1:
public static boolean copyFile(final File fileFrom, final File fileTo) { assert fileFrom != null : "fileFrom is null"; assert fileTo != null : "fileTo is null"; LOGGER.info(buildLogString(COPY_FILE_INFO, new Object[] { fileFrom, fileTo })); boolean error = true; FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(fileFrom); outputStream = new FileOutputStream(fileTo); final FileChannel inChannel = inputStream.getChannel(); final FileChannel outChannel = outputStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); error = false; } catch (final IOException e) { LOGGER.log(SEVERE, buildLogString(COPY_FILE_ERROR, new Object[] { fileFrom, fileTo }), e); } finally { closeCloseable(inputStream, fileFrom); closeCloseable(outputStream, fileTo); } return error; }
Code Sample 2:
@Test public void testWrite() { System.out.println("write"); final File[] files = { new File(sharePath) }; System.out.println("Creating hash..."); String initHash = MD5File.MD5Directory(files[0]); System.out.println("Hash: " + initHash); Share readShare = ShareUtility.createShare(files, "TestShare"); System.out.println("Creating shares..."); final ShareFolder[] readers = ShareUtility.cropShareToParts(readShare, PARTS); System.out.println("Reading and writing shares..."); done = 0; for (int i = 0; i < PARTS; i++) { final int j = i; new Thread() { public void run() { ShareFolder part = (ShareFolder) ObjectClone.clone(readers[j]); ShareFileReader reader = new ShareFileReader(readers[j], files[0]); ShareFileWriter writer = new ShareFileWriter(part, new File("Downloads/" + readers[j].getName())); long tot = 0; byte[] b = new byte[(int) (Math.random() * 10000)]; while (tot < readers[j].getSize()) { reader.read(b); byte[] bwrite = new byte[(int) (Math.random() * 10000) + b.length]; System.arraycopy(b, 0, bwrite, 0, b.length); writer.write(bwrite, b.length); tot += b.length; } done++; System.out.println((int) (done * 100.0 / PARTS) + "% Complete"); } }.start(); } while (done < PARTS) { Thread.yield(); } File resultFile = new File("Downloads/" + readShare.getName()); System.out.println("Creating hash of written share..."); String resultHash = MD5File.MD5Directory(resultFile); System.out.println("Init hash: " + initHash); System.out.println("Result hash: " + resultHash); assertEquals(initHash, resultHash); }
|
00
|
Code Sample 1:
public void updateUserInfo(AuthSession authSession, AuthUserExtendedInfo infoAuth) { log.info("Start update auth"); PreparedStatement ps = null; DatabaseAdapter db = null; try { db = DatabaseAdapter.getInstance(); String sql = "update WM_AUTH_USER " + "set " + "ID_FIRM=?, IS_USE_CURRENT_FIRM=?, " + "ID_HOLDING=?, IS_HOLDING=? " + "WHERE ID_AUTH_USER=? "; ps = db.prepareStatement(sql); if (infoAuth.getAuthInfo().getCompanyId() == null) { ps.setNull(1, Types.INTEGER); ps.setInt(2, 0); } else { ps.setLong(1, infoAuth.getAuthInfo().getCompanyId()); ps.setInt(2, infoAuth.getAuthInfo().isCompany() ? 1 : 0); } if (infoAuth.getAuthInfo().getHoldingId() == null) { ps.setNull(3, Types.INTEGER); ps.setInt(4, 0); } else { ps.setLong(3, infoAuth.getAuthInfo().getHoldingId()); ps.setInt(4, infoAuth.getAuthInfo().isHolding() ? 1 : 0); } ps.setLong(5, infoAuth.getAuthInfo().getAuthUserId()); ps.executeUpdate(); processDeletedRoles(db, infoAuth); processNewRoles(db, infoAuth.getRoles(), infoAuth.getAuthInfo().getAuthUserId()); db.commit(); } catch (Throwable e) { try { if (db != null) db.rollback(); } catch (Exception e001) { } final String es = "Error add user auth"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(db, ps); ps = null; db = null; log.info("End update auth"); } }
Code Sample 2:
protected List webservice(URL url, List locations, boolean followRedirect) throws GeoServiceException { long start = System.currentTimeMillis(); int rowCount = 0, hitCount = 0; try { HttpURLConnection con; try { con = (HttpURLConnection) url.openConnection(); try { con.getClass().getMethod("setConnectTimeout", new Class[] { Integer.TYPE }).invoke(con, new Object[] { TIMEOUT }); } catch (Throwable t) { LOG.info("can't set connection timeout"); } con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); Writer out = new OutputStreamWriter(con.getOutputStream(), UTF8); out.write(HEADER + "\n"); for (int i = 0; i < locations.size(); i++) { if (i > 0) out.write("\n"); out.write(encode((GeoLocation) locations.get(i))); } out.close(); } catch (IOException e) { throw new GeoServiceException("Accessing GEO Webservice failed", e); } List rows = new ArrayList(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), UTF8)); for (int l = 0; l < locations.size(); l++) { String line = in.readLine(); LOG.finer(line); if (line == null) break; if (l == 0 && followRedirect) { try { return webservice(new URL(line), locations, false); } catch (MalformedURLException e) { } } rowCount++; List row = new ArrayList(); if (!line.startsWith("?")) { StringTokenizer hits = new StringTokenizer(line, ";"); while (hits.hasMoreTokens()) { GeoLocation hit = decode(hits.nextToken()); if (hit != null) { row.add(hit); hitCount++; } } } rows.add(row); } in.close(); } catch (IOException e) { throw new GeoServiceException("Reading from GEO Webservice failed", e); } if (rows.size() < locations.size()) throw new GeoServiceException("GEO Webservice returned " + rows.size() + " rows for " + locations.size() + " locations"); return rows; } finally { long secs = (System.currentTimeMillis() - start) / 1000; LOG.fine("query for " + locations.size() + " locations in " + secs + "s resulted in " + rowCount + " rows and " + hitCount + " total hits"); } }
|
00
|
Code Sample 1:
protected byte[] computeHash() { try { final MessageDigest inputHash = MessageDigest.getInstance("SHA"); inputHash.update(bufferFileData().getBytes()); return inputHash.digest(); } catch (final NoSuchAlgorithmException nsae) { lastException = nsae; return new byte[0]; } catch (final IOException ioe) { lastException = ioe; return new byte[0]; } }
Code Sample 2:
public static boolean saveMap(LWMap map, boolean saveAs, boolean export) { Log.info("saveMap: " + map); GUI.activateWaitCursor(); if (map == null) return false; File file = map.getFile(); int response = -1; if (map.getSaveFileModelVersion() == 0) { final Object[] defaultOrderButtons = { VueResources.getString("saveaction.saveacopy"), VueResources.getString("saveaction.save") }; Object[] messageObject = { map.getLabel() }; response = VueUtil.option(VUE.getDialogParent(), VueResources.getFormatMessage(messageObject, "dialog.saveaction.message"), VueResources.getFormatMessage(messageObject, "dialog.saveaction.title"), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, defaultOrderButtons, VueResources.getString("saveaction.saveacopy")); } if (response == 0) { saveAs = true; } if ((saveAs || file == null) && !export) { file = ActionUtil.selectFile("Save Map", null); } else if (export) { file = ActionUtil.selectFile("Export Map", "export"); } if (file == null) { try { return false; } finally { GUI.clearWaitCursor(); } } try { Log.info("saveMap: target[" + file + "]"); final String name = file.getName().toLowerCase(); if (name.endsWith(".rli.xml")) { new IMSResourceList().convert(map, file); } else if (name.endsWith(".xml") || name.endsWith(".vue")) { ActionUtil.marshallMap(file, map); } else if (name.endsWith(".jpeg") || name.endsWith(".jpg")) ImageConversion.createActiveMapJpeg(file, VueResources.getDouble("imageExportFactor")); else if (name.endsWith(".png")) ImageConversion.createActiveMapPng(file, VueResources.getDouble("imageExportFactor")); else if (name.endsWith(".svg")) SVGConversion.createSVG(file); else if (name.endsWith(".pdf")) { PresentationNotes.createMapAsPDF(file); } else if (name.endsWith(".zip")) { Vector resourceVector = new Vector(); Iterator i = map.getAllDescendents(LWComponent.ChildKind.PROPER).iterator(); while (i.hasNext()) { LWComponent component = (LWComponent) i.next(); System.out.println("Component:" + component + " has resource:" + component.hasResource()); if (component.hasResource() && (component.getResource() instanceof URLResource)) { URLResource resource = (URLResource) component.getResource(); try { if (resource.isLocalFile()) { String spec = resource.getSpec(); System.out.println(resource.getSpec()); Vector row = new Vector(); row.add(new Boolean(true)); row.add(resource); row.add(new Long(file.length())); row.add("Ready"); resourceVector.add(row); } } catch (Exception ex) { System.out.println("Publisher.setLocalResourceVector: Resource " + resource.getSpec() + ex); ex.printStackTrace(); } } } File savedCMap = PublishUtil.createZip(map, resourceVector); InputStream istream = new BufferedInputStream(new FileInputStream(savedCMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(file)); int fileLength = (int) savedCMap.length(); byte bytes[] = new byte[fileLength]; try { while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); } catch (Exception e) { e.printStackTrace(); } finally { istream.close(); ostream.close(); } } else if (name.endsWith(".html")) { HtmlOutputDialog hod = new HtmlOutputDialog(); hod.setVisible(true); if (hod.getReturnVal() > 0) new ImageMap().createImageMap(file, hod.getScale(), hod.getFormat()); } else if (name.endsWith(".rdf")) { edu.tufts.vue.rdf.RDFIndex index = new edu.tufts.vue.rdf.RDFIndex(); String selectionType = VueResources.getString("rdf.export.selection"); if (selectionType.equals("ALL")) { Iterator<LWMap> maps = VUE.getLeftTabbedPane().getAllMaps(); while (maps.hasNext()) { index.index(maps.next()); } } else if (selectionType.equals("ACTIVE")) { index.index(VUE.getActiveMap()); } else { index.index(VUE.getActiveMap()); } FileWriter writer = new FileWriter(file); index.write(writer); writer.close(); } else if (name.endsWith(VueUtil.VueArchiveExtension)) { Archive.writeArchive(map, file); } else { Log.warn("Unknown save type for filename extension: " + name); return false; } Log.debug("Save completed for " + file); if (!VUE.isApplet()) { VueFrame frame = (VueFrame) VUE.getMainWindow(); String title = VUE.getName() + ": " + name; frame.setTitle(title); } if (name.endsWith(".vue")) { RecentlyOpenedFilesManager rofm = RecentlyOpenedFilesManager.getInstance(); rofm.updateRecentlyOpenedFiles(file.getAbsolutePath()); } return true; } catch (Throwable t) { Log.error("Exception attempting to save file " + file + ": " + t); Throwable e = t; if (t.getCause() != null) e = t.getCause(); if (e instanceof java.io.FileNotFoundException) { Log.error("Save Failed: " + e); } else { Log.error("Save failed for \"" + file + "\"; ", e); } if (e != t) Log.error("Exception attempting to save file " + file + ": " + e); VueUtil.alert(String.format(Locale.getDefault(), VueResources.getString("saveaction.savemap.error") + "\"%s\";\n" + VueResources.getString("saveaction.targetfiel") + "\n\n" + VueResources.getString("saveaction.problem"), map.getLabel(), file, Util.formatLines(e.toString(), 80)), "Problem Saving Map"); } finally { GUI.invokeAfterAWT(new Runnable() { public void run() { GUI.clearWaitCursor(); } }); } return false; }
|
11
|
Code Sample 1:
public static final long copyFile(final File srcFile, final File dstFile, final long cpySize) throws IOException { if ((null == srcFile) || (null == dstFile)) return (-1L); final File dstFolder = dstFile.getParentFile(); if ((!dstFolder.exists()) && (!dstFolder.mkdirs())) throw new IOException("Failed to created destination folder(s)"); FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); dstChannel = new FileOutputStream(dstFile).getChannel(); final long srcLen = srcFile.length(), copyLen = dstChannel.transferFrom(srcChannel, 0, (cpySize < 0L) ? srcLen : cpySize); if ((cpySize < 0L) && (copyLen != srcLen)) return (-2L); return copyLen; } finally { FileUtil.closeAll(srcChannel, dstChannel); } }
Code Sample 2:
public void save(InputStream is) throws IOException { File dest = Config.getDataFile(getInternalDate(), getPhysMessageID()); OutputStream os = null; try { os = new FileOutputStream(dest); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } }
|
11
|
Code Sample 1:
public final boolean login(String user, String pass) { if (user == null || pass == null) return false; connectionInfo.setData("com.tensegrity.palojava.pass#" + user, pass); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); pass = asHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { throw new PaloException("Failed to create encrypted password for " + "user '" + user + "'!", ex); } connectionInfo.setUser(user); connectionInfo.setPassword(pass); return loginInternal(user, pass); }
Code Sample 2:
public String login(HttpSession callingSession, String username, String password) { String token = null; String customer = null; int timeoutInSeconds = 0; HashSet<Integer> tileProviderIds = new HashSet<Integer>(); boolean bLoginOk = false; String dbPassword = (String) em.createNamedQuery("getCustomerPasswordByUsername").setParameter("username", username).getSingleResult(); if (dbPassword.equals(password)) { CustomerElement ce = (CustomerElement) em.createNamedQuery("getCustomerByUsername").setParameter("username", username).getSingleResult(); customer = ce.getName(); timeoutInSeconds = ce.getTimeout(); String[] tileProviderIdsArray = ce.getTileProvideridsArray(); for (String tileProviderId : tileProviderIdsArray) tileProviderIds.add(Integer.parseInt(tileProviderId)); bLoginOk = true; } if (bLoginOk) { token = SessionHandler.getInstance().alreadyGotValidSession(customer); if (token == null) { Random random = new Random(); token = callingSession.getId() + new Date().getTime() + random.nextLong(); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Unable to digest the token.", e); } md5.update(token.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)); } token = sb.toString(); SessionHandler.getInstance().registerValidSession(token, customer, timeoutInSeconds, tileProviderIds); } } return token; }
|
11
|
Code Sample 1:
public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
private void checkRoundtrip(byte[] content) throws Exception { InputStream in = new ByteArrayInputStream(content); ByteArrayOutputStream out = new ByteArrayOutputStream(); CodecUtil.encodeQuotedPrintableBinary(in, out); in = new QuotedPrintableInputStream(new ByteArrayInputStream(out.toByteArray())); out = new ByteArrayOutputStream(); IOUtils.copy(in, out); assertEquals(content, out.toByteArray()); }
Code Sample 2:
public ZIPSignatureService(InputStream documentInputStream, SignatureFacet signatureFacet, OutputStream documentOutputStream, RevocationDataService revocationDataService, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".zip"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new ZIPSignatureFacet(this.tmpFile, signatureDigestAlgo)); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm()); xadesSignatureFacet.setRole(role); addSignatureFacet(xadesSignatureFacet); addSignatureFacet(new KeyInfoSignatureFacet(true, false, false)); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
|
00
|
Code Sample 1:
public static InputStream downloadStream(URL url) { InputStream inputStream = null; try { URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setFollowRedirects(true); httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) return null; } return urlConnection.getInputStream(); } catch (Exception ex) { try { inputStream.close(); } catch (Exception ex1) { } return null; } }
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; }
|
00
|
Code Sample 1:
public static boolean writeFileByChars(Reader pReader, File pFile, boolean pAppend) { boolean flag = false; try { FileWriter fw = new FileWriter(pFile, pAppend); IOUtils.copy(pReader, fw); fw.flush(); fw.close(); pReader.close(); flag = true; } catch (Exception e) { LOG.error("将字符流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; }
Code Sample 2:
private String fetchHtml(URL url) throws IOException { URLConnection connection; if (StringUtils.isNotBlank(proxyHost) && proxyPort != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(proxyHost, proxyPort)); connection = url.openConnection(proxy); } else { connection = url.openConnection(); } Object content = connection.getContent(); if (content instanceof InputStream) { return IOUtils.toString(InputStream.class.cast(content)); } else { String msg = "Bad content type! " + content.getClass(); log.error(msg); throw new IOException(msg); } }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private void createWar() throws IOException, XMLStreamException { String appName = this.fileout.getName(); int i = appName.indexOf("."); if (i != -1) appName = appName.substring(0, i); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(this.fileout)); { ZipEntry entry = new ZipEntry("WEB-INF/web.xml"); zout.putNextEntry(entry); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter w = factory.createXMLStreamWriter(zout, "ASCII"); w.writeStartDocument("ASCII", "1.0"); w.writeStartElement("web-app"); w.writeAttribute("xsi", XSI, "schemaLocation", "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml /ns/javaee/web-app_2_5.xsd"); w.writeAttribute("version", "2.5"); w.writeAttribute("xmlns", J2EE); w.writeAttribute("xmlns:xsi", XSI); w.writeStartElement("description"); w.writeCharacters("Site maintenance for " + appName); w.writeEndElement(); w.writeStartElement("display-name"); w.writeCharacters(appName); w.writeEndElement(); w.writeStartElement("servlet"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("jsp-file"); w.writeCharacters("/WEB-INF/jsp/down.jsp"); w.writeEndElement(); w.writeEndElement(); w.writeStartElement("servlet-mapping"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("url-pattern"); w.writeCharacters("/*"); w.writeEndElement(); w.writeEndElement(); w.writeEndElement(); w.writeEndDocument(); w.flush(); zout.closeEntry(); } { ZipEntry entry = new ZipEntry("WEB-INF/jsp/down.jsp"); zout.putNextEntry(entry); PrintWriter w = new PrintWriter(zout); if (this.messageFile != null) { IOUtils.copyTo(new FileReader(this.messageFile), w); } else if (this.messageString != null) { w.print("<html><body>" + this.messageString + "</body></html>"); } else { w.print("<html><body><div style='text-align:center;font-size:500%;'>Oh No !<br/><b>" + appName + "</b><br/>is down for maintenance!</div></body></html>"); } w.flush(); zout.closeEntry(); } zout.finish(); zout.flush(); zout.close(); }
|
00
|
Code Sample 1:
private boolean subtitleDownload(Movie movie, File movieFile, File subtitleFile) { try { String ret; String xml; String moviehash = getHash(movieFile); String moviebytesize = String.valueOf(movieFile.length()); xml = generateXMLRPCSS(moviehash, moviebytesize); ret = sendRPC(xml); String subDownloadLink = getValue("SubDownloadLink", ret); if (subDownloadLink.equals("")) { String moviefilename = movieFile.getName(); if (!(moviefilename.toUpperCase().endsWith(".M2TS") && moviefilename.startsWith("0"))) { String subfilename = subtitleFile.getName(); int index = subfilename.lastIndexOf("."); String query = subfilename.substring(0, index); xml = generateXMLRPCSS(query); ret = sendRPC(xml); subDownloadLink = getValue("SubDownloadLink", ret); } } if (subDownloadLink.equals("")) { logger.finer("OpenSubtitles Plugin: Subtitle not found for " + movie.getBaseName()); return false; } logger.finer("OpenSubtitles Plugin: Download subtitle for " + movie.getBaseName()); URL url = new URL(subDownloadLink); HttpURLConnection connection = (HttpURLConnection) (url.openConnection()); connection.setRequestProperty("Connection", "Close"); InputStream inputStream = connection.getInputStream(); int code = connection.getResponseCode(); if (code != HttpURLConnection.HTTP_OK) { logger.severe("OpenSubtitles Plugin: Download Failed"); return false; } GZIPInputStream a = new GZIPInputStream(inputStream); OutputStream out = new FileOutputStream(subtitleFile); byte buf[] = new byte[1024]; int len; while ((len = a.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); movie.setSubtitles(true); return true; } catch (Exception e) { logger.severe("OpenSubtitles Plugin: Download Exception (Movie Not Found)"); return false; } }
Code Sample 2:
public static String harvestForUser(Node userNode, String alias, Boolean all) { FTPClient client = new FTPClient(); OutputStream outStream = null; Calendar filterCal = Calendar.getInstance(); filterCal.set(Calendar.DAY_OF_MONTH, filterCal.get(Calendar.DAY_OF_MONTH) - 1); Date aDayAgo = filterCal.getTime(); String outputRecord = ""; try { Session session = CustomSystemSession.create(r); client.connect(ftpHostname); client.login(ftpUsername, ftpPassword); FTPFile[] users = client.listFiles(); if (users != null) { for (FTPFile user : users) { String userName = user.getName(); if (alias.equals(userName)) { outputRecord += "Found account " + userName + ".\n"; client.changeWorkingDirectory("/" + userName + "/"); FTPFile[] experiments = client.listFiles(); if (experiments != null && userNode != null) { for (FTPFile experiment : experiments) { String experimentName = experiment.getName(); outputRecord += "Exploring " + userName + "/" + experimentName + ".\n"; client.changeWorkingDirectory("/" + userName + "/" + experimentName + "/"); FTPFile[] datasets = client.listFiles(); if (datasets != null) { for (FTPFile dataset : datasets) { String datasetName = dataset.getName(); outputRecord += "Exploring " + userName + "/" + experimentName + "/" + datasetName + ".\n"; client.changeWorkingDirectory("/" + userName + "/" + experimentName + "/" + datasetName + "/"); Date collectionDate = dataset.getTimestamp().getTime(); if (collectionDate.after(aDayAgo) || all) { FTPFile[] images = client.listFiles(); if (images != null) { for (FTPFile image : images) { outputRecord += processImage(userName, experimentName, datasetName, collectionDate, image, client, userNode, session); } } } } } } } } } } client.logout(); } catch (IOException ioe) { log.info("Error communicating with FTP server."); log.error("Error communicating with FTP server.", ioe); ioe.printStackTrace(); } catch (RepositoryException ioe) { log.info("Error communicating with repository."); log.error("Error communicating with repository.", ioe); ioe.printStackTrace(); } finally { IOUtils.closeQuietly(outStream); try { client.disconnect(); } catch (IOException e) { log.error("Problem disconnecting from FTP server", e); } } return outputRecord; }
|
11
|
Code Sample 1:
public boolean visar() throws SQLException, ClassNotFoundException, Exception { Connection conn = null; PreparedStatement ps = null; Date fechaSystem = new Date(); DateFormat aaaammdd = new SimpleDateFormat("yyyyMMdd"); DateFormat hhmmss = new SimpleDateFormat("HHmmss"); DateFormat sss = new SimpleDateFormat("S"); String ss = sss.format(fechaSystem); if (ss.length() > 2) { ss = ss.substring(0, 2); } boolean visado = false; try { conn = ToolsBD.getConn(); conn.setAutoCommit(false); String sentenciaSql = "UPDATE BZMODIF SET FZJCUSVI=?, FZJFVISA=?, FZJHVISA=?" + ((hayVisadoExtracto) ? ", FZJIEXTR=?" : "") + ((hayVisadoRemitente) ? ", FZJIREMI=?" : "") + " WHERE FZJCENSA='E' AND FZJCAGCO=? AND FZJNUMEN=? AND FZJANOEN=? AND FZJFMODI=? AND FZJHMODI=?"; ps = conn.prepareStatement(sentenciaSql); ps.setString(1, usuarioVisado); ps.setInt(2, Integer.parseInt(aaaammdd.format(fechaSystem))); ps.setInt(3, Integer.parseInt(hhmmss.format(fechaSystem) + ss)); int contador = 4; if (hayVisadoExtracto) { ps.setString(contador++, "X"); } if (hayVisadoRemitente) { ps.setString(contador++, "X"); } ps.setInt(contador++, oficina); ps.setInt(contador++, numeroRegistro); ps.setInt(contador++, anoEntrada); ps.setString(contador++, fechaModificacion); ps.setString(contador++, horaModificacion); int registrosAfectados = ps.executeUpdate(); if (registrosAfectados > 0 && !hayVisadoExtracto && !hayVisadoRemitente) { visado = true; } if (registrosAfectados > 0 && (hayVisadoExtracto || hayVisadoRemitente)) { boolean generado = generarBZVISAD(conn, Integer.parseInt(aaaammdd.format(fechaSystem)), Integer.parseInt(hhmmss.format(fechaSystem) + ss)); if (generado) { visado = actualizarBZENTRA(conn); } String rem = ""; String com = ""; if (hayVisadoRemitente) { if (!remitente.trim().equals("")) { rem = remitente; } else { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.ValoresHome"); ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class); Valores valor = home.create(); rem = valor.recuperaRemitenteCastellano(entidad1, entidad2 + ""); valor.remove(); } } else { if (!altres.trim().equals("")) { rem = remitente; } else { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.ValoresHome"); ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class); Valores valor = home.create(); rem = valor.recuperaRemitenteCastellano(entidad1Old, entidad2Old + ""); valor.remove(); } } if (hayVisadoExtracto) { com = extracto; } else { com = comentario; } try { Class t = Class.forName("es.caib.regweb.module.PluginHook"); Class[] partypes = { String.class, Integer.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class, Integer.class, Integer.class, String.class, Integer.class, String.class, String.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class }; Object[] params = { "V", new Integer(anoEntrada), new Integer(numeroRegistro), new Integer(oficina), new Integer(fechaDocumento), rem, com, tipoDocumento, new Integer(fechaRegistro), new Integer(fzacagge), fora, new Integer(destinatario), idioma, null, null, null, null, null, null, null }; java.lang.reflect.Method metodo = t.getMethod("entrada", partypes); metodo.invoke(null, params); } catch (IllegalAccessException iae) { } catch (IllegalArgumentException iae) { } catch (InvocationTargetException ite) { } catch (NullPointerException npe) { } catch (ExceptionInInitializerError eiie) { } catch (NoSuchMethodException nsme) { } catch (SecurityException se) { } catch (LinkageError le) { } catch (ClassNotFoundException le) { } } conn.commit(); int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss); String Stringsss = sss.format(fechaSystem); switch(Stringsss.length()) { case (1): Stringsss = "00" + Stringsss; break; case (2): Stringsss = "0" + Stringsss; break; } int horamili = Integer.parseInt(hhmmss.format(fechaSystem) + Stringsss); int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem)); logLopdBZMODIF("UPDATE", sessioEjb.getCallerPrincipal().getName().toUpperCase(), fzafsis, horamili, 'E', numeroRegistro, anoEntrada, oficina, Integer.parseInt(fechaModificacion), Integer.parseInt(horaModificacion)); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); visado = false; try { if (conn != null) conn.rollback(); else System.out.println("ERROR: No es pot fer rollback sense connexió!"); } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } } finally { ToolsBD.closeConn(conn, ps, null); } return visado; }
Code Sample 2:
public void anular() throws SQLException, ClassNotFoundException, Exception { Connection conn = null; PreparedStatement ms = null; try { conn = ToolsBD.getConn(); conn.setAutoCommit(false); String sentencia_delete = "DELETE FROM BZOFRENT " + " WHERE REN_OFANY=? AND REN_OFOFI=? AND REN_OFNUM=?"; ms = conn.prepareStatement(sentencia_delete); ms.setInt(1, anoOficio != null ? Integer.parseInt(anoOficio) : 0); ms.setInt(2, oficinaOficio != null ? Integer.parseInt(oficinaOficio) : 0); ms.setInt(3, numeroOficio != null ? Integer.parseInt(numeroOficio) : 0); int afectados = ms.executeUpdate(); if (afectados > 0) { registroActualizado = true; } else { registroActualizado = false; } conn.commit(); } catch (Exception ex) { System.out.println("Error inesperat, no s'ha desat el registre: " + ex.getMessage()); ex.printStackTrace(); registroActualizado = false; errores.put("", "Error inesperat, no s'ha desat el registre" + ": " + ex.getClass() + "->" + ex.getMessage()); try { if (conn != null) conn.rollback(); } catch (SQLException sqle) { throw new RemoteException("S'ha produït un error i no s'han pogut tornar enrere els canvis efectuats", sqle); } throw new RemoteException("Error inesperat, no s'ha modifcat el registre", ex); } finally { ToolsBD.closeConn(conn, ms, null); } }
|
00
|
Code Sample 1:
private void gravaOp(Vector<?> op) { PreparedStatement ps = null; String sql = null; ResultSet rs = null; int seqop = 0; Date dtFabrOP = null; try { sql = "SELECT MAX(SEQOP) FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { seqop = rs.getInt(1) + 1; } rs.close(); ps.close(); con.commit(); sql = "SELECT DTFABROP FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, txtSeqOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { dtFabrOP = rs.getDate(1); } rs.close(); ps.close(); con.commit(); sql = "INSERT INTO PPOP (CODEMP,CODFILIAL,CODOP,SEQOP,CODEMPPD,CODFILIALPD,CODPROD,SEQEST,DTFABROP," + "QTDPREVPRODOP,QTDFINALPRODOP,DTVALIDPDOP,CODEMPLE,CODFILIALLE,CODLOTE,CODEMPTM,CODFILIALTM,CODTIPOMOV," + "CODEMPAX,CODFILIALAX,CODALMOX,CODEMPOPM,CODFILIALOPM,CODOPM,SEQOPM,QTDDISTIOP,QTDSUGPRODOP)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, seqop); ps.setInt(5, Aplicativo.iCodEmp); ps.setInt(6, ListaCampos.getMasterFilial("PPESTRUTURA")); ps.setInt(7, ((Integer) op.elementAt(4)).intValue()); ps.setInt(8, ((Integer) op.elementAt(6)).intValue()); ps.setDate(9, dtFabrOP); ps.setFloat(10, ((BigDecimal) op.elementAt(7)).floatValue()); ps.setFloat(11, 0); ps.setDate(12, (Funcoes.strDateToSqlDate((String) op.elementAt(11)))); ps.setInt(13, Aplicativo.iCodEmp); ps.setInt(14, ListaCampos.getMasterFilial("EQLOTE")); ps.setString(15, ((String) op.elementAt(10))); ps.setInt(16, Aplicativo.iCodEmp); ps.setInt(17, ListaCampos.getMasterFilial("EQTIPOMOV")); ps.setInt(18, buscaTipoMov()); ps.setInt(19, ((Integer) op.elementAt(13)).intValue()); ps.setInt(20, ((Integer) op.elementAt(14)).intValue()); ps.setInt(21, ((Integer) op.elementAt(12)).intValue()); ps.setInt(22, Aplicativo.iCodEmp); ps.setInt(23, ListaCampos.getMasterFilial("PPOP")); ps.setInt(24, txtCodOP.getVlrInteger().intValue()); ps.setInt(25, txtSeqOP.getVlrInteger().intValue()); ps.setFloat(26, ((BigDecimal) op.elementAt(9)).floatValue()); ps.setFloat(27, ((BigDecimal) op.elementAt(7)).floatValue()); ps.executeUpdate(); ps.close(); con.commit(); geraRMA(seqop); } catch (SQLException e) { Funcoes.mensagemErro(null, "Erro ao gerar OP's de distribui��o!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException eb) { } } }
Code Sample 2:
public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); }
|
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 execute() { File sourceFile = new File(oarfilePath); File destinationFile = new File(deploymentDirectory + File.separator + sourceFile.getName()); try { FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destinationFile); byte[] readArray = new byte[2048]; while (fis.read(readArray) != -1) { fos.write(readArray); } fis.close(); fos.flush(); fos.close(); } catch (IOException ioe) { logger.severe("failed to copy the file:" + ioe); } }
|
00
|
Code Sample 1:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String version = req.getParameter("version"); String cdn = req.getParameter("cdn"); String dependencies = req.getParameter("dependencies"); String optimize = req.getParameter("optimize"); String cacheFile = null; String result = null; boolean isCached = false; Boolean isError = true; if (!version.equals("1.3.2")) { result = "invalid version: " + version; } if (!cdn.equals("google") && !cdn.equals("aol")) { result = "invalide CDN type: " + cdn; } if (!optimize.equals("comments") && !optimize.equals("shrinksafe") && !optimize.equals("none") && !optimize.equals("shrinksafe.keepLines")) { result = "invalid optimize type: " + optimize; } if (!dependencies.matches("^[\\w\\-\\,\\s\\.]+$")) { result = "invalid dependency list: " + dependencies; } try { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { result = e.getMessage(); } if (result == null) { md.update(dependencies.getBytes()); String digest = (new BASE64Encoder()).encode(md.digest()).replace('+', '~').replace('/', '_').replace('=', '_'); cacheFile = cachePath + "/" + version + "/" + cdn + "/" + digest + "/" + optimize + ".js"; File file = new File(cacheFile); if (file.exists()) { isCached = true; isError = false; } } if (result == null && !isCached) { BuilderContextAction contextAction = new BuilderContextAction(builderPath, version, cdn, dependencies, optimize); ContextFactory.getGlobal().call(contextAction); Exception exception = contextAction.getException(); if (exception != null) { result = exception.getMessage(); } else { result = contextAction.getResult(); FileUtil.writeToFile(cacheFile, result, null, true); isError = false; } } } catch (Exception e) { result = e.getMessage(); } res.setCharacterEncoding("utf-8"); if (isError) { result = result.replaceAll("\\\"", "\\\""); result = "<html><head><script type=\"text/javascript\">alert(\"" + result + "\");</script></head><body></body></html>"; PrintWriter writer = res.getWriter(); writer.append(result); } else { res.setHeader("Content-Type", "application/x-javascript"); res.setHeader("Content-disposition", "attachment; filename=dojo.js"); res.setHeader("Content-Encoding", "gzip"); File file = new File(cacheFile); BufferedInputStream in = new java.io.BufferedInputStream(new DataInputStream(new FileInputStream(file))); OutputStream out = res.getOutputStream(); byte[] bytes = new byte[64000]; int bytesRead = 0; while (bytesRead != -1) { bytesRead = in.read(bytes); if (bytesRead != -1) { out.write(bytes, 0, bytesRead); } } } }
Code Sample 2:
public void copy(final File source, final File dest) throws IOException { final FileInputStream in = new FileInputStream(source); try { final FileOutputStream out = new FileOutputStream(dest); try { final FileChannel inChannel = in.getChannel(); final FileChannel outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { out.close(); } } finally { in.close(); } }
|
11
|
Code Sample 1:
@Override public void render(IContentNode contentNode, Request req, Response resp, Application app, ServerInfo serverInfo) { Node fileNode = contentNode.getNode(); try { Node res = fileNode.getNode("jcr:content"); if (checkLastModified(res, req.getServletRequset(), resp.getServletResponse())) { return; } Property data = res.getProperty("jcr:data"); InputStream is = data.getBinary().getStream(); int contentLength = (int) data.getBinary().getSize(); String mime; if (res.hasProperty("jcr:mimeType")) { mime = res.getProperty("jcr:mimeType").getString(); } else { mime = serverInfo.getSerlvetContext().getMimeType(fileNode.getName()); } if (mime != null && mime.startsWith("image")) { int w = req.getInt("w", 0); int h = req.getInt("h", 0); String fmt = req.get("fmt"); if (w != 0 || h != 0 || fmt != null) { Resource imgRes = ImageResource.create(is, mime.substring(6), w, h, req.getInt("cut", 0), fmt); imgRes.process(serverInfo); return; } } resp.getServletResponse().setContentType(mime); resp.getServletResponse().setContentLength(contentLength); OutputStream os = resp.getServletResponse().getOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); } catch (PathNotFoundException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); XSLTBuddy buddy = new XSLTBuddy(); buddy.parseArgs(args); XSLTransformer transformer = new XSLTransformer(); if (buddy.templateDir != null) { transformer.setTemplateDir(buddy.templateDir); } FileReader xslReader = new FileReader(buddy.xsl); Templates xslTemplate = transformer.getXSLTemplate(buddy.xsl, xslReader); for (Enumeration e = buddy.params.keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); transformer.addParam(key, buddy.params.get(key)); } Reader reader = null; if (buddy.src == null) { reader = new StringReader(XSLTBuddy.BLANK_XML); } else { reader = new FileReader(buddy.src); } if (buddy.out == null) { String result = transformer.doTransform(reader, xslTemplate, buddy.xsl); buddy.getLogger().info("\n\nXSLT Result:\n\n" + result + "\n"); } else { File file = new File(buddy.out); File dir = file.getParentFile(); if (dir != null) { dir.mkdirs(); } FileWriter writer = new FileWriter(buddy.out); transformer.doTransform(reader, xslTemplate, buddy.xsl, writer); writer.flush(); writer.close(); } buddy.getLogger().info("Transform done successfully in " + (System.currentTimeMillis() - start) + " milliseconds"); }
|
11
|
Code Sample 1:
public static void copy(File src, File dest) throws IOException { log.info("Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath()); if (!src.exists()) throw new IOException("File not found: " + src.getAbsolutePath()); if (!src.canRead()) throw new IOException("Source not readable: " + src.getAbsolutePath()); if (src.isDirectory()) { if (!dest.exists()) if (!dest.mkdirs()) throw new IOException("Could not create direcotry: " + dest.getAbsolutePath()); String children[] = src.list(); for (String child : children) { File src1 = new File(src, child); File dst1 = new File(dest, child); copy(src1, dst1); } } else { FileInputStream fin = null; FileOutputStream fout = null; byte[] buffer = new byte[4096]; int bytesRead; fin = new FileInputStream(src); fout = new FileOutputStream(dest); while ((bytesRead = fin.read(buffer)) >= 0) fout.write(buffer, 0, bytesRead); if (fin != null) { fin.close(); } if (fout != null) { fout.close(); } } }
Code Sample 2:
private static boolean copyFile(File src, File dest) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (fis != null) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } if (fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
|
00
|
Code Sample 1:
public static String encripta(String senha) throws GCIException { LOGGER.debug(INICIANDO_METODO + "encripta(String)"); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException e) { LOGGER.fatal(e.getMessage(), e); throw new GCIException(e); } finally { LOGGER.debug(FINALIZANDO_METODO + "encripta(String)"); } }
Code Sample 2:
public void addStadium(Stadium stadium) throws StadiumException { Connection conn = ConnectionManager.getManager().getConnection(); if (findStadiumBy_N_C(stadium.getName(), stadium.getCity()) != -1) throw new StadiumException("Stadium already exists"); try { PreparedStatement stm = conn.prepareStatement(Statements.INSERT_STADIUM); conn.setAutoCommit(false); stm.setString(1, stadium.getName()); stm.setString(2, stadium.getCity()); stm.executeUpdate(); int id = getMaxId(); TribuneLogic logic = TribuneLogic.getInstance(); for (Tribune trib : stadium.getTribunes()) { int tribuneId = logic.addTribune(trib); if (tribuneId != -1) { stm = conn.prepareStatement(Statements.INSERT_STAD_TRIBUNE); stm.setInt(1, id); stm.setInt(2, tribuneId); stm.executeUpdate(); } } } catch (SQLException e) { try { conn.rollback(); conn.setAutoCommit(true); } catch (SQLException e1) { e1.printStackTrace(); } throw new StadiumException("Adding stadium failed", e); } try { conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
protected long incrementInDatabase(Object type) { long current_value; long new_value; String entry; if (global_entry != null) entry = global_entry; else throw new UnsupportedOperationException("Named key generators are not yet supported."); String lkw = (String) properties.get("net.ontopia.topicmaps.impl.rdbms.HighLowKeyGenerator.SelectSuffix"); String sql_select; if (lkw == null && (database.equals("sqlserver"))) { sql_select = "select " + valcol + " from " + table + " with (XLOCK) where " + keycol + " = ?"; } else { if (lkw == null) { if (database.equals("sapdb")) lkw = "with lock"; else lkw = "for update"; } sql_select = "select " + valcol + " from " + table + " where " + keycol + " = ? " + lkw; } if (log.isDebugEnabled()) log.debug("KeyGenerator: retrieving: " + sql_select); Connection conn = null; try { conn = connfactory.requestConnection(); PreparedStatement stm1 = conn.prepareStatement(sql_select); try { stm1.setString(1, entry); ResultSet rs = stm1.executeQuery(); if (!rs.next()) throw new OntopiaRuntimeException("HIGH/LOW key generator table '" + table + "' not initialized (no rows)."); current_value = rs.getLong(1); rs.close(); } finally { stm1.close(); } new_value = current_value + grabsize; String sql_update = "update " + table + " set " + valcol + " = ? where " + keycol + " = ?"; if (log.isDebugEnabled()) log.debug("KeyGenerator: incrementing: " + sql_update); PreparedStatement stm2 = conn.prepareStatement(sql_update); try { stm2.setLong(1, new_value); stm2.setString(2, entry); stm2.executeUpdate(); } finally { stm2.close(); } conn.commit(); } catch (SQLException e) { try { if (conn != null) conn.rollback(); } catch (SQLException e2) { } throw new OntopiaRuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { throw new OntopiaRuntimeException(e); } } } value = current_value + 1; max_value = new_value; return value; }
Code Sample 2:
private String checkForUpdate() { InputStream is = null; try { URL url = new URL(CHECK_UPDATES_URL); try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "TinyLaF"); Object content = conn.getContent(); if (!(content instanceof InputStream)) { return "An exception occured while checking for updates." + "\n\nException was: Content is no InputStream"; } is = (InputStream) content; } catch (IOException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } } catch (MalformedURLException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } try { BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buff = new StringBuffer(); String line; while ((line = in.readLine()) != null) { buff.append(line); } in.close(); return buff.toString(); } catch (IOException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } }
|
11
|
Code Sample 1:
private void writeToFile(Body b, File mime4jFile) throws FileNotFoundException, IOException { if (b instanceof TextBody) { String charset = CharsetUtil.toJavaCharset(b.getParent().getCharset()); if (charset == null) { charset = "ISO8859-1"; } OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((TextBody) b).getReader(), out, charset); } else { OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((BinaryBody) b).getInputStream(), out); } }
Code Sample 2:
public MemoryBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); }
|
00
|
Code Sample 1:
private void getXMLData() { String result = null; URL url = null; URLConnection conn = null; BufferedReader rd = null; StringBuffer sb = new StringBuffer(); String line; try { url = new URL(this.url); conn = url.openConnection(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { sb.append(line + "\n"); } rd.close(); result = sb.toString(); } catch (MalformedURLException e) { log.error("URL was malformed: {}", url, e); } catch (IOException e) { log.error("IOException thrown: {}", url, e); } this.xmlString = result; }
Code Sample 2:
public static String download(String address, String outputFolder) { URL url = null; String fileName = ""; try { url = new URL(address); System.err.println("Indirizzo valido!"); } catch (MalformedURLException ex) { System.err.println("Indirizzo non valido!"); } try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Range", "bytes=0-"); connection.connect(); int contentLength = connection.getContentLength(); if (contentLength < 1) { System.err.println("Errore, c'e' qualcosa che non va!"); return ""; } fileName = url.getFile(); fileName = fileName.substring(url.getFile().lastIndexOf('/') + 1); RandomAccessFile file = new RandomAccessFile(outputFolder + fileName, "rw"); file.seek(0); InputStream stream = connection.getInputStream(); byte[] buffer = new byte[1024]; while (true) { int read = stream.read(buffer); if (read == -1) { break; } file.write(buffer, 0, read); } file.close(); } catch (IOException ioe) { System.err.println("I/O error!"); } return outputFolder + fileName; }
|
00
|
Code Sample 1:
private void getViolationsReportByProductOfferIdYearMonth() throws IOException { String xmlFile8Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportByProductOfferIdYearMonth.xml"; URL url8; url8 = new URL(bmReportingWSUrl); URLConnection connection8 = url8.openConnection(); HttpURLConnection httpConn8 = (HttpURLConnection) connection8; FileInputStream fin8 = new FileInputStream(xmlFile8Send); ByteArrayOutputStream bout8 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin8, bout8); fin8.close(); byte[] b8 = bout8.toByteArray(); httpConn8.setRequestProperty("Content-Length", String.valueOf(b8.length)); httpConn8.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn8.setRequestProperty("SOAPAction", soapAction); httpConn8.setRequestMethod("POST"); httpConn8.setDoOutput(true); httpConn8.setDoInput(true); OutputStream out8 = httpConn8.getOutputStream(); out8.write(b8); out8.close(); InputStreamReader isr8 = new InputStreamReader(httpConn8.getInputStream()); BufferedReader in8 = new BufferedReader(isr8); String inputLine8; StringBuffer response8 = new StringBuffer(); while ((inputLine8 = in8.readLine()) != null) { response8.append(inputLine8); } in8.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name:" + "getViolationsReportByProductOfferIdYearMonth\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response8.toString()); }
Code Sample 2:
private void mergeInDefaultMenuItemActionPerformed(java.awt.event.ActionEvent evt) { try { String surl = AutoplotUtil.getProperty("autoplot.default.bookmarks", "http://www.autoplot.org/data/demos.xml"); URL url = new URL(surl); Document doc = AutoplotUtil.readDoc(url.openStream()); List<Bookmark> importBook = Bookmark.parseBookmarks(doc.getDocumentElement()); List<Bookmark> newList = new ArrayList(model.list.size()); for (int i = 0; i < model.list.size(); i++) { newList.add(i, model.list.get(i).copy()); } model.mergeList(importBook, newList); model.setList(newList); formatToFile(bookmarksFile); } catch (SAXException ex) { logger.log(Level.SEVERE, null, ex); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { logger.log(Level.SEVERE, null, ex); } }
|
00
|
Code Sample 1:
protected void processAnnotationsJndi(URL url) { try { URLConnection urlConn = url.openConnection(); DirContextURLConnection dcUrlConn; if (!(urlConn instanceof DirContextURLConnection)) { sm.getString("contextConfig.jndiUrlNotDirContextConn", url); return; } dcUrlConn = (DirContextURLConnection) urlConn; dcUrlConn.setUseCaches(false); String type = dcUrlConn.getHeaderField(ResourceAttributes.TYPE); if (ResourceAttributes.COLLECTION_TYPE.equals(type)) { Enumeration<String> dirs = dcUrlConn.list(); while (dirs.hasMoreElements()) { String dir = dirs.nextElement(); URL dirUrl = new URL(url.toString() + '/' + dir); processAnnotationsJndi(dirUrl); } } else { if (url.getPath().endsWith(".class")) { InputStream is = null; try { is = dcUrlConn.getInputStream(); processAnnotationsStream(is); } catch (IOException e) { logger.error(sm.getString("contextConfig.inputStreamJndi", url), e); } finally { if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } } } catch (IOException e) { logger.error(sm.getString("contextConfig.jndiUrl", url), e); } }
Code Sample 2:
protected boolean createFile(final IProject project, final IProgressMonitor monitor, final Template templ, final String sourceUrl, final String destFile, final boolean isBinary) throws IOException, CoreException { URL url; url = new URL(sourceUrl); final URLConnection con = url.openConnection(); final IFile f = project.getFile(replaceVariables(templ.getVariables(), destFile)); createParents(f, monitor); if (isBinary) { f.create(con.getInputStream(), true, monitor); } else { final StringWriter sw = new StringWriter(); final InputStream in = con.getInputStream(); for (; ; ) { final int c = in.read(); if (-1 == c) { break; } sw.write(c); } sw.close(); final String fileText = replaceVariables(templ.getVariables(), sw.toString()); f.create(new ByteArrayInputStream(fileText.getBytes()), true, monitor); } return true; }
|
00
|
Code Sample 1:
public void serveResource(HTTPResource resource, HttpServletRequest request, HttpServletResponse response) throws java.io.IOException { Image image = (Image) resource; log.debug("Serving: " + image); URL url = image.getResourceURL(); int idx = url.toString().lastIndexOf("."); String fn = image.getId() + url.toString().substring(idx); String cd = "filename=\"" + fn + "\""; response.setContentType(image.getContentType()); log.debug("LOADING: " + url); IOUtil.copyData(response.getOutputStream(), url.openStream()); }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
00
|
Code Sample 1:
public String getHTTPContent(String sUrl, String encode, String cookie, String host, String referer) { HttpURLConnection connection = null; InputStream in = null; StringBuffer strResult = new StringBuffer(); try { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); if (!isStringNull(host)) this.setHttpInfo(connection, cookie, host, referer); connection.connect(); int httpStatus = connection.getResponseCode(); if (httpStatus != 200) log.info("getHTTPConent error httpStatus - " + httpStatus); in = new BufferedInputStream(connection.getInputStream()); String inputLine = null; byte[] b = new byte[40960]; int len = 0; while ((len = in.read(b)) > 0) { inputLine = new String(b, 0, len, encode); strResult.append(inputLine.replaceAll("[\t\n\r ]", " ")); } in.close(); } catch (IOException e) { log.warn("SpiderUtil getHTTPConent IOException -> ", e); } finally { if (in != null) try { in.close(); } catch (IOException e) { } } return strResult.toString(); }
Code Sample 2:
public void writeToFtp(String login, String password, String address, String directory, String filename) { String newline = System.getProperty("line.separator"); try { URL url = new URL("ftp://" + login + ":" + password + "@ftp." + address + directory + filename + ".html" + ";type=i"); URLConnection urlConn = url.openConnection(); urlConn.setDoOutput(true); OutputStreamWriter stream = new OutputStreamWriter(urlConn.getOutputStream()); stream.write("<html><title>" + title + "</title>" + newline); stream.write("<h1><b>" + title + "</b></h1>" + newline); stream.write("<h2>Table Of Contents:</h2><ul>" + newline); for (int k = 0; k < rings.size(); k++) { stream.write("<li><i><a href=\"#"); stream.write(readNoteTitle(k)); stream.write("\">"); stream.write(readNoteTitle(k)); stream.write("</a></i></li>" + newline); } stream.write("</ul><hr>" + newline + newline); for (int k = 0; k < rings.size(); k++) { stream.write("<h3><b>"); stream.write("<a name=\""); stream.write(readNoteTitle(k)); stream.write("\">"); stream.write(readNoteTitle(k) + "</a>"); stream.write("</b></h3>" + newline); stream.write(readNoteBody(k) + newline); } stream.write(newline + "<br><hr><a>This was created using Scribe, a free crutch editor.</a></html>"); stream.close(); } catch (IOException error) { System.out.println("There was an error: " + error); } }
|
00
|
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 static String getPageSource(String url) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder source = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) source.append(line); in.close(); return source.toString(); }
|
00
|
Code Sample 1:
public void testExecute() throws Exception { LocalWorker worker = new JTidyWorker(); URL url = new URL("http://www.nature.com/index.html"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = in.readLine()) != null) { sb.append(str); sb.append(LINE_ENDING); } in.close(); Map inputMap = new HashMap(); DataThingAdapter inAdapter = new DataThingAdapter(inputMap); inAdapter.putString("inputHtml", sb.toString()); Map outputMap = worker.execute(inputMap); DataThingAdapter outAdapter = new DataThingAdapter(outputMap); assertNotNull("The outputMap was null", outputMap); String results = outAdapter.getString("results"); assertFalse("The results were empty", results.equals("")); assertNotNull("The results were null", results); }
Code Sample 2:
public static void TestDBStore() throws PDException, Exception { StoreDDBB StDB = new StoreDDBB("jdbc:derby://localhost:1527/Prodoc", "Prodoc", "Prodoc", "org.apache.derby.jdbc.ClientDriver;STBLOB"); System.out.println("Driver[" + StDB.getDriver() + "] Tabla [" + StDB.getTable() + "]"); StDB.Connect(); FileInputStream in = new FileInputStream("/tmp/readme.htm"); StDB.Insert("12345678-1", "1.0", in); int TAMBUFF = 1024 * 64; byte Buffer[] = new byte[TAMBUFF]; InputStream Bytes; Bytes = StDB.Retrieve("12345678-1", "1.0"); FileOutputStream fo = new FileOutputStream("/tmp/12345679.htm"); int readed = Bytes.read(Buffer); while (readed != -1) { fo.write(Buffer, 0, readed); readed = Bytes.read(Buffer); } Bytes.close(); fo.close(); StDB.Delete("12345678-1", "1.0"); StDB.Disconnect(); }
|
11
|
Code Sample 1:
public static String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); byte[] hash = md.digest(); StringBuffer hashStringBuf = new StringBuffer(); String byteString; int byteLength; for (int index = 0; index < hash.length; index++) { byteString = String.valueOf(hash[index] + 128); byteLength = byteString.length(); switch(byteLength) { case 1: byteString = "00" + byteString; break; case 2: byteString = "0" + byteString; break; } hashStringBuf.append(byteString); } return hashStringBuf.toString(); } catch (NoSuchAlgorithmException nsae) { log.error("Error getting password hash - " + nsae.getMessage()); return null; } }
Code Sample 2:
public static String generate(String documentSelector) { if (documentSelector == null) { return null; } String date = Long.toString(System.currentTimeMillis()); try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(documentSelector.getBytes()); md.update(date.getBytes()); byte[] digest = md.digest(); return toHexString(digest); } catch (NoSuchAlgorithmException e) { return null; } }
|
00
|
Code Sample 1:
public void add(AddInterceptorChain chain, Entry entry, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + "LDAPBaseServer"); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); HashMap<String, String> db2ldap = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_DB2LDAP + "LDAPBaseServer"); PreparedStatement ps = con.prepareStatement("INSERT INTO USERS (id,firstname,lastname,username) VALUES (?,?,?,?)"); ps.setInt(1, 5); ps.setString(2, entry.getEntry().getAttribute(db2ldap.get("firstname")).getStringValue()); ps.setString(3, entry.getEntry().getAttribute(db2ldap.get("lastname")).getStringValue()); ps.setString(4, entry.getEntry().getAttribute(db2ldap.get("username")).getStringValue()); ps.executeUpdate(); ps.close(); ps = con.prepareStatement("SELECT id FROM LOCATIONS WHERE name=?"); PreparedStatement inst = con.prepareStatement("INSERT INTO LOCATIONMAP (person,location) VALUES (?,?)"); LDAPAttribute l = entry.getEntry().getAttribute(db2ldap.get("name")); if (l == null) { con.rollback(); throw new LDAPException("Location is required", LDAPException.OBJECT_CLASS_VIOLATION, "Location is required"); } String[] vals = l.getStringValueArray(); for (int i = 0; i < vals.length; i++) { ps.setString(1, vals[i]); ResultSet rs = ps.executeQuery(); if (!rs.next()) { con.rollback(); throw new LDAPException("Location " + vals[i] + " does not exist", LDAPException.OBJECT_CLASS_VIOLATION, "Location " + vals[i] + " does not exist"); } inst.setInt(1, 5); inst.setInt(2, rs.getInt("id")); inst.executeUpdate(); } ps.close(); inst.close(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not add entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not add entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
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); } } }
|
11
|
Code Sample 1:
@Override public void copy(final String fileName) throws FileIOException { final long savedCurrentPositionInFile = currentPositionInFile; if (opened) { closeImpl(); } final FileInputStream fis; try { fis = new FileInputStream(file); } catch (FileNotFoundException exception) { throw HELPER_FILE_UTIL.fileIOException(FAILED_OPEN + file, file, exception); } final File destinationFile = new File(fileName); final FileOutputStream fos; try { fos = new FileOutputStream(destinationFile); } catch (FileNotFoundException exception) { throw HELPER_FILE_UTIL.fileIOException(FAILED_OPEN + destinationFile, destinationFile, exception); } try { final byte[] buf = new byte[1024]; int readLength = 0; while ((readLength = fis.read(buf)) != -1) { fos.write(buf, 0, readLength); } } catch (IOException exception) { throw HELPER_FILE_UTIL.fileIOException("failed copy from " + file + " to " + destinationFile, null, exception); } finally { try { if (fis != null) { fis.close(); } } catch (Exception exception) { } try { if (fos != null) { fos.close(); } } catch (Exception exception) { } } if (opened) { openImpl(); seek(savedCurrentPositionInFile); } }
Code Sample 2:
public static void putNextJarEntry(JarOutputStream modelStream, String name, File file) throws IOException { JarEntry entry = new JarEntry(name); entry.setSize(file.length()); modelStream.putNextEntry(entry); InputStream fileStream = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(fileStream, modelStream); fileStream.close(); }
|
00
|
Code Sample 1:
public void sendShape(String s) { try { URLConnection uc = new URL(url + "&add=" + s).openConnection(); InputStream in = uc.getInputStream(); int b; while ((b = in.read()) != -1) { } in.close(); } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
@Override protected String getRawPage(String url) throws IOException { HttpClient httpClient = new HttpClient(); String proxyHost = config.getString("proxy.host"), proxyPortString = config.getString("proxy.port"); if (proxyHost != null && proxyPortString != null) { int proxyPort = -1; try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException e) { } if (proxyPort != -1) { httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); } } GetMethod urlGet = new GetMethod(url); urlGet.setRequestHeader("Accept-Encoding", ""); urlGet.setRequestHeader("User-Agent", "Mozilla/5.0"); int retCode; if ((retCode = httpClient.executeMethod(urlGet)) != HttpStatus.SC_OK) { throw new RuntimeException("Unexpected HTTP code: " + retCode); } String encoding = null; Header contentType = urlGet.getResponseHeader("Content-Type"); if (contentType != null) { String contentTypeString = contentType.toString(); int i = contentTypeString.indexOf("charset="); if (i != -1) { encoding = contentTypeString.substring(i + "charset=".length()).trim(); } } boolean gzipped = false; Header contentEncoding = urlGet.getResponseHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { gzipped = true; } byte[] htmlData; try { InputStream in = gzipped ? new GZIPInputStream(urlGet.getResponseBodyAsStream()) : urlGet.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); htmlData = out.toByteArray(); in.close(); } finally { urlGet.releaseConnection(); } if (encoding == null) { Matcher m = Pattern.compile("(?i)<meta[^>]*charset=(([^\"]+\")|(\"[^\"]+\"))").matcher(new String(htmlData)); if (m.find()) { encoding = m.group(1).trim().replace("\"", ""); } } if (encoding == null) { encoding = "UTF-8"; } return new String(htmlData, encoding); }
|
11
|
Code Sample 1:
public void create(File target) { if ("dir".equals(type)) { File dir = new File(target, name); dir.mkdirs(); for (Resource c : children) { c.create(dir); } } else if ("package".equals(type)) { String[] dirs = name.split("\\."); File parent = target; for (String d : dirs) { parent = new File(parent, d); } parent.mkdirs(); for (Resource c : children) { c.create(parent); } } else if ("file".equals(type)) { InputStream is = getInputStream(); File file = new File(target, name); try { if (is != null) { FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(is, fos); fos.flush(); fos.close(); } else { PrintStream ps = new PrintStream(file); ps.print(content); ps.flush(); ps.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if ("zip".equals(type)) { try { unzip(target); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { throw new RuntimeException("unknown resource type: " + type); } }
Code Sample 2:
public void checkFilesAndCopyValid(String filename) { downloadResults(); loadResults(); File tmpFolderF = new File(tmpFolder); deleteFileFromTMPFolder(tmpFolderF); ZipReader zr = new ZipReader(); zr.UnzipFile(filename); try { LogManager.getInstance().log("Ov��uji odevzdan� soubory a kop�ruji validovan�:"); LogManager.getInstance().log(""); JAXBElement<?> element = ElementJAXB.getJAXBElement(); Ppa1VysledkyCviceniType pvct = (Ppa1VysledkyCviceniType) element.getValue(); File zipFolder = new File(tmpFolder).listFiles()[0].listFiles()[0].listFiles()[0]; File[] zipFolderList = zipFolder.listFiles(); for (File studentDirectory : zipFolderList) { if (studentDirectory.isDirectory()) { String osobniCisloZeSlozky = studentDirectory.getName().split("-")[0]; LogManager.getInstance().changeLog("Prov��ov�n� soubor� studenta s ��slem: " + osobniCisloZeSlozky); List<StudentType> students = (List<StudentType>) pvct.getStudent(); for (StudentType student : students) { if (student.getOsobniCislo().equals(osobniCisloZeSlozky)) { int pzp = student.getDomaciUlohy().getPosledniZpracovanyPokus().getCislo().intValue(); DomaciUlohyType dut = student.getDomaciUlohy(); ChybneOdevzdaneType chot = dut.getChybneOdevzdane(); ObjectFactory of = new ObjectFactory(); File[] pokusyDirectories = studentDirectory.listFiles(); NodeList souboryNL = result.getElementsByTagName("soubor"); int start = souboryNL.getLength() - 1; boolean samostatnaPrace = false; for (int i = (pokusyDirectories.length - 1); i >= 0; i--) { if ((pokusyDirectories[i].isDirectory()) && (pzp < Integer.parseInt(pokusyDirectories[i].getName().split("_")[1].trim()))) { File testedFile = pokusyDirectories[i].listFiles()[0]; if ((testedFile.exists()) && (testedFile.isFile())) { String[] partsOfFilename = testedFile.getName().split("_"); String osobniCisloZeSouboru = "", priponaSouboru = ""; String[] posledniCastSouboru = null; if (partsOfFilename.length == 4) { posledniCastSouboru = partsOfFilename[3].split("[.]"); osobniCisloZeSouboru = posledniCastSouboru[0]; if (posledniCastSouboru.length <= 1) priponaSouboru = ""; else priponaSouboru = posledniCastSouboru[1]; } String samostatnaPraceNazev = Konfigurace.getInstance().getSamostatnaPraceNazev(); List<SouborType> lst = chot.getSoubor(); if (testedFile.getName().startsWith(samostatnaPraceNazev)) { samostatnaPrace = true; } else { samostatnaPrace = false; if (partsOfFilename.length != 4) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� struktura jm�na souboru."); lst.add(st); continue; } else if (!testedFile.getName().startsWith("Ppa1_cv")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� za��tek jm�na souboru."); lst.add(st); continue; } else if (!priponaSouboru.equals("java")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� p��pona souboru."); lst.add(st); continue; } else if (!osobniCisloZeSouboru.equals(osobniCisloZeSlozky)) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Nesouhlas� osobn� ��sla."); lst.add(st); continue; } else if (partsOfFilename[3].split("[.]").length > 2) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("V�ce p��pon souboru."); lst.add(st); continue; } else { long cisloCviceni, cisloUlohy; try { if (partsOfFilename[1].length() == 4) { String cisloS = partsOfFilename[1].substring(2); long cisloL = Long.parseLong(cisloS); cisloCviceni = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo cvi�en�"); lst.add(st); continue; } try { if (partsOfFilename[2].length() > 0) { String cisloS = partsOfFilename[2]; long cisloL = Long.parseLong(cisloS); cisloUlohy = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo �lohy"); lst.add(st); continue; } CislaUloh ci = new CislaUloh(); List<long[]> cviceni = ci.getSeznamCviceni(); boolean nalezenoCv = false, nalezenaUl = false; for (long[] c : cviceni) { if (c[0] == cisloCviceni) { for (int j = 1; j < c.length; j++) { if (c[j] == cisloUlohy) { nalezenaUl = true; break; } } nalezenoCv = true; break; } } if (!nalezenoCv) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo cvi�en�"); lst.add(st); continue; } if (!nalezenaUl) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo �lohy"); lst.add(st); continue; } } } } Calendar dateFromZipFile = null; File zipFile = new File(filename); if (zipFile.exists()) { String[] s = zipFile.getName().split("_"); if (s.length >= 3) { String[] date = s[1].split("-"), time = s[2].split("-"); dateFromZipFile = new GregorianCalendar(); dateFromZipFile.set(Integer.parseInt(date[0]), Integer.parseInt(date[1]) - 1, Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), 0); } } boolean shodaJmenaSouboru = false; String vysledekValidaceSouboru = ""; for (int j = start; j >= 0; j--) { NodeList vlastnostiSouboruNL = souboryNL.item(j).getChildNodes(); for (int k = 0; k < vlastnostiSouboruNL.getLength(); k++) { if (vlastnostiSouboruNL.item(k).getNodeName().equals("cas")) { String[] obsahElementuCas = vlastnostiSouboruNL.item(k).getTextContent().split(" "); String[] datumZElementu = obsahElementuCas[0].split("-"), casZElementu = obsahElementuCas[1].split("-"); Calendar datumACasZElementu = new GregorianCalendar(); datumACasZElementu.set(Integer.parseInt(datumZElementu[0]), Integer.parseInt(datumZElementu[1]) - 1, Integer.parseInt(datumZElementu[2]), Integer.parseInt(casZElementu[0]), Integer.parseInt(casZElementu[1]), Integer.parseInt(casZElementu[2])); if ((dateFromZipFile != null) && (datumACasZElementu.compareTo(dateFromZipFile) > 0)) { shodaJmenaSouboru = false; break; } } if (vlastnostiSouboruNL.item(k).getNodeName().equals("nazev")) { shodaJmenaSouboru = vlastnostiSouboruNL.item(k).getTextContent().equals(testedFile.getName()); } if (vlastnostiSouboruNL.item(k).getNodeName().equals("vysledek")) { vysledekValidaceSouboru = vlastnostiSouboruNL.item(k).getTextContent(); } } if (shodaJmenaSouboru) { start = --j; break; } } if (shodaJmenaSouboru && !samostatnaPrace) { boolean odevzdanoVcas = false; String cisloCviceniS = testedFile.getName().split("_")[1].substring(2); int cisloCviceniI = Integer.parseInt(cisloCviceniS); String cisloUlohyS = testedFile.getName().split("_")[2]; int cisloUlohyI = Integer.parseInt(cisloUlohyS); List<CviceniType> lct = student.getDomaciUlohy().getCviceni(); for (CviceniType ct : lct) { if (ct.getCislo().intValue() == cisloCviceniI) { MezniTerminOdevzdaniVcasType mtovt = ct.getMezniTerminOdevzdaniVcas(); Calendar mtovGC = new GregorianCalendar(); mtovGC.set(mtovt.getDatum().getYear(), mtovt.getDatum().getMonth() - 1, mtovt.getDatum().getDay(), 23, 59, 59); Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); if (fileTimeStamp.compareTo(mtovGC) <= 0) odevzdanoVcas = true; else odevzdanoVcas = false; List<UlohaType> lut = ct.getUloha(); for (UlohaType ut : lut) { if (ut.getCislo().intValue() == cisloUlohyI) { List<OdevzdanoType> lot = ut.getOdevzdano(); OdevzdanoType ot = of.createOdevzdanoType(); ot.setDatum(xmlGCDate); ot.setCas(xmlGCTime); OdevzdanoVcasType ovt = of.createOdevzdanoVcasType(); ovt.setVysledek(odevzdanoVcas); ValidatorType vt = of.createValidatorType(); vt.setVysledek(vysledekValidaceSouboru.equals("true")); ot.setOdevzdanoVcas(ovt); ot.setValidator(vt); lot.add(ot); if (vt.isVysledek()) { String test = String.format("%s%s%02d", validovane, File.separator, ct.getCislo().intValue()); if (!(new File(test).exists())) { LogManager.getInstance().log("Nebyla provedena p��prava soubor�. Chyb� slo�ka " + test.substring(Ppa1Cviceni.USER_DIR.length()) + "."); return; } else { copyValidFile(testedFile, ct.getCislo().intValue()); } } break; } } break; } } } else if (shodaJmenaSouboru && samostatnaPrace) { String[] partsOfFilename = testedFile.getName().split("_"); String[] partsOfLastPartOfFilename = partsOfFilename[partsOfFilename.length - 1].split("[.]"); String osobniCisloZeSouboru = partsOfLastPartOfFilename[0]; String priponaZeSouboru = partsOfLastPartOfFilename[partsOfLastPartOfFilename.length - 1]; if ((partsOfLastPartOfFilename.length == 2) && (priponaZeSouboru.equals("java"))) { if (student.getOsobniCislo().equals(osobniCisloZeSouboru)) { Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); List<UlozenoType> lut = student.getSamostatnaPrace().getUlozeno(); if (lut.isEmpty()) { File samostatnaPraceNewFile = new File(sp + File.separator + testedFile.getName()); if (samostatnaPraceNewFile.exists()) { samostatnaPraceNewFile.delete(); samostatnaPraceNewFile.createNewFile(); } String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(testedFile); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(samostatnaPraceNewFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); samostatnaPraceNewFile.setLastModified(testedFile.lastModified()); } UlozenoType ut = of.createUlozenoType(); ut.setDatum(xmlGCDate); ut.setCas(xmlGCTime); lut.add(0, ut); } } } } } PosledniZpracovanyPokusType pzpt = new PosledniZpracovanyPokusType(); String[] slozkaPoslednihoPokusu = pokusyDirectories[pokusyDirectories.length - 1].getName().split("_"); int cisloPokusu = Integer.parseInt(slozkaPoslednihoPokusu[slozkaPoslednihoPokusu.length - 1].trim()); pzpt.setCislo(new BigInteger(String.valueOf(cisloPokusu))); student.getDomaciUlohy().setPosledniZpracovanyPokus(pzpt); break; } } } } ElementJAXB.setJAXBElement(element); LogManager.getInstance().log("Ov��ov�n� a kop�rov�n� odevzdan�ch soubor� dokon�eno."); } catch (FileNotFoundException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (DatatypeConfigurationException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (IOException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } LogManager.getInstance().log("Maz�n� rozbalen�ch soubor� ..."); deleteFileFromTMPFolder(tmpFolderF); LogManager.getInstance().changeLog("Maz�n� rozbalen�ch soubor� ... OK"); }
|
11
|
Code Sample 1:
private static void downloadFile(String downloadFileName) throws Exception { URL getFileUrl = new URL("http://www.tegsoft.com/Tobe/getFile" + "?tegsoftFileName=" + downloadFileName); URLConnection getFileUrlConnection = getFileUrl.openConnection(); InputStream is = getFileUrlConnection.getInputStream(); String tobeHome = UiUtil.getParameter("RealPath.Context"); OutputStream out = new FileOutputStream(tobeHome + "/setup/" + downloadFileName); IOUtils.copy(is, out); is.close(); out.close(); }
Code Sample 2:
@Override public boolean copyFile(String srcRootPath, String srcDir, String srcFileName, String destRootPath, String destDir, String destFileName) { File srcPath = new File(srcRootPath + separator() + Database.getDomainName() + separator() + srcDir); if (!srcPath.exists()) { try { srcPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + srcPath); return false; } } File destPath = new File(destRootPath + separator() + Database.getDomainName() + separator() + destDir); if (!destPath.exists()) { try { destPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + destPath); return false; } } File from = new File(srcPath + separator() + srcFileName); File to = new File(destPath + separator() + destFileName); boolean res = true; FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(from).getChannel(); destChannel = new FileOutputStream(to).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (Exception ex) { logger.error("Exception", ex); res = false; } finally { if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } if (srcChannel != null) { try { srcChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } } return res; }
|
00
|
Code Sample 1:
public File getURL(URL url) throws IOException { URLConnection conn = null; File tempFile = null; Logger l = Logger.instance(); String className = getClass().getName(); l.log(Logger.DEBUG, loggerPrefix, className + ".getURL", "GET URL " + url.toString()); try { conn = url.openConnection(); tempFile = readIntoTempFile(conn.getInputStream()); } catch (IOException ioe) { l.log(Logger.ERROR, loggerPrefix, className + ".getURL", ioe); throw ioe; } finally { conn = null; } l.log(Logger.DEBUG, loggerPrefix, className + ".getURL", "received URL"); return tempFile; }
Code Sample 2:
private File downloadPDB(String pdbId) { File tempFile = new File(path + "/" + pdbId + ".pdb.gz"); File pdbHome = new File(path); if (!pdbHome.canWrite()) { System.err.println("can not write to " + pdbHome); return null; } String ftp = String.format("ftp://ftp.ebi.ac.uk/pub/databases/msd/pdb_uncompressed/pdb%s.ent", pdbId.toLowerCase()); System.out.println("Fetching " + ftp); try { URL url = new URL(ftp); InputStream conn = url.openStream(); System.out.println("writing to " + tempFile); FileOutputStream outPut = new FileOutputStream(tempFile); GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut); PrintWriter pw = new PrintWriter(gzOutPut); BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn)); String line; while ((line = fileBuffer.readLine()) != null) { pw.println(line); } pw.flush(); pw.close(); outPut.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); return null; } return tempFile; }
|
00
|
Code Sample 1:
public static byte[] sendRequestV2(String url, String content, Map<String, String> headers, String method, String contenttype) { byte[] result = null; try { HttpURLConnection httpConn = (HttpURLConnection) new URL(url).openConnection(); httpConn.setUseCaches(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod(method); httpConn.setRequestProperty("Content-Type", contenttype); httpConn.setRequestProperty("Accept-Encoding", "gzip"); if (headers != null && headers.size() > 0) { Iterator<String> keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); httpConn.setRequestProperty(key, headers.get(key)); } } httpConn.setDoOutput(true); if (content != null) httpConn.getOutputStream().write(content.getBytes("UTF-8")); System.setProperty("http.strictPostRedirect", "true"); httpConn.connect(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { InputStream in = httpConn.getInputStream(); byte[] buf = new byte[500]; int count = 0; while ((count = in.read(buf)) > 0) { bout.write(buf, 0, count); } result = bout.toByteArray(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (bout != null) bout.close(); } System.clearProperty("http.strictPostRedirect"); } catch (Exception e) { logger.error(e, e); } return result; }
Code Sample 2:
public static Image getImage(URL url) throws IOException { InputStream is = null; try { is = url.openStream(); Image img = getImage(is); img.setUrl(url); return img; } finally { if (is != null) { is.close(); } } }
|
11
|
Code Sample 1:
private File uploadFile(InputStream inputStream, File file) { FileOutputStream fileOutputStream = null; try { File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } FileUtils.touch(file); fileOutputStream = new FileOutputStream(file); IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new FileOperationException("Failed to save uploaded image", e); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { LOGGER.warn("Failed to close resources on uploaded file", e); } } return file; }
Code Sample 2:
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(); } }
|
11
|
Code Sample 1:
public static String getMD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
public boolean check(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(realm.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(password.getBytes("ISO-8859-1")); byte[] ha1 = md.digest(); String hexHa1 = new String(Hex.encodeHex(ha1)); md.reset(); md.update(method.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(uri.getBytes("ISO-8859-1")); byte[] ha2 = md.digest(); String hexHa2 = new String(Hex.encodeHex(ha2)); md.reset(); md.update(hexHa1.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nc.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(cnonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(qop.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(hexHa2.getBytes("ISO-8859-1")); byte[] digest = md.digest(); String hexDigest = new String(Hex.encodeHex(digest)); return (hexDigest.equalsIgnoreCase(response)); }
|
00
|
Code Sample 1:
@Override public ReturnValue do_run() { int bufLen = 500 * 1024; ReturnValue ret = new ReturnValue(); ret.setExitStatus(ReturnValue.SUCCESS); File output = null; if (((String) options.valueOf("input-file")).startsWith("s3://")) { Pattern p = Pattern.compile("s3://(\\S+):(\\S+)@(\\S+)"); Matcher m = p.matcher((String) options.valueOf("input-file")); boolean result = m.find(); String accessKey = null; String secretKey = null; String URL = (String) options.valueOf("input-file"); if (result) { accessKey = m.group(1); secretKey = m.group(2); URL = "s3://" + m.group(3); } else { try { HashMap<String, String> settings = (HashMap<String, String>) ConfigTools.getSettings(); accessKey = settings.get("AWS_ACCESS_KEY"); secretKey = settings.get("AWS_SECRET_KEY"); } catch (Exception e) { ret.setExitStatus(ReturnValue.SETTINGSFILENOTFOUND); ret.setProcessExitStatus(ReturnValue.SETTINGSFILENOTFOUND); return (ret); } } if (accessKey == null || secretKey == null) { ret.setExitStatus(ReturnValue.ENVVARNOTFOUND); ret.setProcessExitStatus(ReturnValue.ENVVARNOTFOUND); return (ret); } AmazonS3 s3 = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey)); p = Pattern.compile("s3://([^/]+)/(\\S+)"); m = p.matcher(URL); result = m.find(); if (result) { String bucket = m.group(1); String key = m.group(2); S3Object object = s3.getObject(new GetObjectRequest(bucket, key)); System.out.println("Content-Type: " + object.getObjectMetadata().getContentType()); output = new File((String) options.valueOf("output-dir") + File.separator + key); output.getParentFile().mkdirs(); if (!output.exists() || output.length() != object.getObjectMetadata().getContentLength()) { System.out.println("Downloading an S3 object from bucket: " + bucket + " with key: " + key); BufferedInputStream reader = new BufferedInputStream(object.getObjectContent(), bufLen); try { BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(output), bufLen); while (true) { int data = reader.read(); if (data == -1) { break; } writer.write(data); } reader.close(); writer.close(); } catch (FileNotFoundException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } } else { System.out.println("Skipping download of S3 object from bucket: " + bucket + " with key: " + key + " since local output exists: " + output.getAbsolutePath()); } } } else if (((String) options.valueOf("input-file")).startsWith("http://") || ((String) options.valueOf("input-file")).startsWith("https://")) { Pattern p = Pattern.compile("(https*)://(\\S+):(\\S+)@(\\S+)"); Matcher m = p.matcher((String) options.valueOf("input-file")); boolean result = m.find(); String protocol = null; String user = null; String pass = null; String URL = (String) options.valueOf("input-file"); if (result) { protocol = m.group(1); user = m.group(2); pass = m.group(3); URL = protocol + "://" + m.group(4); } URL urlObj = null; try { urlObj = new URL(URL); if (urlObj != null) { URLConnection urlConn = urlObj.openConnection(); if (user != null && pass != null) { String userPassword = user + ":" + pass; String encoding = new Base64().encodeBase64String(userPassword.getBytes()); urlConn.setRequestProperty("Authorization", "Basic " + encoding); } p = Pattern.compile("://([^/]+)/(\\S+)"); m = p.matcher(URL); result = m.find(); if (result) { String host = m.group(1); String path = m.group(2); output = new File((String) options.valueOf("output-dir") + path); output.getParentFile().mkdirs(); if (!output.exists() || output.length() != urlConn.getContentLength()) { System.out.println("Downloading an http object from URL: " + URL); BufferedInputStream reader = new BufferedInputStream(urlConn.getInputStream(), bufLen); BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(output), bufLen); while (true) { int data = reader.read(); if (data == -1) { break; } writer.write(data); } reader.close(); writer.close(); } else { System.out.println("Skipping download of http object from URL: " + URL + " since local output exists: " + output.getAbsolutePath()); } } } } catch (MalformedURLException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } } else { output = new File((String) options.valueOf("input-file")); } boolean result = FileTools.unzipFile(output, new File((String) options.valueOf("output-dir"))); if (!result) { ret.setStderr("Can't unzip software bundle " + options.valueOf("input-file") + " to directory " + options.valueOf("output-dir")); ret.setExitStatus(ReturnValue.RUNTIMEEXCEPTION); } return (ret); }
Code Sample 2:
protected String getManualDownloadURL() { if (_newestVersionString.indexOf("weekly") > 0) { return "http://www.cs.rice.edu/~javaplt/drjavarice/weekly/"; } final String DRJAVA_FILES_PAGE = "http://sourceforge.net/project/showfiles.php?group_id=44253"; final String LINK_PREFIX = "<a href=\"/project/showfiles.php?group_id=44253"; final String LINK_SUFFIX = "\">"; BufferedReader br = null; try { URL url = new URL(DRJAVA_FILES_PAGE); InputStream urls = url.openStream(); InputStreamReader is = new InputStreamReader(urls); br = new BufferedReader(is); String line; int pos; while ((line = br.readLine()) != null) { if ((pos = line.indexOf(_newestVersionString)) >= 0) { int prePos = line.indexOf(LINK_PREFIX); if ((prePos >= 0) && (prePos < pos)) { int suffixPos = line.indexOf(LINK_SUFFIX, prePos); if ((suffixPos >= 0) && (suffixPos + LINK_SUFFIX.length() == pos)) { String versionLink = edu.rice.cs.plt.text.TextUtil.xmlUnescape(line.substring(prePos + LINK_PREFIX.length(), suffixPos)); return DRJAVA_FILES_PAGE + versionLink; } } } } ; } catch (IOException e) { return DRJAVA_FILES_PAGE; } finally { try { if (br != null) br.close(); } catch (IOException e) { } } return DRJAVA_FILES_PAGE; }
|
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 copyFile(String sourceFilePath, String destFilePath) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sourceFilePath).getChannel(); out = new FileOutputStream(destFilePath).getChannel(); long inputSize = in.size(); in.transferTo(0, inputSize, out); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, inputSize); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
11
|
Code Sample 1:
FileCacheInputStreamFountain(FileCacheInputStreamFountainFactory factory, InputStream in) throws IOException { file = factory.createFile(); OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); in.close(); out.close(); }
Code Sample 2:
private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void decryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.DECRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }
Code Sample 2:
public void run() { try { status = UploadStatus.INITIALISING; if (megaUploadAccount.loginsuccessful) { login = true; host = megaUploadAccount.username + " | MegaUpload.com"; } else { login = false; host = "MegaUpload.com"; } initialize(); HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); filelength = file.length(); generateMegaUploadID(); if (login) { status = UploadStatus.GETTINGCOOKIE; usercookie = MegaUploadAccount.getUserCookie(); postURL = megauploadlink + "upload_done.php?UPLOAD_IDENTIFIER=" + uploadID + "&" + usercookie + "&s=" + filelength; } else { postURL = megauploadlink + "upload_done.php?UPLOAD_IDENTIFIER=" + uploadID + "&user=undefined&s=" + filelength; } HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", usercookie); MultipartEntity mpEntity = new MultipartEntity(); mpEntity.addPart("", new MonitoredFileBody(file, uploadProgress)); httppost.setEntity(mpEntity); NULogger.getLogger().info("Now uploading your file into megaupload..........................."); status = UploadStatus.UPLOADING; HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); if (resEntity != null) { status = UploadStatus.GETTINGLINK; downloadlink = EntityUtils.toString(resEntity); downloadlink = CommonUploaderTasks.parseResponse(downloadlink, "downloadurl = '", "'"); downURL = downloadlink; NULogger.getLogger().log(Level.INFO, "Download Link : {0}", downURL); uploadFinished(); } } catch (Exception ex) { Logger.getLogger(MegaUpload.class.getName()).log(Level.SEVERE, null, ex); uploadFailed(); } }
|
00
|
Code Sample 1:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String act = request.getParameter("act"); if (null == act) { } else if ("down".equalsIgnoreCase(act)) { String vest = request.getParameter("vest"); String id = request.getParameter("id"); if (null == vest) { t_attach_Form attach = null; t_attach_QueryMap query = new t_attach_QueryMap(); attach = query.getByID(id); if (null != attach) { String filename = attach.getAttach_name(); String fullname = attach.getAttach_fullname(); response.addHeader("Content-Disposition", "attachment;filename=" + filename + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); } } } else if ("review".equalsIgnoreCase(vest)) { t_infor_review_QueryMap reviewQuery = new t_infor_review_QueryMap(); t_infor_review_Form review = reviewQuery.getByID(id); String seq = request.getParameter("seq"); String name = null, fullname = null; if ("1".equals(seq)) { name = review.getAttachname1(); fullname = review.getAttachfullname1(); } else if ("2".equals(seq)) { name = review.getAttachname2(); fullname = review.getAttachfullname2(); } else if ("3".equals(seq)) { name = review.getAttachname3(); fullname = review.getAttachfullname3(); } String downTypeStr = DownType.getInst().getDownTypeByFileName(name); logger.debug("filename=" + name + " downtype=" + downTypeStr); response.setContentType(downTypeStr); response.addHeader("Content-Disposition", "attachment;filename=" + name + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); in.close(); } } } else if ("upload".equalsIgnoreCase(act)) { String infoId = request.getParameter("inforId"); logger.debug("infoId=" + infoId); } } catch (Exception e) { } }
Code Sample 2:
protected String encrypt(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } catch (Exception ex) { throw new TiiraException(ex); } }
|
00
|
Code Sample 1:
public static String calculateHash(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.reset(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(password.getBytes()); return byteToBase64(md.digest()); }
Code Sample 2:
public boolean copy(File src, File dest, byte[] b) { if (src.isDirectory()) { String[] ss = src.list(); for (int i = 0; i < ss.length; i++) if (!copy(new File(src, ss[i]), new File(dest, ss[i]), b)) return false; return true; } delete(dest); dest.getParentFile().mkdirs(); try { FileInputStream fis = new FileInputStream(src); try { FileOutputStream fos = new FileOutputStream(dest); try { int read; while ((read = fis.read(b)) != -1) fos.write(b, 0, read); } finally { try { fos.close(); } catch (IOException ignore) { } register(dest); } } finally { fis.close(); } if (log.isDebugEnabled()) log.debug("Success: M-COPY " + src + " -> " + dest); return true; } catch (IOException e) { log.error("Failed: M-COPY " + src + " -> " + dest, e); return false; } }
|
00
|
Code Sample 1:
public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (destFile.getParentFile() != null && !destFile.getParentFile().mkdirs()) { LOG.error("GeneralHelper.copyFile(): Cannot create parent directories from " + destFile); } FileInputStream fIn = null; FileOutputStream fOut = null; FileChannel source = null; FileChannel destination = null; try { fIn = new FileInputStream(sourceFile); source = fIn.getChannel(); fOut = new FileOutputStream(destFile); destination = fOut.getChannel(); long transfered = 0; final long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } } finally { if (source != null) { source.close(); } else if (fIn != null) { fIn.close(); } if (destination != null) { destination.close(); } else if (fOut != null) { fOut.close(); } } }
Code Sample 2:
public static String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); byte[] hash = md.digest(); int hashLength = hash.length; StringBuffer hashStringBuf = new StringBuffer(); String byteString; int byteLength; for (int index = 0; index < hash.length; index++) { byteString = String.valueOf(hash[index] + 128); byteLength = byteString.length(); switch(byteLength) { case 1: byteString = "00" + byteString; break; case 2: byteString = "0" + byteString; break; } hashStringBuf.append(byteString); } return hashStringBuf.toString(); } catch (NoSuchAlgorithmException nsae) { System.out.println("Error getting password hash - " + nsae.getMessage()); return null; } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public void jsFunction_addFile(ScriptableFile infile) throws IOException { if (!infile.jsFunction_exists()) throw new IllegalArgumentException("Cannot add a file that doesn't exists to an archive"); ZipArchiveEntry entry = new ZipArchiveEntry(infile.getName()); entry.setSize(infile.jsFunction_getSize()); out.putArchiveEntry(entry); try { InputStream inStream = infile.jsFunction_createInputStream(); IOUtils.copy(inStream, out); inStream.close(); } finally { out.closeArchiveEntry(); } }
|
00
|
Code Sample 1:
private String generateCode(String seed) { try { Security.addProvider(new FNVProvider()); MessageDigest digest = MessageDigest.getInstance("FNV-1a"); digest.update((seed + UUID.randomUUID().toString()).getBytes()); byte[] hash1 = digest.digest(); String sHash1 = "m" + (new String(LibraryBase64.encode(hash1))).replaceAll("=", "").replaceAll("-", "_"); return sHash1; } catch (Exception e) { e.printStackTrace(); } return ""; }
Code Sample 2:
private static void execute(String fileName) throws IOException, SQLException { InputStream input = DatabaseConstants.class.getResourceAsStream(fileName); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer); String sql = writer.toString(); Statement statement = connection.createStatement(); statement.execute(sql); }
|
11
|
Code Sample 1:
private static boolean computeCustomerAverages(String completePath, String CustomerAveragesOutputFileName, String CustIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TIntObjectHashMap CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int startIndex, endIndex; TIntArrayList a; int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustomerAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalCusts = CustomerLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "MovieRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); int[] itr = CustomerLimitsTHash.keys(); startIndex = 0; endIndex = 0; a = null; ByteBuffer buf; for (int i = 0; i < totalCusts; i++) { int currentCust = itr[i]; a = (TIntArrayList) CustomerLimitsTHash.get(currentCust); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 3); inC.read(buf, (startIndex - 1) * 3); } else { buf = ByteBuffer.allocate(3); inC.read(buf, (startIndex - 1) * 3); } buf.flip(); int bufsize = buf.capacity() / 3; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getShort(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(8); outbuf.putInt(currentCust); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
public void actionPerformed(ActionEvent ev) { if (fileChooser == null) { fileChooser = new JFileChooser(); ExtensionFileFilter fileFilter = new ExtensionFileFilter("Device profile (*.jar, *.zip)"); fileFilter.addExtension("jar"); fileFilter.addExtension("zip"); fileChooser.setFileFilter(fileFilter); } if (fileChooser.showOpenDialog(SwingSelectDevicePanel.this) == JFileChooser.APPROVE_OPTION) { String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); JarFile jar = null; try { jar = new JarFile(fileChooser.getSelectedFile()); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } urls[0] = fileChooser.getSelectedFile().toURL(); } catch (IOException e) { Message.error("Error reading file: " + fileChooser.getSelectedFile().getName() + ", " + Message.getCauseMessage(e), e); return; } finally { if (jar != null) { try { jar.close(); } catch (IOException ignore) { } } } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileChooser.getSelectedFile().getName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { String entryName = (String) it.next(); try { devices.put(entryName, DeviceImpl.create(emulatorContext, classLoader, entryName, J2SEDevice.class)); } catch (IOException e) { Message.error("Error parsing device profile, " + Message.getCauseMessage(e), e); return; } } for (Enumeration en = lsDevicesModel.elements(); en.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) en.nextElement(); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), fileChooser.getSelectedFile().getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(fileChooser.getSelectedFile(), deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } lsDevicesModel.addElement(entry); Config.addDeviceEntry(entry); } lsDevices.setSelectedValue(entry, true); } catch (IOException e) { Message.error("Error adding device profile, " + Message.getCauseMessage(e), e); return; } } }
|
11
|
Code Sample 1:
public static byte[] SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return sha1hash; }
Code Sample 2:
public static String convetToSignature(Map<String, String> keyVal, String apiSecret) { if (keyVal == null || apiSecret == null || keyVal.size() <= 0 || apiSecret.trim().equals("")) { throw new IllegalArgumentException("keyVal or api secret is not valid. Please Check it again."); } Iterator<Entry<String, String>> iterator = keyVal.entrySet().iterator(); StringBuffer rslt = new StringBuffer(); byte[] signature = null; while (iterator.hasNext()) { Entry<String, String> entry = iterator.next(); rslt.append(entry.getKey()); rslt.append("="); rslt.append(entry.getValue()); } rslt.append(apiSecret); try { MessageDigest md5 = MessageDigest.getInstance(HASHING_METHOD); md5.reset(); md5.update(rslt.toString().getBytes()); rslt.delete(0, rslt.length()); signature = md5.digest(); for (int i = 0; i < signature.length; i++) { String hex = Integer.toHexString(0xff & signature[i]); if (hex.length() == 1) { rslt.append('0'); } rslt.append(hex); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return rslt.toString(); }
|
00
|
Code Sample 1:
public static void insertTableData(Connection dest, TableMetaData tableMetaData) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "INSERT INTO " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + ","; } sql = sql.substring(0, sql.length() - 1); sql += ") VALUES ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += "?" + ","; } sql = sql.substring(0, sql.length() - 1); sql += ")"; IOHelper.writeInfo(sql); ps = dest.prepareStatement(sql); for (Row r : tableMetaData.getData()) { try { int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { IOHelper.writeInfo(columnName + " = " + r.getRowData().get(columnName)); ps.setObject(param, r.getRowData().get(columnName)); } param++; } if (ps.executeUpdate() != 1) { dest.rollback(); updateTableData(dest, tableMetaData, r); } } catch (Exception ex) { try { dest.rollback(); updateTableData(dest, tableMetaData, r); } catch (Exception ex2) { IOHelper.writeError("Error in update " + sql, ex2); } } ps.clearParameters(); } dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } }
Code Sample 2:
private static String getBase64(String text, String algorithm) throws NoSuchAlgorithmException { AssertUtility.notNull(text); AssertUtility.notNullAndNotSpace(algorithm); String base64; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(text.getBytes()); base64 = new BASE64Encoder().encode(md.digest()); return base64; }
|
00
|
Code Sample 1:
public String kodetu(String testusoila) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(testusoila.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { new MezuLeiho("Ez da zifraketa algoritmoa aurkitu", "Ados", "Zifraketa Arazoa", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } catch (UnsupportedEncodingException e) { new MezuLeiho("Errorea kodetzerakoan", "Ados", "Kodeketa Errorea", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
@Override public void sendData(String serverUrl, String fileName, String type, InputStream is) throws IOException { ClientSession clientSession = null; try { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + serverUrl); } clientSession = (ClientSession) Connector.open(serverUrl); HeaderSet hsConnectReply = clientSession.connect(clientSession.createHeaderSet()); if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Connect Error " + hsConnectReply.getResponseCode()); } HeaderSet hsOperation = clientSession.createHeaderSet(); hsOperation.setHeader(HeaderSet.NAME, fileName); if (type != null) { hsOperation.setHeader(HeaderSet.TYPE, type); } hsOperation.setHeader(HeaderSet.LENGTH, new Long(is.available())); Operation po = clientSession.put(hsOperation); OutputStream os = po.openOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); if (logger.isDebugEnabled()) { logger.debug("put responseCode " + po.getResponseCode()); } po.close(); HeaderSet hsDisconnect = clientSession.disconnect(null); if (logger.isDebugEnabled()) { logger.debug("disconnect responseCode " + hsDisconnect.getResponseCode()); } if (hsDisconnect.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Send Error " + hsConnectReply.getResponseCode()); } } finally { if (clientSession != null) { try { clientSession.close(); } catch (IOException ignore) { if (logger.isDebugEnabled()) { logger.debug("IOException during clientSession.close()", ignore); } } } clientSession = null; } }
|
00
|
Code Sample 1:
public static HttpURLConnection getHttpConn(String urlStr, String Method) throws IOException { URL url = null; HttpURLConnection connection = null; url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod(Method); connection.setUseCaches(false); connection.connect(); return connection; }
Code Sample 2:
public static void concatFiles(List<File> sourceFiles, File destFile) throws IOException { FileOutputStream outFile = new FileOutputStream(destFile); FileChannel outChannel = outFile.getChannel(); for (File f : sourceFiles) { FileInputStream fis = new FileInputStream(f); FileChannel channel = fis.getChannel(); channel.transferTo(0, channel.size(), outChannel); channel.close(); fis.close(); } outChannel.close(); }
|
00
|
Code Sample 1:
private void storeConfigurationPropertiesFile(java.net.URL url, String comp) { java.util.Properties p; try { p = new java.util.Properties(); p.load(url.openStream()); } catch (java.io.IOException ie) { System.err.println("error opening: " + url.getPath() + ": " + ie.getMessage()); return; } storeConfiguration(p, comp); return; }
Code Sample 2:
@Override public String getPath() { InputStream in = null; OutputStream out = null; File file = null; try { file = File.createTempFile("java-storage_" + RandomStringUtils.randomAlphanumeric(32), ".tmp"); file.deleteOnExit(); out = new FileOutputStream(file); in = openStream(); IOUtils.copy(in, out); } catch (IOException e) { throw new RuntimeException(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } if (file != null && file.exists()) { return file.getPath(); } return null; }
|
00
|
Code Sample 1:
public static void main(String[] args) { File container = new File(ArchiveFeature.class.getProtectionDomain().getCodeSource().getLocation().toURI()); if (container == null) { throw new RuntimeException("this use-case isn't being invoked from the executable jar"); } JarFile jarFile = new JarFile(container); String artifactName = PROJECT_DIST_ARCHIVE + ".tar.gz"; File artifactFile = new File(".", artifactName); ZipEntry artifactEntry = jarFile.getEntry(artifactName); InputStream source = jarFile.getInputStream(artifactEntry); try { FileOutputStream dest = new FileOutputStream(artifactFile); try { IOUtils.copy(source, dest); } finally { IOUtils.closeQuietly(dest); } } finally { IOUtils.closeQuietly(source); } Project project = new Project(); project.setName("project"); project.init(); Target target = new Target(); target.setName("target"); project.addTarget(target); project.addBuildListener(new Log4jListener()); Untar untar = new Untar(); untar.setTaskName("untar"); untar.setSrc(artifactFile); untar.setDest(new File(".")); Untar.UntarCompressionMethod method = new Untar.UntarCompressionMethod(); method.setValue("gzip"); untar.setCompression(method); untar.setProject(project); untar.setOwningTarget(target); target.addTask(untar); untar.execute(); }
Code Sample 2:
private void retrieveClasses(URL url, Map<String, T> cmds) { try { String resource = URLDecoder.decode(url.getPath(), "UTF-8"); File directory = new File(resource); if (directory.exists()) { String[] files = directory.list(); for (String file : files) { if (file.endsWith(".class")) { addInstanceIfCommand(pckgname + '.' + file.substring(0, file.length() - 6), cmds); } } } else { JarURLConnection con = (JarURLConnection) url.openConnection(); String starts = con.getEntryName(); Enumeration<JarEntry> entriesEnum = con.getJarFile().entries(); while (entriesEnum.hasMoreElements()) { ZipEntry entry = (ZipEntry) entriesEnum.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) { classname = classname.substring(1); } classname = classname.replace('/', '.'); addInstanceIfCommand(classname, cmds); } } } } catch (IOException ioe) { LOG.warning("couldn't retrieve classes of " + url + ". Reason: " + ioe); } }
|
11
|
Code Sample 1:
public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } }
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:
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 void loginMD5() throws Exception { GetMethod get = new GetMethod("http://login.yahoo.com/config/login?.src=www&.done=http://www.yahoo.com"); get.setRequestHeader("user-agent", "Mozilla/5.0 (Macintosh; U; PPC MacOS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1"); client.executeMethod(get); parseResponse(get.getResponseBodyAsStream()); MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes("US-ASCII")); String hash1 = new String(digest.digest(), "US-ASCII"); String hash2 = hash1 + challenge; digest.update(hash2.getBytes("US-ASCII")); String hash = new String(digest.digest(), "US-ASCII"); NameValuePair[] pairs = { new NameValuePair("login", login), new NameValuePair("password", hash), new NameValuePair(".save", "1"), new NameValuePair(".tries", "1"), new NameValuePair(".src", "www"), new NameValuePair(".md5", "1"), new NameValuePair(".hash", "1"), new NameValuePair(".js", "1"), new NameValuePair(".last", ""), new NameValuePair(".promo", ""), new NameValuePair(".intl", "us"), new NameValuePair(".bypass", ""), new NameValuePair(".u", u), new NameValuePair(".v", "0"), new NameValuePair(".challenge", challenge), new NameValuePair(".yplus", ""), new NameValuePair(".emailCode", ""), new NameValuePair("pkg", ""), new NameValuePair("stepid", ""), new NameValuePair(".ev", ""), new NameValuePair("hasMsgr", "0"), new NameValuePair(".chkP", "Y"), new NameValuePair(".done", "http://www.yahoo.com"), new NameValuePair(".persistent", "y") }; get = new GetMethod("http://login.yahoo.com/config/login"); get.setRequestHeader("user-agent", "Mozilla/5.0 (Macintosh; U; PPC MacOS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1"); get.addRequestHeader("Accept", "*/*"); get.addRequestHeader("Accept-Language", "en-us, ja;q=0.21, de-de;q=0.86, de;q=0.79, fr-fr;q=0.71, fr;q=0.64, nl-nl;q=0.57, nl;q=0.50, it-it;q=0.43, it;q=0.36, ja-jp;q=0.29, en;q=0.93, es-es;q=0.14, es;q=0.07"); get.setQueryString(pairs); client.executeMethod(get); get.getResponseBodyAsString(); }
|
11
|
Code Sample 1:
public Blowfish(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { System.out.println(e); } m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); }
Code Sample 2:
public static String hashString(String pwd) { StringBuffer hex = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pwd.getBytes()); byte[] d = md.digest(); String plaintxt; for (int i = 0; i < d.length; i++) { plaintxt = Integer.toHexString(0xFF & d[i]); if (plaintxt.length() < 2) { plaintxt = "0" + plaintxt; } hex.append(plaintxt); } } catch (NoSuchAlgorithmException nsae) { } return hex.toString(); }
|
00
|
Code Sample 1:
public void downloadQFromMinibix(int ticketNo) { String minibixDomain = Preferences.userRoot().node("Spectatus").get("MBAddr", "http://mathassess.caret.cam.ac.uk"); String minibixPort = Preferences.userRoot().node("Spectatus").get("MBPort", "80"); String url = minibixDomain + ":" + minibixPort + "/qtibank-webserv/deposits/all/" + ticketNo; File file = new File(tempdir + sep + "minibix.zip"); try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); int l; byte[] tmp = new byte[2048]; while ((l = instream.read(tmp)) != -1) { out.write(tmp, 0, l); } out.close(); instream.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void buildCache() { XMLCacheBuilder cacheBuilder = CompositePageUtil.getCacheBuilder(); String postFix = ""; if (cacheBuilder.getPostFix() != null && !cacheBuilder.getPostFix().equals("")) { postFix = "." + cacheBuilder.getPostFix(); } String basePath = cacheBuilder.getBasePath(); List actions = CompositePageUtil.getXMLActions(); for (int i = 0; i < actions.size(); i++) { try { XMLAction action = (XMLAction) actions.get(i); if (action.getEscapeCacheBuilder() != null && action.getEscapeCacheBuilder().equals("true")) continue; String actionUrl = basePath + action.getName() + postFix; URL url = new URL(actionUrl); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setDoInput(true); huc.setDoOutput(true); huc.setUseCaches(false); huc.setRequestProperty("Content-Type", "text/html"); DataOutputStream dos = new DataOutputStream(huc.getOutputStream()); dos.flush(); dos.close(); huc.disconnect(); } catch (MalformedURLException e) { logger.error(e); e.printStackTrace(); } catch (IOException e) { logger.equals(e); e.printStackTrace(); } } }
|
00
|
Code Sample 1:
private static void copyFile(String srFile, String dtFile) { try { File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } catch (FileNotFoundException ex) { System.out.println("Error copying " + srFile + " to " + dtFile); System.out.println(ex.getMessage() + " in the specified directory."); } catch (IOException e) { System.out.println(e.getMessage()); } }
Code Sample 2:
public static String shaEncrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] shahash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } shahash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < shahash.length; i++) { if (Integer.toHexString(0xFF & shahash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & shahash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & shahash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; }
|
11
|
Code Sample 1:
public static void copy(final File src, final File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); }
Code Sample 2:
public void convert(File file, String fromEncoding, String toEncoding) throws IOException { InputStream in = new FileInputStream(file); StringWriter cache = new StringWriter(); Reader reader = new InputStreamReader(in, fromEncoding); char[] buffer = new char[128]; int read; while ((read = reader.read(buffer)) > -1) { cache.write(buffer, 0, read); } reader.close(); in.close(); Log.warn(this, "read from file " + file + " (" + fromEncoding + "):" + cache); OutputStream out = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(out, toEncoding); writer.write(cache.toString()); cache.close(); writer.close(); out.close(); }
|
00
|
Code Sample 1:
private String computeHash(String str) { StringBuffer hexBuffer = new StringBuffer(); byte[] bytes; int i; try { MessageDigest hashAlgorithm = MessageDigest.getInstance(hashAlgorithmName); hashAlgorithm.reset(); hashAlgorithm.update(str.getBytes()); bytes = hashAlgorithm.digest(); } catch (NoSuchAlgorithmException e) { return null; } for (i = 0; i < bytes.length; i++) hexBuffer.append(((bytes[i] >= 0 && bytes[i] <= 15) ? "0" : "") + Integer.toHexString(bytes[i] & 0xFF)); return hexBuffer.toString(); }
Code Sample 2:
public String contentType() { if (_contentType != null) { return (String) _contentType; } String uti = null; URL url = url(); System.out.println("OKIOSIDManagedObject.contentType(): url = " + url + "\n"); if (url != null) { String contentType = null; try { contentType = url.openConnection().getContentType(); } catch (java.io.IOException e) { System.out.println("OKIOSIDManagedObject.contentType(): couldn't open URL connection!\n"); return UTType.Item; } if (contentType != null) { System.out.println("OKIOSIDManagedObject.contentType(): contentType = " + contentType + "\n"); uti = UTType.preferredIdentifierForTag(UTType.MIMETypeTagClass, contentType, null); } if (uti == null) { uti = UTType.Item; } } else { uti = UTType.Item; } _contentType = uti; System.out.println("OKIOSIDManagedObject.contentType(): uti = " + uti + "\n"); return uti; }
|
00
|
Code Sample 1:
public static byte[] getbytes(String host, int port, String cmd) { String result = "GetHtmlFromServer no answer"; String tmp = ""; result = ""; try { tmp = "http://" + host + ":" + port + "/" + cmd; URL url = new URL(tmp); if (1 == 2) { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { result += str; } in.close(); return result.getBytes(); } else { HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setConnectTimeout(2 * 1000); c.setRequestMethod("GET"); c.connect(); int amt = c.getContentLength(); InputStream in = c.getInputStream(); MojasiWriter writer = new MojasiWriter(); byte[] buff = new byte[256]; while (writer.size() < amt) { int got = in.read(buff); if (got < 0) break; writer.pushBytes(buff, got); } in.close(); c.disconnect(); return writer.getBytes(); } } catch (MalformedURLException e) { System.err.println(tmp + " " + e); } catch (IOException e) { ; } return null; }
Code Sample 2:
public void dumpDB(String in, String out) { try { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (Exception e) { Log.d("exception", e.toString()); } }
|
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 Main(String[] args) { boolean encrypt = false; if (args[0].compareTo("-e") == 0) { encrypt = true; } else if (args[0].compareTo("-d") == 0) { encrypt = false; } else { System.out.println("first argument is invalid"); System.exit(-2); } char[] password = new char[args[2].length()]; for (int i = 0; i < args[2].length(); i++) { password[i] = (char) args[2].getBytes()[i]; } try { InitializeCipher(encrypt, password); } catch (Exception e) { System.out.println("error initializing cipher"); System.exit(-3); } try { InputStream is = new FileInputStream(args[1]); OutputStream os; int read, max = 10; byte[] buffer = new byte[max]; if (encrypt) { os = new FileOutputStream(args[1] + ".enc"); os = new CipherOutputStream(os, cipher); } else { os = new FileOutputStream(args[1] + ".dec"); is = new CipherInputStream(is, cipher); } read = is.read(buffer); while (read != -1) { os.write(buffer, 0, read); read = is.read(buffer); } while (read == max) ; os.close(); is.close(); System.out.println(new String(buffer)); } catch (Exception e) { System.out.println("error encrypting/decrypting message:"); e.printStackTrace(); System.exit(-4); } System.out.println("done"); }
|
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 void addClasses(URL url) { BufferedReader reader = null; String line; ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { line = line.trim(); if ((line.length() == 0) || line.startsWith(";")) { continue; } try { classes.add(Class.forName(line, true, cl)); } catch (Throwable t) { } } } catch (Throwable t) { } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } }
|
00
|
Code Sample 1:
public Project createProject(int testbedID, String name, String description) throws AdaptationException { Project project = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "INSERT INTO Projects(testbedID, name, " + "description) VALUES (" + testbedID + ", '" + name + "', '" + description + "')"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * FROM Projects WHERE " + " testbedID = " + testbedID + " AND " + " name = '" + name + "' AND " + " description = '" + description + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to create project failed."; log.error(msg); throw new AdaptationException(msg); } project = getProject(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in createProject"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return project; }
Code Sample 2:
public void getZipFiles(String filename) { try { String destinationname = "c:\\mods\\peu\\"; byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; zipinputstream = new ZipInputStream(new FileInputStream(filename)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); System.out.println("entryname " + entryName); int n; FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(destinationname + entryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n); fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
int doOne(int bid, int tid, int aid, int delta) { int aBalance = 0; if (Conn == null) { incrementFailedTransactionCount(); return 0; } try { if (prepared_stmt) { pstmt1.setInt(1, delta); pstmt1.setInt(2, aid); pstmt1.executeUpdate(); pstmt1.clearWarnings(); pstmt2.setInt(1, aid); ResultSet RS = pstmt2.executeQuery(); pstmt2.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } pstmt3.setInt(1, delta); pstmt3.setInt(2, tid); pstmt3.executeUpdate(); pstmt3.clearWarnings(); pstmt4.setInt(1, delta); pstmt4.setInt(2, bid); pstmt4.executeUpdate(); pstmt4.clearWarnings(); pstmt5.setInt(1, tid); pstmt5.setInt(2, bid); pstmt5.setInt(3, aid); pstmt5.setInt(4, delta); pstmt5.executeUpdate(); pstmt5.clearWarnings(); } else { Statement Stmt = Conn.createStatement(); String Query = "UPDATE accounts "; Query += "SET Abalance = Abalance + " + delta + " "; Query += "WHERE Aid = " + aid; int res = Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "SELECT Abalance "; Query += "FROM accounts "; Query += "WHERE Aid = " + aid; ResultSet RS = Stmt.executeQuery(Query); Stmt.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } Query = "UPDATE tellers "; Query += "SET Tbalance = Tbalance + " + delta + " "; Query += "WHERE Tid = " + tid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "UPDATE branches "; Query += "SET Bbalance = Bbalance + " + delta + " "; Query += "WHERE Bid = " + bid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "INSERT INTO history(Tid, Bid, Aid, delta) "; Query += "VALUES ("; Query += tid + ","; Query += bid + ","; Query += aid + ","; Query += delta + ")"; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Stmt.close(); } if (transactions) { Conn.commit(); } return aBalance; } catch (Exception E) { if (verbose) { System.out.println("Transaction failed: " + E.getMessage()); E.printStackTrace(); } incrementFailedTransactionCount(); if (transactions) { try { Conn.rollback(); } catch (SQLException E1) { } } } return 0; }
Code Sample 2:
public MoteDeploymentConfiguration addMoteDeploymentConfiguration(int projectDepConfID, int moteID, int programID, int radioPowerLevel) throws AdaptationException { MoteDeploymentConfiguration mdc = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "INSERT INTO MoteDeploymentConfigurations(" + "projectDeploymentConfigurationID, " + "moteID, programID, radioPowerLevel) VALUES (" + projectDepConfID + ", " + moteID + ", " + programID + ", " + radioPowerLevel + ")"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from MoteDeploymentConfigurations WHERE " + "projectDeploymentConfigurationID = " + projectDepConfID + " AND moteID = " + moteID; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Unable to select newly added config."; log.error(msg); ; throw new AdaptationException(msg); } mdc = getMoteDeploymentConfiguration(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in addMoteDeploymentConfiguration"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return mdc; }
|
00
|
Code Sample 1:
public static synchronized void loadConfig(String configFile) { if (properties != null) { return; } URL url = null; InputStream is = null; try { String configProperty = null; try { configProperty = System.getProperty("dspace.configuration"); } catch (SecurityException se) { log.warn("Unable to access system properties, ignoring.", se); } if (loadedFile != null) { log.info("Reloading current config file: " + loadedFile.getAbsolutePath()); url = loadedFile.toURI().toURL(); } else if (configFile != null) { log.info("Loading provided config file: " + configFile); loadedFile = new File(configFile); url = loadedFile.toURI().toURL(); } else if (configProperty != null) { log.info("Loading system provided config property (-Ddspace.configuration): " + configProperty); loadedFile = new File(configProperty); url = loadedFile.toURI().toURL(); } else { url = ConfigurationManager.class.getResource("/dspace.cfg"); if (url != null) { log.info("Loading from classloader: " + url); loadedFile = new File(url.getPath()); } } if (url == null) { log.fatal("Cannot find dspace.cfg"); throw new IllegalStateException("Cannot find dspace.cfg"); } else { properties = new Properties(); moduleProps = new HashMap<String, Properties>(); is = url.openStream(); properties.load(is); for (Enumeration<?> pe = properties.propertyNames(); pe.hasMoreElements(); ) { String key = (String) pe.nextElement(); String value = interpolate(key, properties.getProperty(key), 1); if (value != null) { properties.setProperty(key, value); } } } } catch (IOException e) { log.fatal("Can't load configuration: " + url, e); throw new IllegalStateException("Cannot load configuration: " + url, e); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { } } } File licenseFile = new File(getProperty("dspace.dir") + File.separator + "config" + File.separator + "default.license"); FileInputStream fir = null; InputStreamReader ir = null; BufferedReader br = null; try { fir = new FileInputStream(licenseFile); ir = new InputStreamReader(fir, "UTF-8"); br = new BufferedReader(ir); String lineIn; license = ""; while ((lineIn = br.readLine()) != null) { license = license + lineIn + '\n'; } br.close(); } catch (IOException e) { log.fatal("Can't load license: " + licenseFile.toString(), e); throw new IllegalStateException("Cannot load license: " + licenseFile.toString(), e); } finally { if (br != null) { try { br.close(); } catch (IOException ioe) { } } if (ir != null) { try { ir.close(); } catch (IOException ioe) { } } if (fir != null) { try { fir.close(); } catch (IOException ioe) { } } } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } out.setLastModified(in.lastModified()); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
11
|
Code Sample 1:
public boolean updatenum(int num, String pid) { boolean flag = false; Connection conn = null; PreparedStatement pm = null; try { conn = Pool.getConnection(); conn.setAutoCommit(false); pm = conn.prepareStatement("update addwuliao set innum=? where pid=?"); pm.setInt(1, num); pm.setString(2, pid); int a = pm.executeUpdate(); if (a == 0) { flag = false; } else { flag = true; } conn.commit(); Pool.close(pm); Pool.close(conn); } catch (Exception e) { e.printStackTrace(); flag = false; try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } Pool.close(pm); Pool.close(conn); } finally { Pool.close(pm); Pool.close(conn); } return flag; }
Code Sample 2:
static final void saveStatus(JWAIMStatus status, DBConnector connector) throws IOException { Connection con = null; PreparedStatement ps = null; Statement st = null; try { con = connector.getDB(); con.setAutoCommit(false); st = con.createStatement(); st.executeUpdate("DELETE FROM status"); ps = con.prepareStatement("INSERT INTO status VALUES (?, ?)"); ps.setString(1, "jwaim.status"); ps.setBoolean(2, status.getJWAIMStatus()); ps.addBatch(); ps.setString(1, "logging.status"); ps.setBoolean(2, status.getLoggingStatus()); ps.addBatch(); ps.setString(1, "stats.status"); ps.setBoolean(2, status.getStatsStatus()); ps.addBatch(); ps.executeBatch(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } throw new IOException(e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (SQLException ignore) { } } if (ps != null) { try { ps.close(); } catch (SQLException ignore) { } } if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } }
|
11
|
Code Sample 1:
public static synchronized String encrypt(String plaintextPassword) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e); } try { md.update(plaintextPassword.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static String encrypt(String text) { char[] toEncrypt = text.toCharArray(); StringBuffer hexString = new StringBuffer(); try { MessageDigest dig = MessageDigest.getInstance("MD5"); dig.reset(); String pw = ""; for (int i = 0; i < toEncrypt.length; i++) { pw += toEncrypt[i]; } dig.update(pw.getBytes()); byte[] digest = dig.digest(); int digestLength = digest.length; for (int i = 0; i < digestLength; i++) { hexString.append(hexDigit(digest[i])); } } catch (java.security.NoSuchAlgorithmException ae) { ae.printStackTrace(); } return hexString.toString(); }
|
00
|
Code Sample 1:
public LogoutHandler(String username, String token) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Security.groovy?method=LogOut&username=" + username + "&authentication_token=" + token); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("response"); String status = ((Element) nl.item(0)).getAttributes().item(0).getTextContent(); if (status.toString().equals("fail")) { return; } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private final boolean copy_to_file_nio(File src, File dst) throws IOException { FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(src).getChannel(); dstChannel = new FileOutputStream(dst).getChannel(); { int safe_max = (64 * 1024 * 1024) / 4; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, safe_max, dstChannel); } } return true; } finally { try { if (srcChannel != null) srcChannel.close(); } catch (IOException e) { Debug.debug(e); } try { if (dstChannel != null) dstChannel.close(); } catch (IOException e) { Debug.debug(e); } } }
|
00
|
Code Sample 1:
public boolean addFavBoard(BoardObject board) throws NetworkException, ContentException { String url = HttpConfig.bbsURL() + HttpConfig.BBS_FAV_ADD + board.getId(); HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(url); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (HTTPUtil.isHttp200(response) && HTTPUtil.isXmlContentType(response)) { HTTPUtil.consume(response.getEntity()); return true; } else { String msg = BBSBodyParseHelper.parseFailMsg(entity); throw new ContentException(msg); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new NetworkException(e); } catch (IOException e) { e.printStackTrace(); throw new NetworkException(e); } }
Code Sample 2:
@Override public Collection<IAuthor> doImport() throws Exception { progress.initialize(2, "Ściągam autorów amerykańskich"); String url = "http://pl.wikipedia.org/wiki/Kategoria:Ameryka%C5%84scy_autorzy_fantastyki"; UrlResource resource = new UrlResource(url); InputStream urlInputStream = resource.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(urlInputStream, writer); progress.advance("Parsuję autorów amerykańskich"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); String httpDoc = writer.toString(); httpDoc = httpDoc.replaceFirst("(?s)<!DOCTYPE.+?>\\n", ""); httpDoc = httpDoc.replaceAll("(?s)<script.+?</script>", ""); httpDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" + httpDoc; ByteArrayInputStream byteInputStream = new ByteArrayInputStream(httpDoc.getBytes("UTF-8")); Document doc = builder.parse(byteInputStream); ArrayList<String> authorNames = new ArrayList<String>(); ArrayList<IAuthor> authors = new ArrayList<IAuthor>(); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); NodeList list = (NodeList) xpath.evaluate("//ul/li/div/div/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } list = (NodeList) xpath.evaluate("//td/ul/li/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } for (String name : authorNames) { int idx = name.lastIndexOf(' '); String fname = name.substring(0, idx).trim(); String lname = name.substring(idx + 1).trim(); authors.add(new Author(fname, lname)); } progress.advance("Wykonano"); return authors; }
|
00
|
Code Sample 1:
void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
Code Sample 2:
public static String MD5(String text) { byte[] md5hash = new byte[32]; try { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (Exception e) { e.printStackTrace(); } return convertToHex(md5hash); }
|
11
|
Code Sample 1:
private static byte[] calcMd5(String pass) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pass.getBytes(), 0, pass.length()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm found"); throw new RuntimeException(e); } }
Code Sample 2:
public static String getDigest(String seed, String code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } }
|
00
|
Code Sample 1:
public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; boolean ok = true; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; }
Code Sample 2:
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (text == null || text.length() < 1) { return null; } MessageDigest md = MessageDigest.getInstance(TYPE_SHA); md.update(text.getBytes(ENCODE), 0, text.length()); byte[] sha1hash = new byte[40]; sha1hash = md.digest(); return convertToHexFormat(sha1hash); }
|
11
|
Code Sample 1:
public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } }
Code Sample 2:
public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
|
11
|
Code Sample 1:
private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } }
Code Sample 2:
public void testCreate() throws Exception { File f = File.createTempFile("DiskCacheItemTest", "tmp"); f.deleteOnExit(); try { DiskCacheItem i = new DiskCacheItem(f); i.setLastModified(200005L); i.setTranslationCount(11); i.setEncoding("GB2312"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] chineseText = new byte[] { -42, -48, -46, -30, 87, 101, 98, 46, 99, 111, 109, 32, -54, -57, -46, -69, -72, -10, -61, -26, -49, -14, -42, -48, -50, -60, -45, -61, -69, -89, -95, -94, -67, -23, -55, -36, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -42, -48, -50, -60, -51, -8, -43, -66, -93, -84, -54, -57, -46, -69, -68, -36, -51, -88, -49, -14, -74, -85, -73, -67, -75, -60, -51, -8, -62, -25, -57, -59, -63, -70, -93, -84, -53, -4, -75, -60, -60, -65, -75, -60, -44, -38, -45, -38, -80, -17, -42, -6, -78, -69, -74, -49, -73, -94, -43, -71, -41, -77, -76, -13, -75, -60, -58, -13, -46, -75, -68, -28, -67, -8, -48, -48, -49, -32, -69, -91, -63, -86, -49, -75, -67, -45, -76, -91, -95, -93, -50, -46, -61, -57, -49, -32, -48, -59, -93, -84, -42, -48, -50, -60, -45, -61, -69, -89, -67, -85, -69, -31, -51, -88, -71, -3, -79, -66, -51, -8, -43, -66, -93, -84, -43, -46, -75, -67, -45, -48, -71, -40, -46, -47, -45, -21, -42, -48, -71, -6, -58, -13, -46, -75, -67, -88, -63, -94, -70, -49, -41, -9, -67, -69, -51, -7, -71, -40, -49, -75, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -93, -84, -69, -14, -45, -48, -46, -30, -45, -21, -42, -48, -71, -6, 32, -58, -13, -46, -75, -67, -8, -48, -48, -70, -49, -41, -9, -67, -69, -51, -7, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -45, -48, -45, -61, -48, -59, -49, -94, -41, -54, -63, -49, -95, -93 }; { InputStream input = new ByteArrayInputStream(chineseText); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("GB2312", i.getEncoding()); assertEquals(200005L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[279]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } { FileInputStream input = new FileInputStream(f); StringWriter w = new StringWriter(); try { IOUtils.copy(input, w, "GB2312"); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); } assertEquals(new String(chineseText, "GB2312"), w.toString()); } { FileInputStream input = new FileInputStream(f); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } assertTrue(Arrays.equals(chineseText, output.toByteArray())); } } finally { f.delete(); } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.