label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
| Code Sample 1:
private static String loadUrlToString(String a_url) throws IOException { URL l_url1 = new URL(a_url); BufferedReader br = new BufferedReader(new InputStreamReader(l_url1.openStream())); String l_content = ""; String l_ligne = null; l_content = br.readLine(); while ((l_ligne = br.readLine()) != null) { l_content += AA.SL + l_ligne; } return l_content; }
Code Sample 2:
public static String deleteTag(String tag_id) { String so = OctopusErrorMessages.UNKNOWN_ERROR; if (tag_id == null || tag_id.trim().equals("")) { return OctopusErrorMessages.TAG_ID_CANT_BE_EMPTY; } DBConnection theConnection = null; try { theConnection = DBServiceManager.allocateConnection(); theConnection.setAutoCommit(false); String query = "DELETE FROM tr_translation WHERE tr_translation_trtagid=?"; PreparedStatement state = theConnection.prepareStatement(query); state.setString(1, tag_id); state.executeUpdate(); String query2 = "DELETE FROM tr_tag WHERE tr_tag_id=? "; PreparedStatement state2 = theConnection.prepareStatement(query2); state2.setString(1, tag_id); state2.executeUpdate(); theConnection.commit(); so = OctopusErrorMessages.ACTION_DONE; } catch (SQLException e) { try { theConnection.rollback(); } catch (SQLException ex) { } so = OctopusErrorMessages.ERROR_DATABASE; } finally { if (theConnection != null) { try { theConnection.setAutoCommit(true); } catch (SQLException ex) { } theConnection.release(); } } return so; } |
11
| Code Sample 1:
@Test public void testCopy() throws IOException { final byte[] input = { 0x00, 0x01, 0x7F, 0x03, 0x40 }; final byte[] verification = input.clone(); Assert.assertNotSame("Expecting verification to be a new array.", input, verification); final ByteArrayInputStream in = new ByteArrayInputStream(input); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); final byte[] output = out.toByteArray(); Assert.assertTrue("Expecting input to be unchanged.", Arrays.equals(verification, input)); Assert.assertTrue("Expecting output to be like input.", Arrays.equals(verification, output)); Assert.assertNotSame("Expecting output to be a new array.", input, output); Assert.assertNotSame("Expecting output to be a new array.", verification, output); }
Code Sample 2:
private static void createCompoundData(String dir, String type) { try { Set s = new HashSet(); File nouns = new File(dir + "index." + type); FileInputStream fis = new FileInputStream(nouns); InputStreamReader reader = new InputStreamReader(fis); StringBuffer sb = new StringBuffer(); int chr = reader.read(); while (chr >= 0) { if (chr == '\n' || chr == '\r') { String line = sb.toString(); if (line.length() > 0) { String[] spaceSplit = PerlHelp.split(line); for (int i = 0; i < spaceSplit.length; i++) { if (spaceSplit[i].indexOf('_') >= 0) { s.add(spaceSplit[i].replace('_', ' ')); } } } sb.setLength(0); } else { sb.append((char) chr); } chr = reader.read(); } System.out.println(type + " size=" + s.size()); File output = new File(dir + "compound." + type + "s.gz"); FileOutputStream fos = new FileOutputStream(output); GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos)); PrintWriter writer = new PrintWriter(gzos); writer.println("# This file was extracted from WordNet data, the following copyright notice"); writer.println("# from WordNet is attached."); writer.println("#"); writer.println("# This software and database is being provided to you, the LICENSEE, by "); writer.println("# Princeton University under the following license. By obtaining, using "); writer.println("# and/or copying this software and database, you agree that you have "); writer.println("# read, understood, and will comply with these terms and conditions.: "); writer.println("# "); writer.println("# Permission to use, copy, modify and distribute this software and "); writer.println("# database and its documentation for any purpose and without fee or "); writer.println("# royalty is hereby granted, provided that you agree to comply with "); writer.println("# the following copyright notice and statements, including the disclaimer, "); writer.println("# and that the same appear on ALL copies of the software, database and "); writer.println("# documentation, including modifications that you make for internal "); writer.println("# use or for distribution. "); writer.println("# "); writer.println("# WordNet 1.7 Copyright 2001 by Princeton University. All rights reserved. "); writer.println("# "); writer.println("# THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR "); writer.println("# IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- "); writer.println("# ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE "); writer.println("# OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT "); writer.println("# INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR "); writer.println("# OTHER RIGHTS. "); writer.println("# "); writer.println("# The name of Princeton University or Princeton may not be used in"); writer.println("# advertising or publicity pertaining to distribution of the software"); writer.println("# and/or database. Title to copyright in this software, database and"); writer.println("# any associated documentation shall at all times remain with"); writer.println("# Princeton University and LICENSEE agrees to preserve same. "); for (Iterator i = s.iterator(); i.hasNext(); ) { String mwe = (String) i.next(); writer.println(mwe); } writer.close(); } catch (Exception e) { e.printStackTrace(); } } |
00
| Code Sample 1:
private String fetchContent() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { buf.append(str); } return buf.toString(); }
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 void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); try { String content = ""; URL url = new URL(request.getParameter("url")); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { content += line + "\n"; } in.close(); String result = getResult(content); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println(result); } catch (Exception e) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(getErrorPage(e)); } }
Code Sample 2:
@Test(expected = GadgetException.class) public void badFetchServesCached() throws Exception { HttpRequest firstRequest = createCacheableRequest(); expect(pipeline.execute(firstRequest)).andReturn(new HttpResponse(LOCAL_SPEC_XML)).once(); HttpRequest secondRequest = createIgnoreCacheRequest(); expect(pipeline.execute(secondRequest)).andReturn(HttpResponse.error()).once(); replay(pipeline); GadgetSpec original = specFactory.getGadgetSpec(createContext(SPEC_URL, false)); GadgetSpec cached = specFactory.getGadgetSpec(createContext(SPEC_URL, true)); assertEquals(original.getUrl(), cached.getUrl()); assertEquals(original.getChecksum(), cached.getChecksum()); } |
11
| Code Sample 1:
protected InputStream callApiMethod(String apiUrl, String xmlContent, String contentType, String method, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.setRequestMethod(method); request.setDoOutput(true); if (contentType != null) { request.setRequestProperty("Content-Type", contentType); } if (xmlContent != null) { PrintStream out = new PrintStream(new BufferedOutputStream(request.getOutputStream())); out.print(xmlContent); out.flush(); out.close(); } request.connect(); if (request.getResponseCode() != expected) { throw new BingMapsException(convertStreamToString(request.getErrorStream())); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingMapsException(e); } }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } |
00
| Code Sample 1:
protected void doBackupOrganizeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strSelQuery = "SELECT organize_id,organize_type_id,child_id,child_type_id,remark " + "FROM " + Common.ORGANIZE_RELATION_TABLE; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_RELATION_B_TABLE + " " + "(version_no,organize_id,organize_type,child_id,child_type,remark) " + "VALUES (?,?,?,?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strSelQuery); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setInt(1, this.versionNO); ps.setString(2, result.getString("organize_id")); ps.setString(3, result.getString("organize_type_id")); ps.setString(4, result.getString("child_id")); ps.setString(5, result.getString("child_type_id")); ps.setString(6, result.getString("remark")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_RELATION_B INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doBackupOrganizeRelation(): SQLException while committing or rollback"); } }
Code Sample 2:
public static void replaceAll(File file, String substitute, String substituteReplacement) throws IOException { log.debug("Replace " + substitute + " by " + substituteReplacement); Pattern pattern = Pattern.compile(substitute); FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); int sz = (int) fc.size(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); Charset charset = Charset.forName("ISO-8859-15"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer cb = decoder.decode(bb); Matcher matcher = pattern.matcher(cb); String outString = matcher.replaceAll(substituteReplacement); log.debug(outString); FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); PrintStream ps = new PrintStream(fos); ps.print(outString); ps.close(); fos.close(); } |
00
| Code Sample 1:
@Override public void executeInterruptible() { encodingTerminated = false; File destinationFile = null; try { Runtime runtime = Runtime.getRuntime(); IconAndFileListElement element; while ((element = getNextFileElement()) != null) { File origFile = element.getFile(); destinationFile = new File(encodeFileCard.getDestinationFolder().getValue(), origFile.getName()); if (!destinationFile.getParentFile().exists()) { destinationFile.getParentFile().mkdirs(); } actualFileLabel.setText(origFile.getName()); actualFileModel.setMaximum((int) origFile.length()); actualFileModel.setValue(0); int bitrate; synchronized (bitratePattern) { Matcher bitrateMatcher = bitratePattern.matcher(encodeFileCard.getBitrate().getValue()); bitrateMatcher.find(); bitrate = Integer.parseInt(bitrateMatcher.group(1)); } List<String> command = new LinkedList<String>(); command.add(encoderFile.getCanonicalPath()); command.add("--mp3input"); command.add("-m"); command.add("j"); String sampleFreq = Settings.getSetting("encode.sample.freq"); if (Util.isNotEmpty(sampleFreq)) { command.add("--resample"); command.add(sampleFreq); } QualityElement quality = (QualityElement) ((JComboBox) encodeFileCard.getQuality().getValueComponent()).getSelectedItem(); command.add("-q"); command.add(Integer.toString(quality.getValue())); command.add("-b"); command.add(Integer.toString(bitrate)); command.add("--cbr"); command.add("-"); command.add(destinationFile.getCanonicalPath()); if (LOG.isDebugEnabled()) { StringBuilder commandLine = new StringBuilder(); boolean first = true; for (String part : command) { if (!first) commandLine.append(" "); commandLine.append(part); first = false; } LOG.debug("Command line: " + commandLine.toString()); } encodingProcess = runtime.exec(command.toArray(new String[0])); lastPosition = 0l; InputStream fileStream = null; try { fileStream = new PositionNotifierInputStream(new FileInputStream(origFile), origFile.length(), 2048, this); IOUtils.copy(fileStream, encodingProcess.getOutputStream()); encodingProcess.getOutputStream().close(); } finally { IOUtils.closeQuietly(fileStream); if (LOG.isDebugEnabled()) { InputStream processOut = null; try { processOut = encodingProcess.getInputStream(); StringWriter sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process output stream:\n" + sw); IOUtils.closeQuietly(processOut); processOut = encodingProcess.getErrorStream(); sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process error stream:\n" + sw); } finally { IOUtils.closeQuietly(processOut); } } } int result = encodingProcess.waitFor(); encodingProcess = null; if (result != 0) { LOG.warn("Encoder process returned error code " + result); } if (Boolean.parseBoolean(encodeFileCard.getCopyTag().getValue())) { MP3File mp3Input = new MP3File(origFile); MP3File mp3Output = new MP3File(destinationFile); boolean write = false; if (mp3Input.hasID3v2tag()) { ID3v2Tag id3v2Tag = new ID3v2Tag(); for (ID3v2Frame frame : mp3Input.getID3v2tag().getAllframes()) { id3v2Tag.addFrame(frame); } mp3Output.setID3v2tag(id3v2Tag); write = true; } if (mp3Input.hasID3v11tag()) { mp3Output.setID3v11tag(mp3Input.getID3v11tag()); write = true; } if (write) mp3Output.write(); } } actualFileLabel.setText(Messages.getString("operations.file.encode.execute.actualfile.terminated")); actualFileModel.setValue(actualFileModel.getMaximum()); } catch (Exception e) { LOG.error("Cannot encode files", e); if (!(e instanceof IOException && encodingTerminated)) MainWindowInterface.showError(e); if (destinationFile != null) destinationFile.delete(); } }
Code Sample 2:
@Test public void testTrim() throws Exception { TreeNode ast = TestUtil.readFileInAST("resources/SimpleTestFile.java"); DecoratorSelection ds = new DecoratorSelection(); XmlFileSystemRepository rep = new XmlFileSystemRepository(); XmlToFormatContentConverter converter = new XmlToFormatContentConverter(rep); URI url = new File("resources/javaDefaultFormats.xml").toURI(); InputStream is = url.toURL().openStream(); converter.convert(is); File f = new File("resources/javaDefaultFormats.xml").getAbsoluteFile(); converter.convert(f); String string = new File("resources/query.xml").getAbsolutePath(); Document qDoc = XmlUtil.loadXmlFromFile(string); Query query = new Query(qDoc); Format format = XfsrFormatManager.getInstance().getFormats("java", "signature only"); TokenAutoTrimmer.create("Java", "resources/java.autotrim"); Document doc = rep.getXmlContentTree(ast, query, format, ds).getOwnerDocument(); String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><sourcecode>main(String[])</sourcecode>"; ByteArrayOutputStream bout = new ByteArrayOutputStream(); XmlUtil.outputXml(doc, bout); String actual = bout.toString(); assertEquals(expected, actual); } |
11
| Code Sample 1:
public static void copyFromTo(String src, String des) { staticprintln("Copying:\"" + src + "\"\nto:\"" + des + "\""); try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(des).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
11
| Code Sample 1:
static byte[] getPassword(final String name, final String password) { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(name.getBytes()); messageDigest.update(password.getBytes()); return messageDigest.digest(); } catch (final NoSuchAlgorithmException e) { throw new JobException(e); } }
Code Sample 2:
public static String toMD5String(String plainText) { if (TextUtils.isEmpty(plainText)) { plainText = ""; } StringBuilder text = new StringBuilder(); for (int i = plainText.length() - 1; i >= 0; i--) { text.append(plainText.charAt(i)); } plainText = text.toString(); MessageDigest mDigest; try { mDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return plainText; } mDigest.update(plainText.getBytes()); byte d[] = mDigest.digest(); StringBuffer hash = new StringBuffer(); for (int i = 0; i < d.length; i++) { hash.append(Integer.toHexString(0xFF & d[i])); } return hash.toString(); } |
00
| Code Sample 1:
public static String getDocumentAsString(URL url) throws IOException { StringBuffer result = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF8")); String line = ""; while (line != null) { result.append(line); line = in.readLine(); } return result.toString(); }
Code Sample 2:
public boolean loadURL(URL url) { try { _properties.load(url.openStream()); Argo.log.info("Configuration loaded from " + url + "\n"); return true; } catch (Exception e) { if (_canComplain) Argo.log.warn("Unable to load configuration " + url + "\n"); _canComplain = false; return false; } } |
11
| Code Sample 1:
public static void concatenateToDestFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { if (!destFile.createNewFile()) { throw new IllegalArgumentException("Could not create destination file:" + destFile.getName()); } } BufferedOutputStream bufferedOutputStream = null; BufferedInputStream bufferedInputStream = null; byte[] buffer = new byte[1024]; try { bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFile, true)); bufferedInputStream = new BufferedInputStream(new FileInputStream(sourceFile)); while (true) { int readByte = bufferedInputStream.read(buffer, 0, buffer.length); if (readByte == -1) { break; } bufferedOutputStream.write(buffer, 0, readByte); } } finally { if (bufferedOutputStream != null) { bufferedOutputStream.close(); } if (bufferedInputStream != null) { bufferedInputStream.close(); } } }
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; } |
00
| Code Sample 1:
private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } }
Code Sample 2:
HttpURLConnection getHttpURLConnection(String bizDocToExecute, boolean doom, boolean cmt) { StringBuffer servletURL = new StringBuffer(); servletURL.append(getBaseServletURL()); servletURL.append("?_BIZVIEW=").append(bizDocToExecute); if (doom) { servletURL.append("&_DOOM=TRUE"); } if (cmt) { servletURL.append("&_CMT=TRUE"); } Map<String, Object> inputParms = getInputParams(); if (inputParms != null) { Set<Entry<String, Object>> entrySet = inputParms.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); String value = entry.getValue().toString(); servletURL.append("&").append(name).append("=").append(value); } } HttpURLConnection connection = null; try { URL url = new URL(servletURL.toString()); connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Assert.fail("Failed to connect to the test servlet: " + e); } return connection; } |
00
| Code Sample 1:
public BigInteger generateHashing(String value, int lengthBits) { try { MessageDigest algorithm = MessageDigest.getInstance(this.algorithm); algorithm.update(value.getBytes()); byte[] digest = algorithm.digest(); BigInteger hashing = new BigInteger(+1, digest); if (lengthBits != digest.length * 8) { BigInteger length = new BigInteger("2"); length = length.pow(lengthBits); hashing = hashing.mod(length); } return hashing; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Error with algorithm", e); } }
Code Sample 2:
@Override public boolean validatePublisher(Object object, String... dbSettingParams) { DBConnectionListener listener = (DBConnectionListener) object; String host = dbSettingParams[0]; String port = dbSettingParams[1]; String driver = dbSettingParams[2]; String type = dbSettingParams[3]; String dbHost = dbSettingParams[4]; String dbName = dbSettingParams[5]; String dbUser = dbSettingParams[6]; String dbPassword = dbSettingParams[7]; boolean validPublisher = false; String url = "http://" + host + ":" + port + "/reports"; try { URL _url = new URL(url); _url.openConnection().connect(); validPublisher = true; } catch (Exception e) { log.log(Level.FINE, "Failed validating url " + url, e); } if (validPublisher) { Connection conn; try { if (driver != null) { conn = DBProperties.getInstance().getConnection(driver, dbHost, dbName, type, dbUser, dbPassword); } else { conn = DBProperties.getInstance().getConnection(); } } catch (Exception e) { conn = null; listener.connectionIsOk(false, null); validPublisher = false; } if (validPublisher) { if (!allNecessaryTablesCreated(conn)) { conn = null; listener.connectionIsOk(false, null); validPublisher = false; } listener.connectionIsOk(true, conn); } } else { listener.connectionIsOk(false, null); } return validPublisher; } |
11
| Code Sample 1:
private void renameTo(File from, File to) { if (!from.exists()) return; if (to.exists()) to.delete(); boolean worked = false; try { worked = from.renameTo(to); } catch (Exception e) { database.logError(this, "" + e, null); } if (!worked) { database.logWarning(this, "Could not rename GEDCOM to " + to.getAbsolutePath(), null); try { to.delete(); final FileReader in = new FileReader(from); final FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); from.delete(); } catch (Exception e) { database.logError(this, "" + e, null); } } }
Code Sample 2:
public static void readFile(FOUserAgent ua, String uri, OutputStream output) throws IOException { InputStream in = getURLInputStream(ua, uri); try { IOUtils.copy(in, output); } finally { IOUtils.closeQuietly(in); } } |
00
| 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 Point getCoordinates(String address, String city, String state, String country) { StringBuilder queryString = new StringBuilder(); StringBuilder urlString = new StringBuilder(); StringBuilder response = new StringBuilder(); if (address != null) { queryString.append(address.trim().replaceAll(" ", "+")); queryString.append("+"); } if (city != null) { queryString.append(city.trim().replaceAll(" ", "+")); queryString.append("+"); } if (state != null) { queryString.append(state.trim().replaceAll(" ", "+")); queryString.append("+"); } if (country != null) { queryString.append(country.replaceAll(" ", "+")); } urlString.append("http://maps.google.com/maps/geo?key="); urlString.append(key); urlString.append("&sensor=false&output=json&oe=utf8&q="); urlString.append(queryString.toString()); try { URL url = new URL(urlString.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); JSONObject root = (JSONObject) JSONValue.parse(response.toString()); JSONObject placemark = (JSONObject) ((JSONArray) root.get("Placemark")).get(0); JSONArray coordinates = (JSONArray) ((JSONObject) placemark.get("Point")).get("coordinates"); Point point = new Point(); point.setLatitude((Double) coordinates.get(1)); point.setLongitude((Double) coordinates.get(0)); return point; } catch (MalformedURLException ex) { return null; } catch (NullPointerException ex) { return null; } catch (IOException ex) { return null; } } |
00
| Code Sample 1:
public static void getGPX(String gpxURL, String fName) { try { URL url = new URL(gpxURL); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); File storage = mContext.getExternalFilesDir(null); File file = new File(storage, fName); FileOutputStream os = new FileOutputStream(file); InputStream is = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = is.read(buffer)) > 0) { os.write(buffer, 0, bufferLength); } os.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public String getContent(URL url) { Logger.getLogger(this.getClass().getName()).log(Level.INFO, "getting content from " + url.toString()); String content = ""; try { URLConnection httpc; httpc = url.openConnection(); httpc.setDoInput(true); httpc.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(httpc.getInputStream())); String line = ""; while ((line = in.readLine()) != null) { content = content + line; } in.close(); } catch (IOException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Problem writing to " + url, e); } return content; } |
11
| Code Sample 1:
public static void copy(File file, File dir, boolean overwrite) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); File out = new File(dir, file.getName()); if (out.exists() && !overwrite) { throw new IOException("File: " + out + " already exists."); } FileOutputStream fos = new FileOutputStream(out, false); byte[] block = new byte[4096]; int read = bis.read(block); while (read != -1) { fos.write(block, 0, read); read = bis.read(block); } }
Code Sample 2:
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()); } } |
11
| Code Sample 1:
public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private void regattaBackup() { SwingWorker sw = new SwingWorker() { Regatta lRegatta = fRegatta; public Object construct() { String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName(); System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK })); try { FileInputStream fis = new FileInputStream(new File(fullName)); FileOutputStream fos = new FileOutputStream(new File(fullName + BAK)); int bufsize = 1024; byte[] buffer = new byte[bufsize]; int n = 0; while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n); fos.flush(); fos.close(); } catch (java.io.IOException ex) { Util.showError(ex, true); } return null; } }; sw.start(); } |
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 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:
protected void doDownload(S3Bucket bucket, S3Object s3object) throws Exception { String key = s3object.getKey(); key = trimPrefix(key); String[] path = key.split("/"); String fileName = path[path.length - 1]; String dirPath = ""; for (int i = 0; i < path.length - 1; i++) { dirPath += path[i] + "/"; } File outputDir = new File(downloadFileOutputDir + "/" + dirPath); if (outputDir.exists() == false) { outputDir.mkdirs(); } File outputFile = new File(outputDir, fileName); long size = s3object.getContentLength(); if (outputFile.exists() && outputFile.length() == size) { return; } long startTime = System.currentTimeMillis(); log.info("Download start.S3 file=" + s3object.getKey() + " local file=" + outputFile.getAbsolutePath()); FileOutputStream fout = null; S3Object dataObject = null; try { fout = new FileOutputStream(outputFile); dataObject = s3.getObject(bucket, s3object.getKey()); InputStream is = dataObject.getDataInputStream(); IOUtils.copyStream(is, fout); downloadedFileList.add(key); long downloadTime = System.currentTimeMillis() - startTime; log.info("Download complete.Estimete time=" + downloadTime + "ms " + IOUtils.toBPSText(downloadTime, size)); } catch (Exception e) { log.error("Download fail. s3 file=" + key, e); outputFile.delete(); throw e; } finally { IOUtils.closeNoException(fout); if (dataObject != null) { dataObject.closeDataInputStream(); } } } |
00
| Code Sample 1:
private static int ejecutaUpdate(String database, String SQL) throws Exception { int i = 0; DBConnectionManager dbm = null; Connection bd = null; try { dbm = DBConnectionManager.getInstance(); bd = dbm.getConnection(database); Statement st = bd.createStatement(); i = st.executeUpdate(SQL); bd.commit(); st.close(); dbm.freeConnection(database, bd); } catch (Exception e) { log.error("SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (bd == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { bd.rollback(); excep = new Exception("SQL Error: " + SQL + " error: " + e); dbm.freeConnection(database, bd); } throw excep; } return i; }
Code Sample 2:
public void readURL() throws Exception { URL url = new URL("http://www.google.com"); URLConnection c = url.openConnection(); Map<String, List<String>> headers = c.getHeaderFields(); for (String s : headers.keySet()) { System.out.println(s + ": " + headers.get(s)); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } reader.close(); } |
11
| Code Sample 1:
public void rename(String virtualWiki, String oldTopicName, String newTopicName) throws Exception { Connection conn = DatabaseConnection.getConnection(); try { boolean commit = false; conn.setAutoCommit(false); try { PreparedStatement pstm = conn.prepareStatement(STATEMENT_RENAME); try { pstm.setString(1, newTopicName); pstm.setString(2, oldTopicName); pstm.setString(3, virtualWiki); if (pstm.executeUpdate() == 0) throw new SQLException("Unable to rename topic " + oldTopicName + " on wiki " + virtualWiki); } finally { pstm.close(); } doUnlockTopic(conn, virtualWiki, oldTopicName); doRenameAllVersions(conn, virtualWiki, oldTopicName, newTopicName); commit = true; } finally { if (commit) conn.commit(); else conn.rollback(); } } finally { conn.close(); } }
Code Sample 2:
private void modifyEntry(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, Connection con) throws LDAPException { try { con.setAutoCommit(false); HashMap<String, String> ldap2db = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_LDAP2DB + this.dbInsertName); Iterator<LDAPModification> it = mods.iterator(); String sql = "UPDATE " + this.tableName + " SET "; while (it.hasNext()) { LDAPModification mod = it.next(); if (mod.getOp() != LDAPModification.REPLACE) { throw new LDAPException("Only modify replace allowed", LDAPException.OBJECT_CLASS_VIOLATION, ""); } sql += ldap2db.get(mod.getAttribute().getName()) + "=? "; } sql += " WHERE " + this.rdnField + "=?"; PreparedStatement ps = con.prepareStatement(sql); it = mods.iterator(); int i = 1; while (it.hasNext()) { LDAPModification mod = it.next(); ps.setString(i, mod.getAttribute().getStringValue()); i++; } String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); ps.setString(i, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } } |
00
| Code Sample 1:
private static String hashPassword(String password) { try { String hashword = null; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); return hashword; } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } }
Code Sample 2:
void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); } |
00
| Code Sample 1:
public static void main(String[] args) throws MalformedURLException, IOException { URL url = new URL("https://imo.im/"); URLConnection con = url.openConnection(); InputStream is = con.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while (((len = is.read(buffer)) >= 0)) { out.write(buffer, 0, len); } out.flush(); System.out.println(out.toString()); }
Code Sample 2:
int doOne(int bid, int tid, int aid, int delta) { int aBalance = 0; if (Conn == null) { incrementFailedTransactionCount(); return 0; } try { if (prepared_stmt) { pstmt1.setInt(1, delta); pstmt1.setInt(2, aid); pstmt1.executeUpdate(); pstmt1.clearWarnings(); pstmt2.setInt(1, aid); ResultSet RS = pstmt2.executeQuery(); pstmt2.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } pstmt3.setInt(1, delta); pstmt3.setInt(2, tid); pstmt3.executeUpdate(); pstmt3.clearWarnings(); pstmt4.setInt(1, delta); pstmt4.setInt(2, bid); pstmt4.executeUpdate(); pstmt4.clearWarnings(); pstmt5.setInt(1, tid); pstmt5.setInt(2, bid); pstmt5.setInt(3, aid); pstmt5.setInt(4, delta); pstmt5.executeUpdate(); pstmt5.clearWarnings(); } else { Statement Stmt = Conn.createStatement(); String Query = "UPDATE accounts "; Query += "SET Abalance = Abalance + " + delta + " "; Query += "WHERE Aid = " + aid; int res = Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "SELECT Abalance "; Query += "FROM accounts "; Query += "WHERE Aid = " + aid; ResultSet RS = Stmt.executeQuery(Query); Stmt.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } Query = "UPDATE tellers "; Query += "SET Tbalance = Tbalance + " + delta + " "; Query += "WHERE Tid = " + tid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "UPDATE branches "; Query += "SET Bbalance = Bbalance + " + delta + " "; Query += "WHERE Bid = " + bid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "INSERT INTO history(Tid, Bid, Aid, delta) "; Query += "VALUES ("; Query += tid + ","; Query += bid + ","; Query += aid + ","; Query += delta + ")"; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Stmt.close(); } if (transactions) { Conn.commit(); } return aBalance; } catch (Exception E) { if (verbose) { System.out.println("Transaction failed: " + E.getMessage()); E.printStackTrace(); } incrementFailedTransactionCount(); if (transactions) { try { Conn.rollback(); } catch (SQLException E1) { } } } return 0; } |
11
| Code Sample 1:
public static String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { logger.error("NoSuchAlgorithmException:" + e); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncodingException:" + e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } |
11
| Code Sample 1:
protected void download(URL url, File destination, long beginRange, long endRange, long totalFileSize, boolean appendToFile) throws DownloadException { System.out.println(" DOWNLOAD REQUEST RECEIVED " + url.toString() + " \n\tbeginRange : " + beginRange + " - EndRange " + endRange + " \n\t to -> " + destination.getAbsolutePath()); try { if (destination.exists() && !appendToFile) { destination.delete(); } if (!destination.exists()) destination.createNewFile(); GetMethod get = new GetMethod(url.toString()); HttpClient httpClient = new HttpClient(); Header rangeHeader = new Header(); rangeHeader.setName("Range"); rangeHeader.setValue("bytes=" + beginRange + "-" + endRange); get.setRequestHeader(rangeHeader); httpClient.executeMethod(get); int statusCode = get.getStatusCode(); if (statusCode >= 400 && statusCode < 500) throw new DownloadException("The file does not exist in this location : message from server -> " + statusCode + " " + get.getStatusText()); InputStream input = get.getResponseBodyAsStream(); OutputStream output = new FileOutputStream(destination, appendToFile); try { int length = IOUtils.copy(input, output); System.out.println(" Length : " + length); } finally { input.close(); output.flush(); output.close(); } } catch (Exception e) { e.printStackTrace(); logger.error("Unable to figure out the length of the file from the URL : " + e.getMessage()); throw new DownloadException("Unable to figure out the length of the file from the URL : " + e.getMessage()); } }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } } |
11
| Code Sample 1:
public HashCash(String cash) throws NoSuchAlgorithmException { myToken = cash; String[] parts = cash.split(":"); myVersion = Integer.parseInt(parts[0]); if (myVersion < 0 || myVersion > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if ((myVersion == 0 && parts.length != 6) || (myVersion == 1 && parts.length != 7)) throw new IllegalArgumentException("Improperly formed HashCash"); try { int index = 1; if (myVersion == 1) myValue = Integer.parseInt(parts[index++]); else myValue = 0; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); Calendar tempCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); tempCal.setTime(dateFormat.parse(parts[index++])); myResource = parts[index++]; myExtensions = deserializeExtensions(parts[index++]); MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(cash.getBytes()); byte[] tempBytes = md.digest(); int tempValue = numberOfLeadingZeros(tempBytes); if (myVersion == 0) myValue = tempValue; else if (myVersion == 1) myValue = (tempValue > myValue ? myValue : tempValue); } catch (java.text.ParseException ex) { throw new IllegalArgumentException("Improperly formed HashCash", ex); } }
Code Sample 2:
public void write(PDDocument doc) throws COSVisitorException { document = doc; SecurityHandler securityHandler = document.getSecurityHandler(); if (securityHandler != null) { try { securityHandler.prepareDocumentForEncryption(document); this.willEncrypt = true; } catch (IOException e) { throw new COSVisitorException(e); } catch (CryptographyException e) { throw new COSVisitorException(e); } } else { this.willEncrypt = false; } COSDocument cosDoc = document.getDocument(); COSDictionary trailer = cosDoc.getTrailer(); COSArray idArray = (COSArray) trailer.getDictionaryObject("ID"); if (idArray == null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(Long.toString(System.currentTimeMillis()).getBytes()); COSDictionary info = (COSDictionary) trailer.getDictionaryObject("Info"); if (info != null) { Iterator values = info.getValues().iterator(); while (values.hasNext()) { md.update(values.next().toString().getBytes()); } } idArray = new COSArray(); COSString id = new COSString(md.digest()); idArray.add(id); idArray.add(id); trailer.setItem("ID", idArray); } catch (NoSuchAlgorithmException e) { throw new COSVisitorException(e); } } cosDoc.accept(this); } |
00
| Code Sample 1:
private File Gzip(File f) throws IOException { if (f == null || !f.exists()) return null; File dest_dir = f.getParentFile(); String dest_filename = f.getName() + ".gz"; File zipfile = new File(dest_dir, dest_filename); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(zipfile)); FileInputStream in = new FileInputStream(f); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.finish(); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { f.delete(); } catch (Exception e) { } return zipfile; }
Code Sample 2:
private String calculateMD5(String value) { String finalString; try { MessageDigest md5Alg = MessageDigest.getInstance("MD5"); md5Alg.reset(); md5Alg.update(value.getBytes()); byte messageDigest[] = md5Alg.digest(); StringBuilder hexString = new StringBuilder(256); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } finalString = hexString.toString(); } catch (NoSuchAlgorithmException exc) { throw new RuntimeException("Hashing error happened:", exc); } return finalString; } |
11
| Code Sample 1:
public static final String convertPassword(final String srcPwd) { StringBuilder out; MessageDigest md; byte[] byteValues; byte singleChar = 0; try { md = MessageDigest.getInstance("MD5"); md.update(srcPwd.getBytes()); byteValues = md.digest(); if ((byteValues == null) || (byteValues.length <= 0)) { return null; } out = new StringBuilder(byteValues.length * 2); for (byte element : byteValues) { singleChar = (byte) (element & 0xF0); singleChar = (byte) (singleChar >>> 4); singleChar = (byte) (singleChar & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); singleChar = (byte) (element & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); } return out.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
Code Sample 2:
private static String getHash(char[] passwd, String algorithm) throws NoSuchAlgorithmException { MessageDigest alg = MessageDigest.getInstance(algorithm); alg.reset(); alg.update(new String(passwd).getBytes()); byte[] digest = alg.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(0xff & digest[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } |
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 String downloadFromUrl(URL url) { BufferedReader dis; String content = ""; HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setAllowUserInteraction(false); dis = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line; while ((line = dis.readLine()) != null) { content = content.concat(line); content = content.concat("\n"); } } catch (MalformedURLException ex) { System.err.println(ex + " (downloadFromUrl)"); } catch (java.io.IOException iox) { System.out.println(iox + " (downloadFromUrl)"); } catch (Exception generic) { System.out.println(generic.toString() + " (downloadFromUrl)"); } finally { } return content; } |
11
| Code Sample 1:
public static String MD5(String text) throws ProducteevSignatureException { try { MessageDigest md; md = MessageDigest.getInstance(ALGORITHM); byte[] md5hash; md.update(text.getBytes("utf-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException nsae) { throw new ProducteevSignatureException("No such algorithm : " + ALGORITHM, nsae); } catch (UnsupportedEncodingException e) { throw new ProducteevSignatureException("No such algorithm : " + ALGORITHM, e); } }
Code Sample 2:
public static boolean checkEncode(String origin, byte[] mDigest, String algorithm) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(origin.getBytes()); if (MessageDigest.isEqual(mDigest, md.digest())) { return true; } else { return false; } } |
11
| Code Sample 1:
public void create_list() { try { String data = URLEncoder.encode("PHPSESSID", "UTF-8") + "=" + URLEncoder.encode(this.get_session(), "UTF-8"); URL url = new URL(URL_LOLA + FILE_CREATE_LIST); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; line = rd.readLine(); wr.close(); rd.close(); System.out.println("Gene list saved in LOLA"); } catch (Exception e) { System.out.println("error in createList()"); e.printStackTrace(); } }
Code Sample 2:
protected InputStream callApiMethod(String apiUrl, String xmlContent, String contentType, String method, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.setRequestMethod(method); request.setDoOutput(true); if (contentType != null) { request.setRequestProperty("Content-Type", contentType); } if (xmlContent != null) { PrintStream out = new PrintStream(new BufferedOutputStream(request.getOutputStream())); out.print(xmlContent); out.flush(); out.close(); } request.connect(); if (request.getResponseCode() != expected) { throw new BingMapsException(convertStreamToString(request.getErrorStream())); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingMapsException(e); } } |
11
| Code Sample 1:
private static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); }
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); } |
00
| Code Sample 1:
private void addConfigurationResource(final String fileName, final boolean ensureLoaded) { try { final ClassLoader cl = this.getClass().getClassLoader(); final Properties p = new Properties(); final URL url = cl.getResource(fileName); if (url == null) { throw new NakedObjectRuntimeException("Failed to load configuration resource: " + fileName); } p.load(url.openStream()); configuration.add(p); } catch (Exception e) { if (ensureLoaded) { throw new NakedObjectRuntimeException(e); } LOG.debug("Resource: " + fileName + " not found, but not needed"); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
11
| Code Sample 1:
public void run() { try { File outDir = new File(outDirTextField.getText()); if (!outDir.exists()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen directory does not exist!", "Directory Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.isDirectory()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen file is not a directory!", "Not a Directory Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.canWrite()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Cannot write to the chosen directory!", "Directory Not Writeable Error", JOptionPane.ERROR_MESSAGE); } }); return; } File archiveDir = new File("foo.bar").getAbsoluteFile().getParentFile(); URL baseUrl = UnpackWizard.class.getClassLoader().getResource(UnpackWizard.class.getName().replaceAll("\\.", "/") + ".class"); if (baseUrl.getProtocol().equals("jar")) { String jarPath = baseUrl.getPath(); jarPath = jarPath.substring(0, jarPath.indexOf('!')); if (jarPath.startsWith("file:")) { try { archiveDir = new File(new URI(jarPath)).getAbsoluteFile().getParentFile(); } catch (URISyntaxException e1) { e1.printStackTrace(System.err); } } } SortedMap<Integer, String> inputFileNames = new TreeMap<Integer, String>(); for (Entry<Object, Object> anEntry : indexProperties.entrySet()) { String key = anEntry.getKey().toString(); if (key.startsWith("archive file ")) { inputFileNames.put(Integer.parseInt(key.substring("archive file ".length())), anEntry.getValue().toString()); } } byte[] buff = new byte[64 * 1024]; try { long bytesToWrite = 0; long bytesReported = 0; long bytesWritten = 0; for (String aFileName : inputFileNames.values()) { File aFile = new File(archiveDir, aFileName); if (aFile.exists()) { if (aFile.isFile()) { bytesToWrite += aFile.length(); } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" is not a standard file!", "Non Standard File Error", JOptionPane.ERROR_MESSAGE); } }); return; } } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" does not exist!", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } } MultiFileInputStream mfis = new MultiFileInputStream(archiveDir, inputFileNames.values().toArray(new String[inputFileNames.size()])); TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(mfis)); TarArchiveEntry tarEntry = tis.getNextTarEntry(); while (tarEntry != null) { File outFile = new File(outDir.getAbsolutePath() + "/" + tarEntry.getName()); if (outFile.exists()) { final File wrongFile = outFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Was about to write out file \"" + wrongFile.getAbsolutePath() + "\" but it already " + "exists.\nPlease [re]move existing files out of the way " + "and try again.", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (tarEntry.isDirectory()) { outFile.getAbsoluteFile().mkdirs(); } else { outFile.getAbsoluteFile().getParentFile().mkdirs(); OutputStream os = new BufferedOutputStream(new FileOutputStream(outFile)); int len = tis.read(buff, 0, buff.length); while (len != -1) { os.write(buff, 0, len); bytesWritten += len; if (bytesWritten - bytesReported > (10 * 1024 * 1024)) { bytesReported = bytesWritten; final int progress = (int) (bytesReported * 100 / bytesToWrite); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(progress); } }); } len = tis.read(buff, 0, buff.length); } os.close(); } tarEntry = tis.getNextTarEntry(); } long expectedCrc = 0; try { expectedCrc = Long.parseLong(indexProperties.getProperty("CRC32", "0")); } catch (NumberFormatException e) { System.err.println("Error while obtaining the expected CRC"); e.printStackTrace(System.err); } if (mfis.getCRC() == expectedCrc) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Extraction completed successfully!", "Done!", JOptionPane.INFORMATION_MESSAGE); } }); return; } else { System.err.println("CRC Error: was expecting " + expectedCrc + " but got " + mfis.getCRC()); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "CRC Error: the data extracted does not have the expected CRC!\n" + "You should probably delete the extracted files, as they are " + "likely to be invalid.", "CRC Error", JOptionPane.ERROR_MESSAGE); } }); return; } } catch (final IOException e) { e.printStackTrace(System.err); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Input/Output Error: " + e.getLocalizedMessage(), "Input/Output Error", JOptionPane.ERROR_MESSAGE); } }); return; } } finally { SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); setEnabled(true); } }); } }
Code Sample 2:
@Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException { try { if (vtf == null) { LOG.debug("Serializing from database"); existDocument.stream(out); } else { LOG.debug("Serializing from buffer"); InputStream is = vtf.getByteStream(); IOUtils.copy(is, out); out.flush(); IOUtils.closeQuietly(is); vtf.delete(); vtf = null; } } catch (PermissionDeniedException e) { LOG.debug(e.getMessage()); throw new NotAuthorizedException(this); } finally { IOUtils.closeQuietly(out); } } |
00
| Code Sample 1:
public HttpURLConnection connect() throws IOException { if (url == null) { return null; } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (previousETag != null) { connection.addRequestProperty("If-None-Match", previousETag); } if (previousLastModified != null) { connection.addRequestProperty("If-Modified-Since", previousLastModified); } return connection; }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/zip"); response.setHeader("Content-Disposition", "inline; filename=c:/server1.zip"); try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("server.zip"); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; java.util.Properties props = new java.util.Properties(); props.load(new java.io.FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + "/SystemFiles/ENV_VAR.txt")); String jbossHomePath = props.getProperty("JBOSS_HOME"); jbossHomePath = jbossHomePath.replaceAll("deploy", "log"); FileInputStream fis = new FileInputStream(new File(jbossHomePath + "/server.log")); origin = new BufferedInputStream(fis, BUFFER); ZipEntry entry = new ZipEntry(jbossHomePath + "/server.log"); zipOut.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } origin.close(); zipOut.closeEntry(); java.io.FileInputStream fis1 = new java.io.FileInputStream(new java.io.File("server.zip")); java.nio.channels.FileChannel fc1 = fis1.getChannel(); int length1 = (int) fc1.size(); byte buffer[] = new byte[length1]; System.out.println("size of zip file = " + length1); fis1.read(buffer); OutputStream out1 = response.getOutputStream(); out1.write(buffer); fis1.close(); out1.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
11
| Code Sample 1:
public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } |
00
| Code Sample 1:
static byte[] getPassword(final String name, final String password) { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(name.getBytes()); messageDigest.update(password.getBytes()); return messageDigest.digest(); } catch (final NoSuchAlgorithmException e) { throw new JobException(e); } }
Code Sample 2:
public LineIterator iterator() { LineIterator ret; final String charsetname; final Charset charset; final CharsetDecoder charsetDecoder; synchronized (this) { charsetname = this.charsetname; charset = this.charset; charsetDecoder = this.charsetDecoder; } try { if (charsetDecoder != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charsetDecoder); else if (charset != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charset); else if (charsetname != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, Charset.forName(charsetname)); else ret = new LineIterator(this, url.openStream(), returnNullUponEof, (Charset) null); synchronized (openedIterators) { openedIterators.add(ret); } return ret; } catch (IOException e) { throw new IllegalStateException(e); } } |
11
| Code Sample 1:
public void copyFile2(String src, String dest) throws IOException { String newLine = System.getProperty("line.separator"); FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(src); fw = new FileWriter(dest); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(src); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { throw new FileCopyException(src + " " + QZ.PHRASES.getPhrase("35")); } catch (IOException ioe) { throw new FileCopyException(QZ.PHRASES.getPhrase("36")); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } }
Code Sample 2:
Library(MainFrame mf, boolean newLibrary, String templateName, String newFileName) throws Exception { mainFrame = mf; trackMap = new HashMap<String, LibraryTrack>(); trackVec = new Vector<LibraryTrack>(); String propFileName = null; File propFile = null; String notExist = ""; String[] options = templateDesc; boolean isCurrent = mainFrame.library != null; int ix; if (!newLibrary) { propFileName = mainFrame.name + ".jampal"; propFile = new File(propFileName); } if (isCurrent) { options = new String[templateDesc.length + 1]; options[0] = "Copy of Current Library"; for (ix = 0; ix < templateDesc.length; ix++) { options[ix + 1] = templateDesc[ix]; } } boolean copyLibrary = false; if (newLibrary) { if (templateName == null) { Object resp = JOptionPane.showInputDialog(mainFrame.frame, "Please select a template.", "Select Type of Library", JOptionPane.WARNING_MESSAGE, null, options, null); if (resp == null) return; templateName = (String) resp; } for (ix = 0; ix < options.length && !options[ix].equals(templateName); ix++) ; if (isCurrent) ix--; boolean creatingPlaylist = false; BufferedReader in; if (ix == -1) { in = new BufferedReader(new FileReader(mainFrame.name + ".jampal")); copyLibrary = true; creatingPlaylist = (mainFrame.library.attributes.libraryType == 'P'); } else { in = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("pgbennett/jampal/" + templateNames[ix]))); creatingPlaylist = ("playlist.jampal".equals(templateNames[ix])); } if (newFileName == null) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Create New Library File"); String currentDirectory = null; if (mainFrame.name != null) { File nameFile = new File(mainFrame.name); currentDirectory = nameFile.getParent(); if (currentDirectory == null) currentDirectory = "."; } if (currentDirectory == null) currentDirectory = Jampal.jampalDirectory; if (currentDirectory != null) fileChooser.setCurrentDirectory(new File(currentDirectory)); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(false); Mp3FileFilter filter = new Mp3FileFilter(); filter.setExtension("jampal", "Jampal library files"); fileChooser.addChoosableFileFilter(filter); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(filter); fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); int returnVal = fileChooser.showSaveDialog(mainFrame.frame); if (returnVal == fileChooser.APPROVE_OPTION) { propFile = fileChooser.getSelectedFile(); propFileName = propFile.getPath(); if (!propFileName.toLowerCase().endsWith(".jampal")) { propFileName = propFileName + ".jampal"; propFile = new File(propFileName); } } else return; } else { propFileName = newFileName; propFile = new File(propFileName); } if (propFile.exists()) { if (JOptionPane.showConfirmDialog(mainFrame.frame, "File " + propFileName + " already exists. Do you want to overwrite it ?", "Warning", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return; } PrintWriter out = new PrintWriter(new FileOutputStream(propFile)); String libName = propFile.getName(); libName = libName.substring(0, libName.length() - 7); for (; ; ) { String line = in.readLine(); if (line == null) break; if (creatingPlaylist && line.startsWith("playlist=")) { line = "playlist=" + libName; } if (line.startsWith("libraryname=")) { line = "libraryname=" + libName + ".jmp"; } out.println(line); } in.close(); out.close(); if (!creatingPlaylist && !copyLibrary) { String playlistName = propFile.getParent() + File.separator + "playlist.jampal"; File playlistFile = new File(playlistName); if (!playlistFile.exists()) { in = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("pgbennett/jampal/playlist.jampal"))); out = new PrintWriter(new FileOutputStream(playlistFile)); for (; ; ) { String line = in.readLine(); if (line == null) break; out.println(line); } in.close(); out.close(); } } } if (propFileName != null) attributes = new LibraryAttributes(propFileName); insertBefore = -1; } |
00
| Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
private static void zip(ZipOutputStream aOutputStream, final File[] aFiles, final String sArchive, final URI aRootURI, final String sFilter) throws FileError { boolean closeStream = false; if (aOutputStream == null) try { aOutputStream = new ZipOutputStream(new FileOutputStream(sArchive)); closeStream = true; } catch (final FileNotFoundException e) { throw new FileError("Can't create ODF file!", e); } try { try { for (final File curFile : aFiles) { aOutputStream.putNextEntry(new ZipEntry(URLDecoder.decode(aRootURI.relativize(curFile.toURI()).toASCIIString(), "UTF-8"))); if (curFile.isDirectory()) { aOutputStream.closeEntry(); FileUtils.zip(aOutputStream, FileUtils.getFiles(curFile, sFilter), sArchive, aRootURI, sFilter); continue; } final FileInputStream inputStream = new FileInputStream(curFile); for (int i; (i = inputStream.read(FileUtils.BUFFER)) != -1; ) aOutputStream.write(FileUtils.BUFFER, 0, i); inputStream.close(); aOutputStream.closeEntry(); } } finally { if (closeStream && aOutputStream != null) aOutputStream.close(); } } catch (final IOException e) { throw new FileError("Can't zip file to archive!", e); } if (closeStream) DocumentController.getStaticLogger().fine(aFiles.length + " files and folders zipped as " + sArchive); } |
11
| Code Sample 1:
private String readData(URL url) { try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = in.readLine()) != null) { responseBuffer.append(line); } in.close(); return new String(responseBuffer); } catch (Exception e) { System.out.println(e); } return null; }
Code Sample 2:
protected void setOuterIP() { try { URL url = new URL("http://elm-ve.sf.net/ipCheck/ipCheck.cgi"); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ip = br.readLine(); ip = ip.trim(); bridgeOutIPTF.setText(ip); } catch (Exception e) { e.printStackTrace(); } } |
11
| Code Sample 1:
public static void main(String[] args) throws Exception { PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n"); ConsoleAppender ca = new ConsoleAppender(pl); Logger.getRoot().addAppender(ca); Logger.getRoot().setLevel(Level.INFO); Options options = new Options(); options.addOption("p", "put", false, "put a file in the DHT overlay"); options.addOption("g", "get", false, "get a file from the DHT"); options.addOption("r", "remove", false, "remove a file from the DHT"); options.addOption("u", "update", false, "updates the lease"); options.addOption("j", "join", false, "join the DHT overlay"); options.addOption("c", "config", true, "the configuration file"); options.addOption("k", "key", true, "the key to read a file from"); options.addOption("f", "file", true, "the file to read or write"); options.addOption("a", "app", true, "the application ID"); options.addOption("s", "secret", true, "the secret used to hide data"); options.addOption("t", "ttl", true, "how long in seconds data should persist"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String configFile = null; String mode = null; String secretStr = null; int ttl = 9999; String keyStr = null; String file = null; int appId = 0; if (cmd.hasOption("j")) { mode = "join"; } if (cmd.hasOption("p")) { mode = "put"; } if (cmd.hasOption("g")) { mode = "get"; } if (cmd.hasOption("r")) { mode = "remove"; } if (cmd.hasOption("u")) { mode = "update"; } if (cmd.hasOption("c")) { configFile = cmd.getOptionValue("c"); } if (cmd.hasOption("k")) { keyStr = cmd.getOptionValue("k"); } if (cmd.hasOption("f")) { file = cmd.getOptionValue("f"); } if (cmd.hasOption("s")) { secretStr = cmd.getOptionValue("s"); } if (cmd.hasOption("t")) { ttl = Integer.parseInt(cmd.getOptionValue("t")); } if (cmd.hasOption("a")) { appId = Integer.parseInt(cmd.getOptionValue("a")); } if (mode == null) { System.err.println("ERROR: --put or --get or --remove or --join or --update is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (configFile == null) { System.err.println("ERROR: --config is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } Properties conf = new Properties(); conf.load(new FileInputStream(configFile)); DHT dht = new DHT(conf); if (mode.equals("join")) { dht.join(); } else if (mode.equals("put")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("putting file " + file); FileInputStream in = new FileInputStream(file); byte[] tmp = new byte[1000000]; int num = in.read(tmp); byte[] value = new byte[num]; System.arraycopy(tmp, 0, value, 0, num); in.close(); if (dht.put((short) appId, keyStr.getBytes(), value, ttl, secretStr.getBytes()) < 0) { logger.info("There was an error while putting a key-value."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("get")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("getting file " + file); ArrayList<byte[]> values = new ArrayList<byte[]>(); if (dht.get((short) appId, keyStr.getBytes(), Integer.MAX_VALUE, values) < 0) { logger.info("There was an error while getting a value."); System.exit(0); } if (values.size() == 0 || values == null) { System.out.println("No values returned."); System.exit(0); } FileOutputStream out = new FileOutputStream(file); System.out.println("Found " + values.size() + " values -- saving the first one only."); out.write(values.get(0)); out.close(); System.out.println("Ok!"); } else if (mode.equals("remove")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("removing <key,value> for key=" + keyStr); if (dht.remove((short) appId, keyStr.getBytes(), secretStr.getBytes()) < 0) { logger.info("There was an error while removing a key."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("update")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("updating <key,value> for key=" + keyStr); if (dht.updateLease((short) appId, keyStr.getBytes(), ttl) < 0) { logger.info("There was an error while updating data lease."); System.exit(0); } System.out.println("Ok!"); } DHT.getInstance().stop(); }
Code Sample 2:
private static void copyFile(File sourceFile, File destFile) { try { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } catch (Exception e) { throw new RuntimeException(e); } } |
11
| Code Sample 1:
public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public static String hashURL(String url) { if (url == null) { throw new IllegalArgumentException("URL may not be null. "); } String result = null; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); if (md != null) { md.reset(); md.update(url.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); result = hash.toString(16); } md = null; } catch (NoSuchAlgorithmException ex) { result = null; } return result; } |
11
| Code Sample 1:
@Test public void testLargePut() throws Throwable { int size = CommonParameters.BLOCK_SIZE; InputStream is = new FileInputStream(_fileName); RepositoryFileOutputStream ostream = new RepositoryFileOutputStream(_nodeName, _putHandle, CommonParameters.local); int readLen = 0; int writeLen = 0; byte[] buffer = new byte[CommonParameters.BLOCK_SIZE]; while ((readLen = is.read(buffer, 0, size)) != -1) { ostream.write(buffer, 0, readLen); writeLen += readLen; } ostream.close(); CCNStats stats = _putHandle.getNetworkManager().getStats(); Assert.assertEquals(0, stats.getCounter("DeliverInterestFailed")); }
Code Sample 2:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } |
00
| Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.debug("Random GUID error: " + e.getMessage()); } 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 createTableIfNotExisting(Connection conn) throws SQLException { String sql = "select * from " + tableName; PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.executeQuery(); } catch (SQLException sqle) { ps.close(); sql = "create table " + tableName + " ( tableName varchar(255) not null primary key, " + " lastId numeric(18) not null)"; ps = conn.prepareStatement(sql); ps.executeUpdate(); } finally { ps.close(); try { if (!conn.getAutoCommit()) conn.commit(); } catch (Exception e) { conn.rollback(); } } } |
00
| Code Sample 1:
public void copyDependancyFiles() { for (String[] depStrings : getDependancyFiles()) { String source = depStrings[0]; String target = depStrings[1]; try { File sourceFile = PluginManager.getFile(source); IOUtils.copyEverything(sourceFile, new File(WEB_ROOT + target)); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } |
11
| Code Sample 1:
protected void saveSelectedFiles() { if (dataList.getSelectedRowCount() == 0) { return; } if (dataList.getSelectedRowCount() == 1) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(dataList.getSelectedRow())); AttachFile entry = (AttachFile) obj; JFileChooser fc = new JFileChooser(); fc.setSelectedFile(new File(fc.getCurrentDirectory(), entry.getCurrentPath().getName())); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File current = entry.getCurrentPath(); File dest = fc.getSelectedFile(); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return; } else { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { for (Integer idx : dataList.getSelectedRows()) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(idx)); AttachFile entry = (AttachFile) obj; File current = entry.getCurrentPath(); File dest = new File(fc.getSelectedFile(), entry.getName()); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } return; } }
Code Sample 2:
private static byte[] tryLoadFile(String path) throws IOException { InputStream in = new FileInputStream(path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); return out.toByteArray(); } |
00
| Code Sample 1:
public static void main(String[] args) { try { URL url = new URL("http://localhost:6557"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); int responseCode = conn.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String decodedString; while ((decodedString = in.readLine()) != null) { System.out.println(decodedString); } in.close(); conn.disconnect(); } catch (Exception ex) { Logger.getLogger(TestSSLConnection.class.getName()).log(Level.SEVERE, null, ex); } }
Code Sample 2:
private static void _checkConfigFile() throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; boolean copy = false; File from = new java.io.File(filePath); if (!from.exists()) { Properties properties = new Properties(); properties.put(Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CELL_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CELL_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_VISIBILITY")); Company comp = PublicCompanyFactory.getDefaultCompany(); int numberGenericVariables = Config.getIntProperty("MAX_NUMBER_VARIABLES_TO_SHOW"); for (int i = 1; i <= numberGenericVariables; i++) { properties.put(LanguageUtil.get(comp.getCompanyId(), comp.getLocale(), "user.profile.var" + i).replace(" ", "_"), Config.getStringProperty("ADDITIONAL_INFO_DEFAULT_VISIBILITY")); } try { properties.store(new java.io.FileOutputStream(filePath), null); } catch (Exception e) { Logger.error(UserManagerPropertiesFactory.class, e.getMessage(), e); } from = new java.io.File(filePath); copy = true; } String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File to = new java.io.File(tmpFilePath); if (!to.exists()) { to.createNewFile(); copy = true; } if (copy) { FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } catch (IOException e) { Logger.error(UserManagerPropertiesFactory.class, "_checkLanguagesFiles:Property File Copy Failed " + e, e); } } |
00
| Code Sample 1:
private void announce(String trackerURL, byte[] hash, byte[] peerId, int port) { try { String strUrl = trackerURL + "?info_hash=" + URLEncoder.encode(new String(hash, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&peer_id=" + URLEncoder.encode(new String(peerId, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&port=" + port + "&uploaded=0&downloaded=0&left=0&numwant=50&no_peer_id=1&compact=1"; URL url = new URL(strUrl); URLConnection con = url.openConnection(); con.connect(); con.getContent(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } } |
11
| Code Sample 1:
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); } }
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; } |
00
| Code Sample 1:
protected static void copyDeleting(File source, File dest) throws ErrorCodeException { byte[] buf = new byte[8 * 1024]; FileInputStream in = null; try { in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { int count; while ((count = in.read(buf)) >= 0) out.write(buf, 0, count); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new ErrorCodeException(e); } }
Code Sample 2:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); 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); } } |
11
| Code Sample 1:
public static void main(String[] args) throws IOException { String zipPath = "C:\\test.zip"; CZipInputStream zip_in = null; try { byte[] c = new byte[1024]; int slen; zip_in = new CZipInputStream(new FileInputStream(zipPath), "utf-8"); do { ZipEntry file = zip_in.getNextEntry(); if (file == null) break; String fileName = file.getName(); System.out.println(fileName); String ext = fileName.substring(fileName.lastIndexOf(".")); long seed = new Date(System.currentTimeMillis()).getTime(); String newFileName = Long.toString(seed) + ext; FileOutputStream out = new FileOutputStream(newFileName); while ((slen = zip_in.read(c, 0, c.length)) != -1) out.write(c, 0, slen); out.close(); } while (true); } catch (ZipException zipe) { zipe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { zip_in.close(); } }
Code Sample 2:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } |
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 static Image load(final InputStream input, String format, Point dimension) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = null; ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); dotOutput = File.createTempFile(TMP_FILE_PREFIX, "." + format); dotOutput.delete(); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); status.add(result); status.add(logInput(dotContents)); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); ImageLoader loader = new ImageLoader(); ImageData[] imageData = loader.load(dotOutput.getAbsolutePath()); return new Image(Display.getDefault(), imageData[0]); } } catch (SWTException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); dotOutput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); } |
11
| Code Sample 1:
private ArrayList<String> getFiles(String date) { ArrayList<String> files = new ArrayList<String>(); String info = ""; try { obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data")); URL url = new URL(URL_ROUTE_VIEWS + date + "/"); URLConnection conn = url.openConnection(); conn.setDoOutput(false); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (!line.equals("")) info += line + "%"; } obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data")); info = Patterns.removeTags(info); StringTokenizer st = new StringTokenizer(info, "%"); info = ""; boolean alternador = false; int index = 1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!token.trim().equals("")) { int pos = token.indexOf(".bz2"); if (pos != -1) { token = token.substring(1, pos + 4); files.add(token); } } } rd.close(); } catch (Exception e) { e.printStackTrace(); } return files; }
Code Sample 2:
private Image retrievePdsImage(double lat, double lon) { imageDone = false; try { StringBuffer urlBuff = new StringBuffer(psdUrl + psdCgi + "?"); urlBuff.append("DATA_SET_NAME=" + dataSet); urlBuff.append("&VERSION=" + version); urlBuff.append("&PIXEL_TYPE=" + pixelType); urlBuff.append("&PROJECTION=" + projection); urlBuff.append("&STRETCH=" + stretch); urlBuff.append("&GRIDLINE_FREQUENCY=" + gridlineFrequency); urlBuff.append("&SCALE=" + URLEncoder.encode(scale)); urlBuff.append("&RESOLUTION=" + resolution); urlBuff.append("&LATBOX=" + latbox); urlBuff.append("&LONBOX=" + lonbox); urlBuff.append("&BANDS_SELECTED=" + bandsSelected); urlBuff.append("&LAT=" + lat); urlBuff.append("&LON=" + lon); URL url = new URL(urlBuff.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String result = null; String line; String imageSrc; int count = 0; while ((line = in.readLine()) != null) { if (count == 6) result = line; count++; } int startIndex = result.indexOf("<TH COLSPAN=2 ROWSPAN=2><IMG SRC = \"") + 36; int endIndex = result.indexOf("\"", startIndex); imageSrc = result.substring(startIndex, endIndex); URL imageUrl = new URL(imageSrc); return (Toolkit.getDefaultToolkit().getImage(imageUrl)); } catch (MalformedURLException e) { } catch (IOException e) { } return null; } |
00
| Code Sample 1:
public static String readFromURL(String urlStr) throws IOException { URL url = new URL(urlStr); StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); return sb.toString(); }
Code Sample 2:
public static InputStream getInputStream(String fileName) throws IOException { InputStream input; if (fileName.startsWith("http:")) { URL url = new URL(fileName); URLConnection connection = url.openConnection(); input = connection.getInputStream(); } else { input = new FileInputStream(fileName); } return input; } |
00
| Code Sample 1:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
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) { } } } } |
11
| Code Sample 1:
public static String downloadWebpage2(String address) throws MalformedURLException, IOException { URL url = new URL(address); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); String encoding = conn.getContentEncoding(); InputStream is = null; if(encoding != null && encoding.equalsIgnoreCase("gzip")) { is = new GZIPInputStream(conn.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { is = new InflaterInputStream(conn.getInputStream()); } else { is = conn.getInputStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; String page = ""; while((line = br.readLine()) != null) { page += line + "\n"; } br.close(); return page; }
Code Sample 2:
@Override public String getFeedFeed(String sUrl) { try { URL url = new URL(sUrl); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String result = ""; String line; for (; (line = reader.readLine()) != null; result += line) { } reader.close(); return result; } catch (MalformedURLException e) { } catch (IOException e) { } return null; } |
11
| Code Sample 1:
public static String CreateHash(String s) { String str = s.toString(); if (str == null || str.length() == 0) { throw new IllegalArgumentException("String cannot be null or empty"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return (hexString.toString()); }
Code Sample 2:
public static String encrypt(String plaintext) throws EncryptionException { if (plaintext == null) { throw new EncryptionException(); } try { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); return Base64.encodeBytes(md.digest()); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e); } catch (UnsupportedEncodingException e) { throw new EncryptionException(e); } } |
00
| Code Sample 1:
public void extractImage(String input, OutputStream os, DjatokaDecodeParam params, IWriter w) throws DjatokaException { File in = null; if (input.equals(STDIN)) { try { in = File.createTempFile("tmp", ".jp2"); input = in.getAbsolutePath(); in.deleteOnExit(); IOUtils.copyFile(new File(STDIN), in); } catch (IOException e) { logger.error("Unable to process image from " + STDIN + ": " + e.getMessage()); throw new DjatokaException(e); } } BufferedImage bi = extractImpl.process(input, params); if (bi != null) { if (params.getScalingFactor() != 1.0 || params.getScalingDimensions() != null) bi = applyScaling(bi, params); if (params.getTransform() != null) bi = params.getTransform().run(bi); w.write(bi, os); } if (in != null) in.delete(); }
Code Sample 2:
public boolean searchEntity(String login, String password, String searcheId, OutputStream os) throws SynchronizationException { HttpClient client = new SSLHttpClient(); try { StringBuilder builder = new StringBuilder(url).append("?" + CMD_PARAM + "=" + CMD_SEARCH).append("&" + LOGIN_PARAM + "=" + URLEncoder.encode(login, "UTF-8")).append("&" + PASSWD_PARAM + "=" + URLEncoder.encode(password, "UTF-8")).append("&" + SEARCH_PARAM + "=" + searcheId); HttpGet method = httpGetMethod(builder.toString()); HttpResponse response = client.execute(method); Header header = response.getFirstHeader(HEADER_NAME); if (header != null && HEADER_VALUE.equals(HEADER_VALUE)) { int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { long expectedLength = response.getEntity().getContentLength(); InputStream is = response.getEntity().getContent(); FileUtils.writeInFile(is, os, expectedLength); return true; } else { throw new SynchronizationException("Command 'search' : HTTP error code returned." + code, SynchronizationException.ERROR_SEARCH); } } else { throw new SynchronizationException("HTTP header is invalid", SynchronizationException.ERROR_SEARCH); } } catch (Exception e) { throw new SynchronizationException("Command 'search' -> ", e, SynchronizationException.ERROR_SEARCH); } } |
11
| Code Sample 1:
public static void DecodeMapFile(String mapFile, String outputFile) throws Exception { byte magicKey = 0; byte[] buffer = new byte[2048]; int nread; InputStream map; OutputStream output; try { map = new FileInputStream(mapFile); } catch (Exception e) { throw new Exception("Map file error", e); } try { output = new FileOutputStream(outputFile); } catch (Exception e) { throw new Exception("Map file error", e); } while ((nread = map.read(buffer, 0, 2048)) != 0) { for (int i = 0; i < nread; ++i) { buffer[i] ^= magicKey; magicKey += 43; } output.write(buffer, 0, nread); } map.close(); output.close(); }
Code Sample 2:
public static void copyFile(File from, File to) { try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024 * 16]; int read = 0; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } in.close(); } catch (IOException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
private void executeRequest(OperationContext context) throws java.lang.Throwable { long t1 = System.currentTimeMillis(); DirectoryParams params = context.getRequestOptions().getDirectoryOptions(); try { String srvCfg = context.getRequestContext().getApplicationConfiguration().getCatalogConfiguration().getParameters().getValue("openls.directory"); HashMap<String, String> poiProperties = params.getPoiProperties(); Set<String> keys = poiProperties.keySet(); Iterator<String> iter = keys.iterator(); StringBuffer filter = new StringBuffer(); while (iter.hasNext()) { String key = iter.next(); QueryFilter queryFilter = new QueryFilter(key, poiProperties.get(key)); filter.append(makePOIRequest(queryFilter)); } String sUrl = srvCfg + "/query?" + filter.toString(); LOGGER.info("REQUEST=\n" + sUrl); URL url = new URL(sUrl); URLConnection conn = url.openConnection(); String line = ""; String sResponse = ""; InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader rd = new BufferedReader(isr); while ((line = rd.readLine()) != null) { sResponse += line; } rd.close(); url = null; parsePOIResponse(sResponse, params); } catch (Exception p_e) { LOGGER.severe("Throwing exception" + p_e.getMessage()); throw p_e; } finally { long t2 = System.currentTimeMillis(); LOGGER.info("PERFORMANCE: " + (t2 - t1) + " ms spent performing service"); } }
Code Sample 2:
private MimeTypesProvider() { File mimeTypesFile = new File(XPontusConstantsIF.XPONTUS_HOME_DIR, "mimes.properties"); try { if (!mimeTypesFile.exists()) { OutputStream os = null; InputStream is = getClass().getResourceAsStream("/net/sf/xpontus/configuration/mimetypes.properties"); os = FileUtils.openOutputStream(mimeTypesFile); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } provider = new XPontusMimetypesFileTypeMap(mimeTypesFile.getAbsolutePath()); MimetypesFileTypeMap.setDefaultFileTypeMap(provider); } catch (Exception err) { err.printStackTrace(); } } |
00
| Code Sample 1:
@Test public void test_blueprintTypeByTypeID_StringInsteadOfID() throws Exception { URL url = new URL(baseUrl + "/blueprintTypeByTypeID/blah-blah"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); }
Code Sample 2:
public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { if (globali.jcVariabili.DEBUG) globali.jcFunzioni.erroreSQL(ex.toString()); } return res; } |
00
| Code Sample 1:
public synchronized void readModels(Project p, URL url) throws IOException { _proj = p; Argo.log.info("======================================="); Argo.log.info("== READING MODEL " + url); try { XMIReader reader = new XMIReader(); InputSource source = new InputSource(url.openStream()); source.setSystemId(url.toString()); _curModel = reader.parse(source); if (reader.getErrors()) { throw new IOException("XMI file " + url.toString() + " could not be parsed."); } _UUIDRefs = new HashMap(reader.getXMIUUIDToObjectMap()); } catch (SAXException saxEx) { Exception ex = saxEx.getException(); if (ex == null) { saxEx.printStackTrace(); } else { ex.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } Argo.log.info("======================================="); try { _proj.addModel((ru.novosoft.uml.foundation.core.MNamespace) _curModel); } catch (PropertyVetoException ex) { System.err.println("An error occurred adding the model to the project!"); ex.printStackTrace(); } Collection ownedElements = _curModel.getOwnedElements(); Iterator oeIterator = ownedElements.iterator(); while (oeIterator.hasNext()) { MModelElement me = (MModelElement) oeIterator.next(); if (me instanceof MClass) { _proj.defineType((MClass) me); } else if (me instanceof MDataType) { _proj.defineType((MDataType) me); } } }
Code Sample 2:
void setURLString(String path, boolean forceLoad) { if (path != null) { if (this.url != null || inputStream != null) throw new IllegalArgumentException(Ding3dI18N.getString("MediaContainer5")); try { URL url = new URL(path); InputStream stream; stream = url.openStream(); stream.close(); } catch (Exception e) { throw new SoundException(javax.media.ding3d.Ding3dI18N.getString("MediaContainer0")); } } this.urlString = path; if (forceLoad) dispatchMessage(); } |
11
| Code Sample 1:
public boolean authenticate() { if (empresaFeta == null) empresaFeta = new AltaEmpresaBean(); log.info("authenticating {0}", credentials.getUsername()); boolean bo; try { String passwordEncriptat = credentials.getPassword(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(passwordEncriptat.getBytes(), 0, passwordEncriptat.length()); passwordEncriptat = new BigInteger(1, m.digest()).toString(16); Query q = entityManager.createQuery("select usuari from Usuaris usuari where usuari.login=? and usuari.password=?"); q.setParameter(1, credentials.getUsername()); q.setParameter(2, passwordEncriptat); Usuaris usuari = (Usuaris) q.getSingleResult(); bo = (usuari != null); if (bo) { if (usuari.isEsAdministrador()) { identity.addRole("admin"); } else { carregaDadesEmpresa(); log.info("nom de l'empresa: " + empresaFeta.getInstance().getNom()); } } } catch (Throwable t) { log.error(t); bo = false; } log.info("L'usuari {0} s'ha identificat bé? : {1} ", credentials.getUsername(), bo ? "si" : "no"); return bo; }
Code Sample 2:
public static boolean checkEncryptedPassword(String md5key, String passwordAccount, String encryptedPassword, int passwdenc) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance(Constants.ALGORITHM); switch(passwdenc) { case 1: md.update((md5key + encryptedPassword).getBytes("8859_1")); return md.digest().equals(passwordAccount.getBytes("8859_1")); case 2: md.update((encryptedPassword + md5key).getBytes("8859_1")); return md.digest().equals(passwordAccount.getBytes("8859_1")); default: return false; } } |
11
| Code Sample 1:
public static String encriptar(String string) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new Exception("Algoritmo de Criptografia não encontrado."); } md.update(string.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String retorno = hash.toString(16); return retorno; }
Code Sample 2:
public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = 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 = 0L; 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 < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); } |
00
| Code Sample 1:
public static String getURL(String urlString, String getData, String postData) { try { if (getData != null) if (!getData.equals("")) urlString += "?" + getData; URL url = new URL(urlString); URLConnection connection = url.openConnection(); if (!postData.equals("")) { connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print(postData); out.close(); } BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); int inputLine; String output = ""; while ((inputLine = in.read()) != -1) output += (char) inputLine; in.close(); return output; } catch (Exception e) { return null; } }
Code Sample 2:
public void removeJarFiles() throws IOException { HashSet<GridNode> nodes = (HashSet) batchTask.returnNodeCollection(); Iterator<GridNode> ic = nodes.iterator(); InetAddress addLocal = InetAddress.getLocalHost(); String hostnameLocal = addLocal.getHostName(); while (ic.hasNext()) { GridNode node = ic.next(); String address = node.getPhysicalAddress(); InetAddress addr = InetAddress.getByName(address); byte[] rawAddr = addr.getAddress(); Map<String, String> attributes = node.getAttributes(); InetAddress hostname = InetAddress.getByAddress(rawAddr); if (hostname.getHostName().equals(hostnameLocal)) continue; String gridPath = attributes.get("GRIDGAIN_HOME"); FTPClient ftp = new FTPClient(); try { String[] usernamePass = inputNodes.get(hostname.getHostName()); ftp.connect(hostname); ftp.login(usernamePass[0], usernamePass[1]); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); continue; } ftp.login(usernamePass[0], usernamePass[1]); String directory = gridPath + "/libs/ext/"; ftp.changeWorkingDirectory(directory); FTPFile[] fs = ftp.listFiles(); for (FTPFile f : fs) { if (f.isDirectory()) continue; System.out.println(f.getName()); ftp.deleteFile(f.getName()); } ftp.sendCommand("rm *"); ftp.logout(); ftp.disconnect(); } catch (Exception e) { MessageCenter.getMessageCenter(BatchMainSetup.class).error("Problems with the FTP connection." + "A file has not been succesfully transfered", e); e.printStackTrace(); } } } |
00
| Code Sample 1:
private String writeInputStreamToString(InputStream stream) { StringWriter stringWriter = new StringWriter(); try { IOUtils.copy(stream, stringWriter); } catch (IOException e) { e.printStackTrace(); } String namespaces = stringWriter.toString().trim(); return namespaces; }
Code Sample 2:
public static String md5EncodeString(String s) throws UnsupportedEncodingException, NoSuchAlgorithmException { if (s == null) return null; if (StringUtils.isBlank(s)) return ""; MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(s.getBytes("UTF-8")); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } |
00
| Code Sample 1:
public void doStatementQueryAndUpdate(Connection conn, String id) throws SQLException { try { int key = getNextKey(); Statement s1 = conn.createStatement(); String bValue = "doStatementQueryAndUpdate:" + id + testId; if (key >= MAX_KEY_VALUE) { key = key % MAX_KEY_VALUE; s1.executeUpdate("delete from many_threads where a = " + key); } int count = s1.executeUpdate("insert into many_threads values (" + key + ", '" + bValue + "', 0)"); assertEquals(1, count); assertEquals(key, executeQuery(s1, "select a from many_threads where a = " + key)); s1.executeUpdate("update many_threads set value = a * a, b = b || '&" + bValue + "' where a = " + (key + 1)); s1.close(); if (!conn.getAutoCommit()) { conn.commit(); } } catch (SQLException e) { if (!conn.getAutoCommit()) { try { conn.rollback(); } catch (SQLException e2) { } } } }
Code Sample 2:
public File createTemporaryFile() throws IOException { URL url = clazz.getResource(resource); if (url == null) { throw new IOException("No resource available from '" + clazz.getName() + "' for '" + resource + "'"); } String extension = getExtension(resource); String prefix = "resource-temporary-file-creator"; File file = File.createTempFile(prefix, extension); InputStream input = url.openConnection().getInputStream(); FileOutputStream output = new FileOutputStream(file); com.volantis.synergetics.io.IOUtils.copyAndClose(input, output); return file; } |
00
| Code Sample 1:
public static Dictionary getDefaultConfig(BundleContext bc) { final Dictionary config = new Hashtable(); config.put(HttpConfig.HTTP_ENABLED_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.enabled", "true")); config.put(HttpConfig.HTTPS_ENABLED_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.secure.enabled", "true")); config.put(HttpConfig.HTTP_PORT_KEY, getPropertyAsInteger(bc, "org.osgi.service.http.port", HTTP_PORT_DEFAULT)); config.put(HttpConfig.HTTPS_PORT_KEY, getPropertyAsInteger(bc, "org.osgi.service.http.secure.port", HTTPS_PORT_DEFAULT)); config.put(HttpConfig.HOST_KEY, getPropertyAsString(bc, "org.osgi.service.http.hostname", "")); Properties mimeProps = new Properties(); try { mimeProps.load(HttpConfig.class.getResourceAsStream("/mime.default")); String propurl = getPropertyAsString(bc, "org.knopflerfish.http.mime.props", ""); if (propurl.length() > 0) { URL url = new URL(propurl); Properties userMimeProps = new Properties(); userMimeProps.load(url.openStream()); Enumeration e = userMimeProps.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); mimeProps.put(key, userMimeProps.getProperty(key)); } } } catch (MalformedURLException ignore) { } catch (IOException ignore) { } Vector mimeVector = new Vector(mimeProps.size()); Enumeration e = mimeProps.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); mimeVector.addElement(new String[] { key, mimeProps.getProperty(key) }); } config.put(HttpConfig.MIME_PROPS_KEY, mimeVector); config.put(HttpConfig.SESSION_TIMEOUT_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.session.timeout.default", 1200)); config.put(HttpConfig.CONNECTION_TIMEOUT_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.connection.timeout", 30)); config.put(HttpConfig.CONNECTION_MAX_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.connection.max", 50)); config.put(HttpConfig.DNS_LOOKUP_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.dnslookup", "false")); config.put(HttpConfig.RESPONSE_BUFFER_SIZE_DEFAULT_KEY, getPropertyAsInteger(bc, "org.knopflerfish.http.response.buffer.size.default", 16384)); config.put(HttpConfig.DEFAULT_CHAR_ENCODING_KEY, getPropertyAsString(bc, HttpConfig.DEFAULT_CHAR_ENCODING_KEY, "ISO-8859-1")); config.put(HttpConfig.REQ_CLIENT_AUTH_KEY, getPropertyAsBoolean(bc, "org.knopflerfish.http.req.client.auth", "false")); return config; }
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 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:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } |
11
| Code Sample 1:
public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); }
Code Sample 2:
public static void copieFichier(File fichier1, File fichier2) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fichier1).getChannel(); out = new FileOutputStream(fichier2).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } |
00
| 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 Object invoke(Invocation invocation) throws Throwable { SmartRef smartRef = (SmartRef) invocation.getValue(Invocation.SMARTREF); HttpURLConnection connection = null; ObjectOutputStream out = null; URL url = null; try { url = new URL(smartRef.getProperties().getProperty("org.smartcc.connector.url")); url = new URL(url, smartRef.getLookup()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); out = new ObjectOutputStream(connection.getOutputStream()); out.writeObject(invocation); out.flush(); } catch (ObjectStreamException e) { System.err.println("error: during serialization"); throw new EJBException("error: during serialization", e); } catch (IOException e) { System.err.println("error: could not connect to " + url); throw new ConnectIOException("could not connect to " + url, e); } finally { try { out.close(); } catch (Exception e) { } } boolean isThrowable = false; Object result = null; ObjectInputStream in = null; try { in = new ObjectInputStream(connection.getInputStream()); isThrowable = in.readBoolean(); if (isThrowable || !invocation.getMethod().getReturnType().equals(void.class)) result = in.readObject(); } catch (ObjectStreamException e) { System.err.println("error: during deserialization"); throw new EJBException("error: during deserialization", e); } catch (IOException e) { System.err.println("error: could not connect to " + url); throw new ConnectIOException("could not connect to " + url, e); } finally { try { in.close(); } catch (Exception e) { } } if (isThrowable) throw (Throwable) result; return result; } |
00
| Code Sample 1:
public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; }
Code Sample 2:
private void process(String zipFileName, String directory, String db) throws SQLException { InputStream in = null; try { if (!FileUtils.exists(zipFileName)) { throw new IOException("File not found: " + zipFileName); } String originalDbName = null; int originalDbLen = 0; if (db != null) { originalDbName = getOriginalDbName(zipFileName, db); if (originalDbName == null) { throw new IOException("No database named " + db + " found"); } if (originalDbName.startsWith(File.separator)) { originalDbName = originalDbName.substring(1); } originalDbLen = originalDbName.length(); } in = FileUtils.openFileInputStream(zipFileName); ZipInputStream zipIn = new ZipInputStream(in); while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String fileName = entry.getName(); fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } boolean copy = false; if (db == null) { copy = true; } else if (fileName.startsWith(originalDbName + ".")) { fileName = db + fileName.substring(originalDbLen); copy = true; } if (copy) { OutputStream out = null; try { out = FileUtils.openFileOutputStream(directory + File.separator + fileName, false); IOUtils.copy(zipIn, out); out.close(); } finally { IOUtils.closeSilently(out); } } zipIn.closeEntry(); } zipIn.closeEntry(); zipIn.close(); } catch (IOException e) { throw Message.convertIOException(e, zipFileName); } finally { IOUtils.closeSilently(in); } } |
00
| 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 byte[] evaluateResponse(byte[] responseBytes) throws SaslException { if (firstEvaluation) { firstEvaluation = false; StringBuilder challenge = new StringBuilder(100); Iterator iter = configurationManager.getRealms().values().iterator(); Realm aRealm; while (iter.hasNext()) { aRealm = (Realm) iter.next(); if (aRealm.getFullRealmName().equals("null")) continue; challenge.append("realm=\"" + aRealm.getFullRealmName() + "\""); challenge.append(","); } String nonceUUID = UUID.randomUUID().toString(); String nonce = null; try { nonce = new String(Base64.encodeBase64(MD5Digest(String.valueOf(System.nanoTime() + ":" + nonceUUID))), "US-ASCII"); } catch (UnsupportedEncodingException uee) { throw new SaslException(uee.getMessage(), uee); } catch (GeneralSecurityException uee) { throw new SaslException(uee.getMessage(), uee); } nonces.put(nonce, new ArrayList()); nonces.get(nonce).add(Integer.valueOf(1)); challenge.append("nonce=\"" + nonce + "\""); challenge.append(","); challenge.append("qop=\"" + configurationManager.getSaslQOP() + "\""); challenge.append(","); challenge.append("charset=\"utf-8\""); challenge.append(","); challenge.append("algorithm=\"md5-sess\""); if (configurationManager.getSaslQOP().indexOf("auth-conf") != -1) { challenge.append(","); challenge.append("cipher-opts=\"" + configurationManager.getDigestMD5Ciphers() + "\""); } try { return Base64.encodeBase64(challenge.toString().getBytes("US-ASCII")); } catch (UnsupportedEncodingException uee) { throw new SaslException(uee.getMessage(), uee); } } else { String nonce = null; if (!Base64.isArrayByteBase64(responseBytes)) { throw new SaslException("Can not decode Base64 Content", new MalformedBase64ContentException()); } responseBytes = Base64.decodeBase64(responseBytes); List<byte[]> splittedBytes = splitByteArray(responseBytes, (byte) 0x3d); int tokenCountMinus1 = splittedBytes.size() - 1, lastCommaPos; Map rawDirectives = new HashMap(); String key = null; Map<String, String> directives; try { key = new String(splittedBytes.get(0), "US-ASCII"); for (int i = 1; i < tokenCountMinus1; i++) { key = responseTokenProcessor(splittedBytes, rawDirectives, key, i, tokenCountMinus1); } responseTokenProcessor(splittedBytes, rawDirectives, key, tokenCountMinus1, tokenCountMinus1); if (rawDirectives.containsKey("charset")) { String value = new String((byte[]) rawDirectives.get("charset"), "US-ASCII").toLowerCase(locale); if (value.equals("utf-8")) { encoding = "UTF-8"; } } if (encoding.equals("ISO-8859-1")) { decodeAllAs8859(rawDirectives); } else { decodeMixed(rawDirectives); } directives = rawDirectives; } catch (UnsupportedEncodingException uee) { throw new SaslException(uee.getMessage()); } if (!directives.containsKey("username") || !directives.containsKey("nonce") || !directives.containsKey("nc") || !directives.containsKey("cnonce") || !directives.containsKey("response")) { throw new SaslException("Digest-Response lacks at least one neccesery key-value pair"); } if (directives.get("username").indexOf('@') != -1) { throw new SaslException("digest-response username field must not include domain name", new AuthenticationException()); } if (!directives.containsKey("qop")) { directives.put("qop", QOP_AUTH); } if (!directives.containsKey("realm") || ((String) directives.get("realm")).equals("")) { directives.put("realm", "null"); } nonce = (String) directives.get("nonce"); if (!nonces.containsKey(nonce)) { throw new SaslException("Illegal nonce value"); } List<Integer> nonceListInMap = nonces.get(nonce); int nc = Integer.parseInt((String) directives.get("nc"), 16); if (nonceListInMap.get(nonceListInMap.size() - 1).equals(Integer.valueOf(nc))) { nonceListInMap.add(Integer.valueOf(++nc)); } else { throw new SaslException("Illegal nc value"); } nonceListInMap = null; if (directives.get("qop").equals(QOP_AUTH_INT)) integrity = true; else if (directives.get("qop").equals(QOP_AUTH_CONF)) privacy = true; if (privacy) { if (!directives.containsKey("cipher")) { throw new SaslException("Message confidentially required but cipher entry is missing"); } sessionCipher = directives.get("cipher").toLowerCase(locale); if ("3des,des,rc4-40,rc4,rc4-56".indexOf(sessionCipher) == -1) { throw new SaslException("Unsupported cipher for message confidentiality"); } } String realm = directives.get("realm").toLowerCase(Locale.getDefault()); String username = directives.get("username").toLowerCase(locale); if (username.indexOf('@') == -1) { if (!directives.get("realm").equals("null")) { username += directives.get("realm").substring(directives.get("realm").indexOf('@')); } else if (directives.get("authzid").indexOf('@') != -1) { username += directives.get("authzid").substring(directives.get("authzid").indexOf('@')); } } DomainWithPassword domainWithPassword = configurationManager.getRealmPassword(realm, username); if (domainWithPassword == null || domainWithPassword.getPassword() == null) { log.warn("The supplied username and/or realm do(es) not match a registered entry"); return null; } if (realm.equals("null") && username.indexOf('@') == -1) { username += "@" + domainWithPassword.getDomain(); } byte[] HA1 = toByteArray(domainWithPassword.getPassword()); for (int i = domainWithPassword.getPassword().length - 1; i >= 0; i--) { domainWithPassword.getPassword()[i] = 0xff; } domainWithPassword = null; MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (GeneralSecurityException gse) { throw new SaslException(gse.getMessage()); } md.update(HA1); md.update(":".getBytes()); md.update((directives.get("nonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("cnonce")).getBytes()); if (directives.containsKey("authzid")) { md.update(":".getBytes()); md.update((directives.get("authzid")).getBytes()); } MD5DigestSessionKey = HA1 = md.digest(); String MD5DigestSessionKeyToHex = toHex(HA1, HA1.length); md.update("AUTHENTICATE".getBytes()); md.update(":".getBytes()); md.update((directives.get("digest-uri")).getBytes()); if (!directives.get("qop").equals(QOP_AUTH)) { md.update(":".getBytes()); md.update("00000000000000000000000000000000".getBytes()); } byte[] HA2 = md.digest(); String HA2HEX = toHex(HA2, HA2.length); md.update(MD5DigestSessionKeyToHex.getBytes()); md.update(":".getBytes()); md.update((directives.get("nonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("nc")).getBytes()); md.update(":".getBytes()); md.update((directives.get("cnonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("qop")).getBytes()); md.update(":".getBytes()); md.update(HA2HEX.getBytes()); byte[] responseHash = md.digest(); String HexResponseHash = toHex(responseHash, responseHash.length); if (HexResponseHash.equals(directives.get("response"))) { md.update(":".getBytes()); md.update((directives.get("digest-uri")).getBytes()); if (!directives.get("qop").equals(QOP_AUTH)) { md.update(":".getBytes()); md.update("00000000000000000000000000000000".getBytes()); } HA2 = md.digest(); HA2HEX = toHex(HA2, HA2.length); md.update(MD5DigestSessionKeyToHex.getBytes()); md.update(":".getBytes()); md.update((directives.get("nonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("nc")).getBytes()); md.update(":".getBytes()); md.update((directives.get("cnonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("qop")).getBytes()); md.update(":".getBytes()); md.update(HA2HEX.getBytes()); responseHash = md.digest(); return finalizeAuthentication.finalize(responseHash, username); } else { log.warn("Improper credentials"); return null; } } } |
00
| Code Sample 1:
private static List retrieveQuotes(Report report, Symbol symbol, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, startDate, endDate); EODQuoteFilter filter = new YahooEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
Code Sample 2:
protected URLConnection openConnection(URL url) throws IOException { URLConnection con = url.openConnection(); if ("HTTPS".equalsIgnoreCase(url.getProtocol())) { HttpsURLConnection scon = (HttpsURLConnection) con; try { scon.setSSLSocketFactory(SSLUtil.getSSLSocketFactory(ks, password, alias)); scon.setHostnameVerifier(SSLUtil.getHostnameVerifier(SSLUtil.HOSTCERT_MIN_CHECK)); } catch (GeneralException e) { throw new IOException(e.getMessage()); } catch (GeneralSecurityException e) { throw new IOException(e.getMessage()); } } return con; } |
11
| Code Sample 1:
public static String md5(String source) { MessageDigest md; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); try { md = MessageDigest.getInstance("MD5"); md.update(source.getBytes()); byte[] digested = md.digest(); for (int i = 0; i < digested.length; i++) { pw.printf("%02x", digested[i]); } pw.flush(); return sw.getBuffer().toString(); } catch (NoSuchAlgorithmException e) { return null; } }
Code Sample 2:
private static String digest(String buffer) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(buffer.getBytes()); return new String(encodeHex(md5.digest(key))); } catch (NoSuchAlgorithmException e) { } return null; } |
00
| Code Sample 1:
public void testGetOldVersion() throws ServiceException, IOException, SAXException, ParserConfigurationException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Read again at:" + secondSource.getSourceRevision()); InputStream expected = emptySource.getInputStream(); InputStream actual = secondSource.getInputStream(); assertTrue(isXmlEqual(expected, actual)); }
Code Sample 2:
public static AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { InputStream inputStream = null; if (useragent != null) { URLConnection myCon = url.openConnection(); myCon.setUseCaches(false); myCon.setDoInput(true); myCon.setDoOutput(true); myCon.setAllowUserInteraction(false); myCon.setRequestProperty("User-Agent", useragent); myCon.setRequestProperty("Accept", "*/*"); myCon.setRequestProperty("Icy-Metadata", "1"); myCon.setRequestProperty("Connection", "close"); inputStream = new BufferedInputStream(myCon.getInputStream()); } else { inputStream = new BufferedInputStream(url.openStream()); } try { if (DEBUG == true) { System.err.println("Using AppletVorbisSPIWorkaround to get codec AudioFileFormat(url)"); } return getAudioFileFormat(inputStream); } finally { inputStream.close(); } } |
00
| Code Sample 1:
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); String requestNumber = req.getParameter("reqno"); int parseNumber = Integer.parseInt(requestNumber); Connection con = null; try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); con = DriverManager.getConnection("jdbc:derby:/DerbyDB/AssetDB"); con.setAutoCommit(false); String inet = req.getRemoteAddr(); Statement stmt = con.createStatement(); String sql = "UPDATE REQUEST_DETAILS SET viewed = '1', checked_by = '" + inet + "' WHERE QUERY = ?"; PreparedStatement pst = con.prepareStatement(sql); pst.setInt(1, parseNumber); pst.executeUpdate(); con.commit(); String nextJSP = "/queryRemoved.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP); dispatcher.forward(req, res); } catch (Exception e) { try { con.rollback(); } catch (SQLException ignored) { } out.println("Failed"); } finally { try { if (con != null) con.close(); } catch (SQLException ignored) { } } }
Code Sample 2:
public static SpeciesTree create(String url) throws IOException { SpeciesTree tree = new SpeciesTree(); tree.setUrl(url); System.out.println("Fetching URL: " + url); BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String toParse = null; Properties properties = new Properties(); properties.load(in); String line = properties.getProperty("TREE"); if (line == null) return null; int end = line.indexOf(';'); if (end < 0) end = line.length(); toParse = line.substring(0, end).trim(); System.out.print("Parsing... "); parse(tree, toParse, properties); return tree; } |
11
| Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = 67076096; long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
Code Sample 2:
public static void copy(File _from, File _to) throws IOException { if (_from == null || !_from.exists()) return; FileOutputStream out = null; FileInputStream in = null; try { out = new FileOutputStream(_to); in = new FileInputStream(_from); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } } catch (IOException _e) { throw _e; } finally { if (in != null) in.close(); if (out != null) out.close(); } } |
11
| Code Sample 1:
public static boolean nioWriteFile(FileInputStream inputStream, FileOutputStream out) { if (inputStream == null && out == null) { return false; } try { FileChannel fci = inputStream.getChannel(); FileChannel fco = out.getChannel(); fco.transferFrom(fci, 0, fci.size()); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { FileUtil.safeClose(inputStream); FileUtil.safeClose(out); } }
Code Sample 2:
public static void sendSimpleHTMLMessage(Map<String, String> recipients, String object, String htmlContent, String from) { String message; try { File webinfDir = ClasspathUtils.getClassesDir().getParentFile(); File mailDir = new File(webinfDir, "mail"); File templateFile = new File(mailDir, "HtmlMessageTemplate.html"); StringWriter sw = new StringWriter(); Reader r = new BufferedReader(new FileReader(templateFile)); IOUtils.copy(r, sw); sw.close(); message = sw.getBuffer().toString(); message = message.replaceAll("%MESSAGE_HTML%", htmlContent).replaceAll("%APPLICATION_URL%", FGDSpringUtils.getExternalServerURL()); } catch (IOException e) { throw new RuntimeException(e); } Properties prop = getRealSMTPServerProperties(); if (prop != null) { try { MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(message, "text/html"); multipart.addBodyPart(messageBodyPart); sendHTML(recipients, object, multipart, from); } catch (MessagingException e) { throw new RuntimeException(e); } } else { StringBuffer contenuCourriel = new StringBuffer(); for (Entry<String, String> recipient : recipients.entrySet()) { if (recipient.getValue() == null) { contenuCourriel.append("À : " + recipient.getKey()); } else { contenuCourriel.append("À : " + recipient.getValue() + "<" + recipient.getKey() + ">"); } contenuCourriel.append("\n"); } contenuCourriel.append("Sujet : " + object); contenuCourriel.append("\n"); contenuCourriel.append("Message : "); contenuCourriel.append("\n"); contenuCourriel.append(message); } } |
11
| Code Sample 1:
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { PositionParser pp; Database.init("XIDResult"); pp = new PositionParser("01:33:50.904+30:39:35.79"); String url = "http://simbad.u-strasbg.fr/simbad/sim-script?submit=submit+script&script="; String script = "format object \"%IDLIST[%-30*]|-%COO(A)|%COO(D)|%OTYPELIST(S)\"\n"; String tmp = ""; script += pp.getPosition() + " radius=1m"; url += URLEncoder.encode(script, "ISO-8859-1"); URL simurl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(simurl.openStream())); String boeuf; boolean data_found = false; JSONObject retour = new JSONObject(); JSONArray dataarray = new JSONArray(); JSONArray colarray = new JSONArray(); JSONObject jsloc = new JSONObject(); jsloc.put("sTitle", "ID"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Position"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Type"); colarray.add(jsloc); retour.put("aoColumns", colarray); int datasize = 0; while ((boeuf = in.readLine()) != null) { if (data_found) { String[] fields = boeuf.trim().split("\\|", -1); int pos = fields.length - 1; if (pos >= 3) { String type = fields[pos]; pos--; String dec = fields[pos]; pos--; String ra = fields[pos]; String id = ""; for (int i = 0; i < pos; i++) { id += fields[i]; if (i < (pos - 1)) { id += "|"; } } if (id.length() <= 30) { JSONArray darray = new JSONArray(); darray.add(id.trim()); darray.add(ra + " " + dec); darray.add(type.trim()); dataarray.add(darray); datasize++; } } } else if (boeuf.startsWith("::data")) { data_found = true; } } retour.put("aaData", dataarray); retour.put("iTotalRecords", datasize); retour.put("iTotalDisplayRecords", datasize); System.out.println(retour.toJSONString()); in.close(); }
Code Sample 2:
public static void main(String[] args) throws IOException { PostParameter a1 = new PostParameter("v", Utils.encode("1.0")); PostParameter a2 = new PostParameter("api_key", Utils.encode(RenRenConstant.apiKey)); PostParameter a3 = new PostParameter("method", Utils.encode("notifications.send")); PostParameter a4 = new PostParameter("call_id", System.nanoTime()); PostParameter a5 = new PostParameter("session_key", Utils.encode("5.22af9ee9ad842c7eb52004ece6e96b10.86400.1298646000-350727914")); PostParameter a6 = new PostParameter("to_ids", Utils.encode("350727914")); PostParameter a7 = new PostParameter("notification", "又到了要睡觉的时间了。"); PostParameter a8 = new PostParameter("format", Utils.encode("JSON")); RenRenPostParameters ps = new RenRenPostParameters(Utils.encode(RenRenConstant.secret)); ps.addParameter(a1); ps.addParameter(a2); ps.addParameter(a3); ps.addParameter(a4); ps.addParameter(a5); ps.addParameter(a6); ps.addParameter(a7); ps.addParameter(a8); System.out.println(RenRenConstant.apiUrl + "?" + ps.generateUrl()); URL url = new URL(RenRenConstant.apiUrl + "?" + ps.generateUrl()); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setDoOutput(true); request.setRequestMethod("POST"); System.out.println("Sending request..."); request.connect(); System.out.println("Response: " + request.getResponseCode() + " " + request.getResponseMessage()); BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); String b = null; while ((b = reader.readLine()) != null) { System.out.println(b); } } |
00
| Code Sample 1:
public Message[] expunge() throws MessagingException { Statement oStmt = null; CallableStatement oCall = null; PreparedStatement oUpdt = null; ResultSet oRSet; if (DebugFile.trace) { DebugFile.writeln("Begin DBFolder.expunge()"); DebugFile.incIdent(); } if (0 == (iOpenMode & READ_WRITE)) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open is READ_WRITE mode"); } if ((0 == (iOpenMode & MODE_MBOX)) && (0 == (iOpenMode & MODE_BLOB))) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open in MBOX nor BLOB mode"); } MboxFile oMBox = null; DBSubset oDeleted = new DBSubset(DB.k_mime_msgs, DB.gu_mimemsg + "," + DB.pg_message, DB.bo_deleted + "=1 AND " + DB.gu_category + "='" + oCatg.getString(DB.gu_category) + "'", 100); try { int iDeleted = oDeleted.load(getConnection()); File oFile = getFile(); if (oFile.exists() && iDeleted > 0) { oMBox = new MboxFile(oFile, MboxFile.READ_WRITE); int[] msgnums = new int[iDeleted]; for (int m = 0; m < iDeleted; m++) msgnums[m] = oDeleted.getInt(1, m); oMBox.purge(msgnums); oMBox.close(); } oStmt = oConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); oRSet = oStmt.executeQuery("SELECT p." + DB.file_name + " FROM " + DB.k_mime_parts + " p," + DB.k_mime_msgs + " m WHERE p." + DB.gu_mimemsg + "=m." + DB.gu_mimemsg + " AND m." + DB.id_disposition + "='reference' AND m." + DB.bo_deleted + "=1 AND m." + DB.gu_category + "='" + oCatg.getString(DB.gu_category) + "'"); while (oRSet.next()) { String sFileName = oRSet.getString(1); if (!oRSet.wasNull()) { try { File oRef = new File(sFileName); oRef.delete(); } catch (SecurityException se) { if (DebugFile.trace) DebugFile.writeln("SecurityException " + sFileName + " " + se.getMessage()); } } } oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; oFile = getFile(); oStmt = oConn.createStatement(); oStmt.executeUpdate("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + String.valueOf(oFile.length()) + " WHERE " + DB.gu_category + "='" + getCategory().getString(DB.gu_category) + "'"); oStmt.close(); oStmt = null; if (oConn.getDataBaseProduct() == JDCConnection.DBMS_POSTGRESQL) { oStmt = oConn.createStatement(); for (int d = 0; d < iDeleted; d++) oStmt.executeQuery("SELECT k_sp_del_mime_msg('" + oDeleted.getString(0, d) + "')"); oStmt.close(); oStmt = null; } else { oCall = oConn.prepareCall("{ call k_sp_del_mime_msg(?) }"); for (int d = 0; d < iDeleted; d++) { oCall.setString(1, oDeleted.getString(0, d)); oCall.execute(); } oCall.close(); oCall = null; } if (oFile.exists() && iDeleted > 0) { BigDecimal oUnit = new BigDecimal(1); oStmt = oConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); oRSet = oStmt.executeQuery("SELECT MAX(" + DB.pg_message + ") FROM " + DB.k_mime_msgs + " WHERE " + DB.gu_category + "='getCategory().getString(DB.gu_category)'"); oRSet.next(); BigDecimal oMaxPg = oRSet.getBigDecimal(1); if (oRSet.wasNull()) oMaxPg = new BigDecimal(0); oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; oMaxPg = oMaxPg.add(oUnit); oStmt = oConn.createStatement(); oStmt.executeUpdate("UPDATE " + DB.k_mime_msgs + " SET " + DB.pg_message + "=" + DB.pg_message + "+" + oMaxPg.toString() + " WHERE " + DB.gu_category + "='" + getCategory().getString(DB.gu_category) + "'"); oStmt.close(); oStmt = null; DBSubset oMsgSet = new DBSubset(DB.k_mime_msgs, DB.gu_mimemsg + "," + DB.pg_message, DB.gu_category + "='" + getCategory().getString(DB.gu_category) + "' ORDER BY " + DB.pg_message, 1000); int iMsgCount = oMsgSet.load(oConn); oMBox = new MboxFile(oFile, MboxFile.READ_ONLY); long[] aPositions = oMBox.getMessagePositions(); oMBox.close(); if (iMsgCount != aPositions.length) { throw new IOException("DBFolder.expunge() Message count of " + String.valueOf(aPositions.length) + " at MBOX file " + oFile.getName() + " does not match message count at database index of " + String.valueOf(iMsgCount)); } oMaxPg = new BigDecimal(0); oUpdt = oConn.prepareStatement("UPDATE " + DB.k_mime_msgs + " SET " + DB.pg_message + "=?," + DB.nu_position + "=? WHERE " + DB.gu_mimemsg + "=?"); for (int m = 0; m < iMsgCount; m++) { oUpdt.setBigDecimal(1, oMaxPg); oUpdt.setBigDecimal(2, new BigDecimal(aPositions[m])); oUpdt.setString(3, oMsgSet.getString(0, m)); oUpdt.executeUpdate(); oMaxPg = oMaxPg.add(oUnit); } oUpdt.close(); } oConn.commit(); } catch (SQLException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception e) { } try { if (oStmt != null) oStmt.close(); } catch (Exception e) { } try { if (oCall != null) oCall.close(); } catch (Exception e) { } try { if (oConn != null) oConn.rollback(); } catch (Exception e) { } throw new MessagingException(sqle.getMessage(), sqle); } catch (IOException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception e) { } try { if (oStmt != null) oStmt.close(); } catch (Exception e) { } try { if (oCall != null) oCall.close(); } catch (Exception e) { } try { if (oConn != null) oConn.rollback(); } catch (Exception e) { } throw new MessagingException(sqle.getMessage(), sqle); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBFolder.expunge()"); } return null; }
Code Sample 2:
public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getCanonicalPath()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getCanonicalPath()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getCanonicalPath()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getCanonicalPath()); throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[1024 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); if (fromFile.isHidden()) { } toFile.setLastModified(fromFile.lastModified()); toFile.setExecutable(fromFile.canExecute()); toFile.setReadable(fromFile.canRead()); toFile.setWritable(toFile.canWrite()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } |
11
| Code Sample 1:
public static void perform(ChangeSet changes, ArchiveInputStream in, ArchiveOutputStream out) throws IOException { ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { System.out.println(entry.getName()); boolean copy = true; for (Iterator it = changes.asSet().iterator(); it.hasNext(); ) { Change change = (Change) it.next(); if (change.type() == ChangeSet.CHANGE_TYPE_DELETE) { DeleteChange delete = ((DeleteChange) change); if (entry.getName() != null && entry.getName().equals(delete.targetFile())) { copy = false; } } } if (copy) { System.out.println("Copy: " + entry.getName()); long size = entry.getSize(); out.putArchiveEntry(entry); IOUtils.copy((InputStream) in, out, (int) size); out.closeArchiveEntry(); } System.out.println("---"); } out.close(); }
Code Sample 2:
public GetMessages(String messageType) { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetMessages"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "messages.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&messagetype=" + messageType + "&filename=" + URLEncoder.encode(username, "UTF-8") + "messages.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("message"); int num = nodelist.getLength(); messages = new String[num][7]; for (int i = 0; i < num; i++) { messages[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageid")); messages[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "subject")); messages[i][2] = (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "firstname"))) + " " + (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "lastname"))); messages[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagedatetime")); messages[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagefrom")); messages[i][5] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageto")); messages[i][6] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } } |
11
| Code Sample 1:
public void init(String[] arguments) { if (arguments.length < 1) { printHelp(); return; } String[] valid_args = new String[] { "device*", "d*", "help", "h", "speed#", "s#", "file*", "f*", "gpsd*", "nmea", "n", "garmin", "g", "sirf", "i", "rawdata", "downloadtracks", "downloadwaypoints", "downloadroutes", "deviceinfo", "printposonce", "printpos", "p", "printalt", "printspeed", "printheading", "printsat", "template*", "outfile*", "screenshot*", "printdefaulttemplate", "helptemplate", "nmealogfile*", "l", "uploadtracks", "uploadroutes", "uploadwaypoints", "infile*" }; CommandArguments args = null; try { args = new CommandArguments(arguments, valid_args); } catch (CommandArgumentException cae) { System.err.println("Invalid arguments: " + cae.getMessage()); printHelp(); return; } String filename = null; String serial_port_name = null; boolean gpsd = false; String gpsd_host = "localhost"; int gpsd_port = 2947; int serial_port_speed = -1; GPSDataProcessor gps_data_processor; String nmea_log_file = null; if (args.isSet("help") || (args.isSet("h"))) { printHelp(); return; } if (args.isSet("helptemplate")) { printHelpTemplate(); } if (args.isSet("printdefaulttemplate")) { System.out.println(DEFAULT_TEMPLATE); } if (args.isSet("device")) { serial_port_name = (String) args.getValue("device"); } else if (args.isSet("d")) { serial_port_name = (String) args.getValue("d"); } if (args.isSet("speed")) { serial_port_speed = ((Integer) args.getValue("speed")).intValue(); } else if (args.isSet("s")) { serial_port_speed = ((Integer) args.getValue("s")).intValue(); } if (args.isSet("file")) { filename = (String) args.getValue("file"); } else if (args.isSet("f")) { filename = (String) args.getValue("f"); } if (args.isSet("gpsd")) { gpsd = true; String gpsd_host_port = (String) args.getValue("gpsd"); if (gpsd_host_port != null && gpsd_host_port.length() > 0) { String[] params = gpsd_host_port.split(":"); gpsd_host = params[0]; if (params.length > 0) { gpsd_port = Integer.parseInt(params[1]); } } } if (args.isSet("garmin") || args.isSet("g")) { gps_data_processor = new GPSGarminDataProcessor(); serial_port_speed = 9600; if (filename != null) { System.err.println("ERROR: Cannot read garmin data from file, only serial port supported!"); return; } } else if (args.isSet("sirf") || args.isSet("i")) { gps_data_processor = new GPSSirfDataProcessor(); serial_port_speed = 19200; if (filename != null) { System.err.println("ERROR: Cannot read sirf data from file, only serial port supported!"); return; } } else { gps_data_processor = new GPSNmeaDataProcessor(); serial_port_speed = 4800; } if (args.isSet("nmealogfile") || (args.isSet("l"))) { if (args.isSet("nmealogfile")) nmea_log_file = args.getStringValue("nmealogfile"); else nmea_log_file = args.getStringValue("l"); } if (args.isSet("rawdata")) { gps_data_processor.addGPSRawDataListener(new GPSRawDataListener() { public void gpsRawDataReceived(char[] data, int offset, int length) { System.out.println("RAWLOG: " + new String(data, offset, length)); } }); } GPSDevice gps_device; Hashtable environment = new Hashtable(); if (filename != null) { environment.put(GPSFileDevice.PATH_NAME_KEY, filename); gps_device = new GPSFileDevice(); } else if (gpsd) { environment.put(GPSNetworkGpsdDevice.GPSD_HOST_KEY, gpsd_host); environment.put(GPSNetworkGpsdDevice.GPSD_PORT_KEY, new Integer(gpsd_port)); gps_device = new GPSNetworkGpsdDevice(); } else { if (serial_port_name != null) environment.put(GPSSerialDevice.PORT_NAME_KEY, serial_port_name); if (serial_port_speed > -1) environment.put(GPSSerialDevice.PORT_SPEED_KEY, new Integer(serial_port_speed)); gps_device = new GPSSerialDevice(); } try { gps_device.init(environment); gps_data_processor.setGPSDevice(gps_device); gps_data_processor.open(); gps_data_processor.addProgressListener(this); if ((nmea_log_file != null) && (nmea_log_file.length() > 0)) { gps_data_processor.addGPSRawDataListener(new GPSRawDataFileLogger(nmea_log_file)); } if (args.isSet("deviceinfo")) { System.out.println("GPSInfo:"); String[] infos = gps_data_processor.getGPSInfo(); for (int index = 0; index < infos.length; index++) { System.out.println(infos[index]); } } if (args.isSet("screenshot")) { FileOutputStream out = new FileOutputStream((String) args.getValue("screenshot")); BufferedImage image = gps_data_processor.getScreenShot(); ImageIO.write(image, "PNG", out); } boolean print_waypoints = args.isSet("downloadwaypoints"); boolean print_routes = args.isSet("downloadroutes"); boolean print_tracks = args.isSet("downloadtracks"); if (print_waypoints || print_routes || print_tracks) { VelocityContext context = new VelocityContext(); if (print_waypoints) { List waypoints = gps_data_processor.getWaypoints(); if (waypoints != null) context.put("waypoints", waypoints); else print_waypoints = false; } if (print_tracks) { List tracks = gps_data_processor.getTracks(); if (tracks != null) context.put("tracks", tracks); else print_tracks = false; } if (print_routes) { List routes = gps_data_processor.getRoutes(); if (routes != null) context.put("routes", routes); else print_routes = false; } context.put("printwaypoints", new Boolean(print_waypoints)); context.put("printtracks", new Boolean(print_tracks)); context.put("printroutes", new Boolean(print_routes)); Writer writer; Reader reader; if (args.isSet("template")) { String template_file = (String) args.getValue("template"); reader = new FileReader(template_file); } else { reader = new StringReader(DEFAULT_TEMPLATE); } if (args.isSet("outfile")) writer = new FileWriter((String) args.getValue("outfile")); else writer = new OutputStreamWriter(System.out); addDefaultValuesToContext(context); boolean result = printTemplate(context, reader, writer); } boolean read_waypoints = (args.isSet("uploadwaypoints") && args.isSet("infile")); boolean read_routes = (args.isSet("uploadroutes") && args.isSet("infile")); boolean read_tracks = (args.isSet("uploadtracks") && args.isSet("infile")); if (read_waypoints || read_routes || read_tracks) { ReadGPX reader = new ReadGPX(); String in_file = (String) args.getValue("infile"); reader.parseFile(in_file); if (read_waypoints) gps_data_processor.setWaypoints(reader.getWaypoints()); if (read_routes) gps_data_processor.setRoutes(reader.getRoutes()); if (read_tracks) gps_data_processor.setTracks(reader.getTracks()); } if (args.isSet("printposonce")) { GPSPosition pos = gps_data_processor.getGPSPosition(); System.out.println("Current Position: " + pos); } if (args.isSet("printpos") || args.isSet("p")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.LOCATION, this); } if (args.isSet("printalt")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.ALTITUDE, this); } if (args.isSet("printspeed")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.SPEED, this); } if (args.isSet("printheading")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.HEADING, this); } if (args.isSet("printsat")) { gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.NUMBER_SATELLITES, this); gps_data_processor.addGPSDataChangeListener(GPSDataProcessor.SATELLITE_INFO, this); } if (args.isSet("printpos") || args.isSet("p") || args.isSet("printalt") || args.isSet("printsat") || args.isSet("printspeed") || args.isSet("printheading")) { gps_data_processor.startSendPositionPeriodically(1000L); try { System.in.read(); } catch (IOException ignore) { } } gps_data_processor.close(); } catch (GPSException e) { e.printStackTrace(); } catch (FileNotFoundException fnfe) { System.err.println("ERROR: File not found: " + fnfe.getMessage()); } catch (IOException ioe) { System.err.println("ERROR: I/O Error: " + ioe.getMessage()); } }
Code Sample 2:
public static void main(String[] args) { String command = "java -jar "; String linkerJarPath = ""; String path = ""; String osName = System.getProperty("os.name"); String temp = Launcher.class.getResource("").toString(); int index = temp.indexOf(".jar"); int start = index - 1; while (Character.isLetter(temp.charAt(start))) { start--; } String jarName = temp.substring(start + 1, index + 4); System.out.println(jarName); if (osName.startsWith("Linux")) { temp = temp.substring(temp.indexOf("/"), temp.indexOf(jarName)); } else if (osName.startsWith("Windows")) { temp = temp.substring(temp.indexOf("file:") + 5, temp.indexOf(jarName)); } else { System.exit(0); } path = path + temp; try { path = java.net.URLDecoder.decode(path, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File dir = new File(path); File[] files = dir.listFiles(); String exeJarName = null; for (File f : files) { if (f.getName().endsWith(".jar") && !f.getName().startsWith(jarName)) { exeJarName = f.getName(); break; } } if (exeJarName == null) { System.out.println("no exefile"); System.exit(0); } linkerJarPath = path + exeJarName; String pluginDirPath = path + "plugin" + File.separator; File[] plugins = new File(pluginDirPath).listFiles(); StringBuffer pluginNames = new StringBuffer(""); for (File plugin : plugins) { if (plugin.getAbsolutePath().endsWith(".jar")) { pluginNames.append("plugin/" + plugin.getName() + " "); } } String libDirPath = path + "lib" + File.separator; File[] libs = new File(libDirPath).listFiles(); StringBuffer libNames = new StringBuffer(""); for (File lib : libs) { if (lib.getAbsolutePath().endsWith(".jar")) { libNames.append("lib/" + lib.getName() + " "); } } try { JarFile jarFile = new JarFile(linkerJarPath); Manifest manifest = jarFile.getManifest(); if (manifest == null) { manifest = new Manifest(); } Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Class-Path", pluginNames.toString() + libNames.toString()); String backupFile = linkerJarPath + "back"; FileInputStream copyInput = new FileInputStream(linkerJarPath); FileOutputStream copyOutput = new FileOutputStream(backupFile); byte[] buffer = new byte[4096]; int s; while ((s = copyInput.read(buffer)) > -1) { copyOutput.write(buffer, 0, s); } copyOutput.flush(); copyOutput.close(); copyInput.close(); JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(linkerJarPath), manifest); JarInputStream jarIn = new JarInputStream(new FileInputStream(backupFile)); byte[] buf = new byte[4096]; JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if ("META-INF/MANIFEST.MF".equals(entry.getName())) continue; jarOut.putNextEntry(entry); int read; while ((read = jarIn.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); } jarOut.flush(); jarOut.close(); jarIn.close(); File file = new File(backupFile); if (file.exists()) { file.delete(); } } catch (IOException e1) { e1.printStackTrace(); } try { if (System.getProperty("os.name").startsWith("Linux")) { Runtime runtime = Runtime.getRuntime(); String[] commands = new String[] { "java", "-jar", path + exeJarName }; runtime.exec(commands); } else { path = path.substring(1); command = command + "\"" + path + exeJarName + "\""; System.out.println(command); Runtime.getRuntime().exec(command); } } catch (IOException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
public static int getUrl(final String s) { try { final URL url = new URL(s); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); int count = 0; String data = null; while ((data = reader.readLine()) != null) { System.out.printf("Results(%3d) of data: %s\n", count, data); ++count; } return count; } catch (Exception ex) { throw new RuntimeException(ex); } }
Code Sample 2:
private static BufferedInputStream getHTTPConnection(String sUrl) { URL url = null; BufferedInputStream bis = null; try { url = new URL(sUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setConnectTimeout(30000); connection.setReadTimeout(60000); connection.setRequestProperty("Accept-Encoding", "gzip, deflate"); connection.connect(); String encoding = connection.getContentEncoding(); if (!Utilities.isEmpty(encoding) && "gzip".equalsIgnoreCase(encoding)) { bis = new BufferedInputStream(new GZIPInputStream(connection.getInputStream()), IO_BUFFER_SIZE); } else if (!Utilities.isEmpty(encoding) && "deflate".equalsIgnoreCase(encoding)) { bis = new BufferedInputStream(new InflaterInputStream(connection.getInputStream(), new Inflater(true)), IO_BUFFER_SIZE); } else { bis = new BufferedInputStream(connection.getInputStream(), IO_BUFFER_SIZE); } } catch (Exception e) { LogUtil.e(Constants.TAG, e.getMessage()); } return bis; } |
11
| Code Sample 1:
public void copyFileFromLocalMachineToRemoteMachine(InputStream source, File destination) throws Exception { String fileName = destination.getPath(); File f = new File(getFtpServerHome(), "" + System.currentTimeMillis()); f.deleteOnExit(); org.apache.commons.io.IOUtils.copy(source, new FileOutputStream(f)); remoteHostClient.setAscii(isAscii()); remoteHostClient.setPromptOn(isPrompt()); remoteHostClient.copyFileFromLocalMachineToRemoteClient(f.getName(), fileName); }
Code Sample 2:
private Document saveFile(Document document, File file) throws Exception { List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { preference = preferences.get(0); } SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File folder = new File(sbRepo.append(sbFolder).toString()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } return document; } |
11
| Code Sample 1:
protected void writePage(final CacheItem entry, final TranslationResponse response, ModifyTimes times) throws IOException { if (entry == null) { return; } Set<ResponseHeader> headers = new TreeSet<ResponseHeader>(); for (ResponseHeader h : entry.getHeaders()) { if (TranslationResponse.ETAG.equals(h.getName())) { if (!times.isFileLastModifiedKnown()) { headers.add(new ResponseHeaderImpl(h.getName(), doETagStripWeakMarker(h.getValues()))); } } else { headers.add(h); } } response.addHeaders(headers); if (!times.isFileLastModifiedKnown()) { response.setLastModified(entry.getLastModified()); } response.setTranslationCount(entry.getTranslationCount()); response.setFailCount(entry.getFailCount()); OutputStream output = response.getOutputStream(); try { InputStream input = entry.getContentAsStream(); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { response.setEndState(ResponseStateOk.getInstance()); } }
Code Sample 2:
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; } |
11
| Code Sample 1:
private void copyOneFile(String oldPath, String newPath) { File copiedFile = new File(newPath); try { FileInputStream source = new FileInputStream(oldPath); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } }
Code Sample 2:
@Override protected IStatus run(IProgressMonitor monitor) { final int BUFFER_SIZE = 1024; final int DISPLAY_BUFFER_SIZE = 8196; File sourceFile = new File(_sourceFile); File destFile = new File(_destFile); if (sourceFile.exists()) { try { Log.getInstance(FileCopierJob.class).debug(String.format("Start copy of %s to %s", _sourceFile, _destFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); monitor.beginTask(Messages.getString("FileCopierJob.MainTask") + " " + _sourceFile, (int) ((sourceFile.length() / DISPLAY_BUFFER_SIZE) + 4)); monitor.worked(1); byte[] buffer = new byte[BUFFER_SIZE]; int stepRead = 0; int read; boolean copying = true; while (copying) { read = bis.read(buffer); if (read > 0) { bos.write(buffer, 0, read); stepRead += read; } else { copying = false; } if (monitor.isCanceled()) { bos.close(); bis.close(); deleteFile(_destFile); return Status.CANCEL_STATUS; } if (stepRead >= DISPLAY_BUFFER_SIZE) { monitor.worked(1); stepRead = 0; } } bos.flush(); bos.close(); bis.close(); monitor.worked(1); } catch (Exception e) { processError("Error while copying: " + e.getMessage()); } Log.getInstance(FileCopierJob.class).debug("End of copy."); return Status.OK_STATUS; } else { processError(Messages.getString("FileCopierJob.ErrorSourceDontExists") + sourceFile.getAbsolutePath()); return Status.CANCEL_STATUS; } } |
11
| Code Sample 1:
public static boolean insereLicao(final Connection con, Licao lic, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodLicao(con, lic); String titulo = lic.getTitulo().replaceAll("['\"]", ""); String coment = lic.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO licao VALUES(" + lic.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO lic_aut VALUES(" + lic.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "LICAO: Database error", JOptionPane.ERROR_MESSAGE); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } }
Code Sample 2:
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } |
00
| Code Sample 1:
void sort(int a[]) throws Exception { int j; int limit = a.length; int st = -1; while (st < limit) { boolean flipped = false; st++; limit--; for (j = st; j < limit; j++) { if (stopRequested) { return; } if (a[j] > a[j + 1]) { int T = a[j]; a[j] = a[j + 1]; a[j + 1] = T; flipped = true; pause(st, limit); } } if (!flipped) { return; } for (j = limit; --j >= st; ) { if (stopRequested) { return; } if (a[j] > a[j + 1]) { int T = a[j]; a[j] = a[j + 1]; a[j + 1] = T; flipped = true; pause(st, limit); } } if (!flipped) { return; } } pause(st, limit); }
Code Sample 2:
public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_BACKUP; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } } |
11
| Code Sample 1:
private String getClassname(Bundle bundle) { URL urlEntry = bundle.getEntry("jdbcBundleInfo.xml"); InputStream in = null; try { in = urlEntry.openStream(); try { StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { if (!line.startsWith("<!DOCTYPE")) { sb.append(line); } } SAXBuilder builder = new SAXBuilder(false); Document doc = builder.build(new StringReader(sb.toString())); Element eRoot = doc.getRootElement(); if ("jdbcBundleInfo".equals(eRoot.getName())) { Attribute atri = eRoot.getAttribute("className"); if (atri != null) { return atri.getValue(); } } } catch (JDOMException e) { } } catch (IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } return null; }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } |
00
| Code Sample 1:
public int read(String name) { status = STATUS_OK; try { name = name.trim(); if (name.indexOf("://") > 0) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; }
Code Sample 2:
public static void main(String[] args) throws FileNotFoundException, IOException { String filePath = "/Users/francisbaril/Downloads/test-1.pdf"; String testFilePath = "/Users/francisbaril/Desktop/testpdfbox/test.pdf"; File file = new File(filePath); final File testFile = new File(testFilePath); if (testFile.exists()) { testFile.delete(); } IOUtils.copy(new FileInputStream(file), new FileOutputStream(testFile)); System.out.println(getLongProperty(new FileInputStream(testFile), PROPRIETE_ID_IGID)); } |
11
| Code Sample 1:
public static boolean writeFile(HttpServletResponse resp, File reqFile) { boolean retVal = false; InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(reqFile)); IOUtils.copy(in, resp.getOutputStream()); logger.debug("File successful written to servlet response: " + reqFile.getAbsolutePath()); } catch (FileNotFoundException e) { logger.error("Resource not found: " + reqFile.getAbsolutePath()); } catch (IOException e) { logger.error(String.format("Error while rendering [%s]: %s", reqFile.getAbsolutePath(), e.getMessage()), e); } finally { IOUtils.closeQuietly(in); } return retVal; }
Code Sample 2:
public static void copyFile(String f_in, String f_out, boolean remove) throws FileNotFoundException, IOException { if (remove) { PogoString readcode = new PogoString(PogoUtil.readFile(f_in)); readcode = PogoUtil.removeLogMessages(readcode); PogoUtil.writeFile(f_out, readcode.str); } else { FileInputStream fid = new FileInputStream(f_in); FileOutputStream fidout = new FileOutputStream(f_out); int nb = fid.available(); byte[] inStr = new byte[nb]; if (fid.read(inStr) > 0) fidout.write(inStr); fid.close(); fidout.close(); } } |
11
| Code Sample 1:
@Override public String getData(String blipApiPath, String authHeader) { try { URL url = new URL(BLIP_API_URL + blipApiPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (authHeader != null) { conn.addRequestProperty("Authorization", "Basic " + authHeader); } BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuffer content = new StringBuffer(); System.out.println("Resp code " + conn.getResponseCode()); while ((line = reader.readLine()) != null) { System.out.println(">> " + line); content.append(line); } reader.close(); return content.toString(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } }
Code Sample 2:
public void readData() throws IOException { i = 0; j = 0; URL url = getClass().getResource("resources/tuneGridMaster.dat"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); tune_x[i][j] = Double.parseDouble(st.nextToken()); gridmin = tune_x[i][j]; temp_prev = tune_x[i][j]; tune_y[i][j] = Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); j++; int k = 0; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } tune_x[i][j] = temp_new; tune_y[i][j] = Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; k++; } gridmax = tune_x[i][j - 1]; } |
00
| Code Sample 1:
public String getPassword(URI uri) { if (_getPassword(uri) != null) return _getPassword(uri); String result = null; try { String sUri = scrubURI(uri); URL url = new URL(TEMP_PASSWORD_SERVICE_URL + "?SID=" + sessionId + "&ruri=" + URLEncoder.encode(sUri, "UTF-8")); JSONObject jsonObject = null; URLConnection conn = url.openConnection(); InputStream istream = conn.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(istream)); if ((result = in.readLine()) != null) { jsonObject = new JSONObject(result); } if (jsonObject.has("success")) { if (jsonObject.get("success").toString().equals("false")) { if (jsonObject.has("error")) { logger.log("Returned error message from temporary password service is: " + jsonObject.get("error")); } return null; } } if (jsonObject.has("temppass")) { result = (String) jsonObject.get("temppass"); } } catch (java.io.FileNotFoundException fe) { logger.log("Could not find temporary password service. " + fe); fe.printStackTrace(); } catch (Exception e) { logger.log("Exception getting temporary password. " + e); e.printStackTrace(); } if (result == null) return null; return result; }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
11
| Code Sample 1:
public static void cpdir(File src, File dest) throws BrutException { dest.mkdirs(); File[] files = src.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; File destFile = new File(dest.getPath() + File.separatorChar + file.getName()); if (file.isDirectory()) { cpdir(file, destFile); continue; } try { InputStream in = new FileInputStream(file); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); } catch (IOException ex) { throw new BrutException("Could not copy file: " + file, ex); } } }
Code Sample 2:
public void loadXML(URL flux, int status, File file) { try { SAXBuilder sbx = new SAXBuilder(); try { if (file.exists()) { file.delete(); } if (!file.exists()) { URLConnection conn = flux.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(10000); InputStream is = conn.getInputStream(); OutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) out.write(buf, 0, len); out.close(); is.close(); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "Exeption retrieving XML", e); } try { document = sbx.build(new FileInputStream(file)); } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "xml error ", e); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "TsukiQueryError", e); } if (document != null) { root = document.getRootElement(); PopulateDatabase(root, status); } } |
00
| Code Sample 1:
public static String[] parsePLS(String strURL, Context c) { URL url; URLConnection urlConn = null; String TAG = "parsePLS"; Vector<String> radio = new Vector<String>(); final String filetoken = "file"; final String SPLITTER = "="; try { url = new URL(strURL); urlConn = url.openConnection(); Log.d(TAG, "Got data"); } catch (IOException ioe) { Log.e(TAG, "Could not connect to " + strURL); } try { DataInputStream in = new DataInputStream(urlConn.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { String temp = strLine.toLowerCase(); Log.d(TAG, strLine); if (temp.startsWith(filetoken)) { String[] s = Pattern.compile(SPLITTER).split(temp); radio.add(s[1]); Log.d(TAG, "Found audio " + s[1]); } } br.close(); in.close(); } catch (Exception e) { Log.e(TAG, "Trouble reading file: " + e.getMessage()); } String[] t = new String[0]; String[] r = null; if (radio.size() != 0) { r = (String[]) radio.toArray(t); Log.d(TAG, "Found total: " + String.valueOf(r.length)); } return r; }
Code Sample 2:
public static String move_files(String sessionid, String keys, String absolutePathForTheDestinationTag) { String resultJsonString = "some problem existed inside the create_new_tag() function if you see this string"; try { Log.d("current running function name:", "move_files"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "move_file")); nameValuePairs.add(new BasicNameValuePair("absolute_new_parent_tag", absolutePathForTheDestinationTag)); nameValuePairs.add(new BasicNameValuePair("keys", keys)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); resultJsonString = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", resultJsonString); return resultJsonString; } catch (Exception e) { e.printStackTrace(); } return resultJsonString; } |
00
| Code Sample 1:
public ProcessorOutput createOutput(String name) { ProcessorOutput output = new ProcessorImpl.CacheableTransformerOutputImpl(getClass(), name) { protected void readImpl(org.orbeon.oxf.pipeline.api.PipelineContext context, final ContentHandler contentHandler) { ProcessorInput i = getInputByName(INPUT_DATA); try { Grammar grammar = (Grammar) readCacheInputAsObject(context, getInputByName(INPUT_CONFIG), new CacheableInputReader() { public Object read(org.orbeon.oxf.pipeline.api.PipelineContext context, ProcessorInput input) { final Locator[] locator = new Locator[1]; GrammarReader grammarReader = new XMLSchemaReader(new GrammarReaderController() { public void error(Locator[] locators, String s, Exception e) { throw new ValidationException(s, e, new LocationData(locators[0])); } public void warning(Locator[] locators, String s) { throw new ValidationException(s, new LocationData(locators[0])); } public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { URL url = URLFactory.createURL((locator[0] != null && locator[0].getSystemId() != null) ? locator[0].getSystemId() : null, systemId); InputSource i = new InputSource(url.openStream()); i.setSystemId(url.toString()); return i; } }); readInputAsSAX(context, input, new ForwardingContentHandler(grammarReader) { public void setDocumentLocator(Locator loc) { super.setDocumentLocator(loc); locator[0] = loc; } }); return grammarReader.getResultAsGrammar(); } }); DocumentDeclaration vgm = new REDocumentDeclaration(grammar.getTopLevel(), new ExpressionPool()); Verifier verifier = new Verifier(vgm, new ErrorHandler()) { boolean stopDecorating = false; private void generateErrorElement(ValidationException ve) throws SAXException { if (decorateOutput && ve != null) { if (!stopDecorating) { AttributesImpl a = new AttributesImpl(); a.addAttribute("", ValidationProcessor.MESSAGE_ATTRIBUTE, ValidationProcessor.MESSAGE_ATTRIBUTE, "CDATA", ve.getSimpleMessage()); a.addAttribute("", ValidationProcessor.SYSTEMID_ATTRIBUTE, ValidationProcessor.SYSTEMID_ATTRIBUTE, "CDATA", ve.getLocationData().getSystemID()); a.addAttribute("", ValidationProcessor.LINE_ATTRIBUTE, ValidationProcessor.LINE_ATTRIBUTE, "CDATA", Integer.toString(ve.getLocationData().getLine())); a.addAttribute("", ValidationProcessor.COLUMN_ATTRIBUTE, ValidationProcessor.COLUMN_ATTRIBUTE, "CDATA", Integer.toString(ve.getLocationData().getCol())); contentHandler.startElement(ValidationProcessor.ORBEON_ERROR_NS, ValidationProcessor.ERROR_ELEMENT, ValidationProcessor.ORBEON_ERROR_PREFIX + ":" + ValidationProcessor.ERROR_ELEMENT, a); contentHandler.endElement(ValidationProcessor.ORBEON_ERROR_NS, ValidationProcessor.ERROR_ELEMENT, ValidationProcessor.ORBEON_ERROR_PREFIX + ":" + ValidationProcessor.ERROR_ELEMENT); stopDecorating = true; } } else { throw ve; } } public void characters(char[] chars, int i, int i1) throws SAXException { try { super.characters(chars, i, i1); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.characters(chars, i, i1); } public void endDocument() throws SAXException { try { super.endDocument(); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.endDocument(); } public void endElement(String s, String s1, String s2) throws SAXException { try { super.endElement(s, s1, s2); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.endElement(s, s1, s2); } public void startDocument() throws SAXException { try { super.startDocument(); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.startDocument(); } public void startElement(String s, String s1, String s2, Attributes attributes) throws SAXException { ((ErrorHandler) getErrorHandler()).setElement(s, s1); try { super.startElement(s, s1, s2, attributes); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.startElement(s, s1, s2, attributes); } public void endPrefixMapping(String s) { try { super.endPrefixMapping(s); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.endPrefixMapping(s); } catch (SAXException se) { throw new OXFException(se.getException()); } } public void processingInstruction(String s, String s1) { try { super.processingInstruction(s, s1); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.processingInstruction(s, s1); } catch (SAXException e) { throw new OXFException(e.getException()); } } public void setDocumentLocator(Locator locator) { try { super.setDocumentLocator(locator); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } contentHandler.setDocumentLocator(locator); } public void skippedEntity(String s) { try { super.skippedEntity(s); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getMessage()); } } try { contentHandler.skippedEntity(s); } catch (SAXException e) { throw new OXFException(e.getException()); } } public void startPrefixMapping(String s, String s1) { try { super.startPrefixMapping(s, s1); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.startPrefixMapping(s, s1); } catch (SAXException e) { throw new OXFException(e.getException()); } } }; readInputAsSAX(context, getInputByName(INPUT_DATA), verifier); } catch (Exception e) { throw new OXFException(e); } } }; addOutput(name, output); return output; }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } |
00
| Code Sample 1:
public static void main(String[] args) { try { URL url = new URL("http://localhost:8080/axis/services/Tripcom?wsdl"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-type", "text/xml; charset=utf-8"); connection.setRequestProperty("SOAPAction", "http://tempuri.org/GetTime"); String msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<soap:Envelope " + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + " <soap:Body>\n" + " <rdTest xmlns=\"http://tempuri.org/\"> \n" + " <tns:rdTest message=\"tns:rdTest\"/> \n" + " </rdTest>" + " </soap:Body>\n" + "</soap:Envelope>"; byte[] bytes = msg.getBytes(); connection.setRequestProperty("Content-length", String.valueOf(bytes.length)); System.out.println("\nSOAP Aufruf:"); System.out.println("Content-type:" + connection.getRequestProperty("Content-type")); System.out.println("Content-length:" + connection.getRequestProperty("Content-length")); System.out.println("SOAPAction:" + connection.getRequestProperty("SOAPAction")); System.out.println(msg); OutputStream out = connection.getOutputStream(); out.write(bytes); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; System.out.println("\nServer Antwort:"); while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } catch (Exception e) { System.out.println("FEHLER:" + e); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
00
| Code Sample 1:
public void testSetRequestProperty() throws Exception { MockHTTPServer httpServer = new MockHTTPServer("HTTP Server for User-Specified Request Property", 2); httpServer.start(); synchronized (bound) { if (!httpServer.started) { bound.wait(5000); } } HttpURLConnection urlConnection = (HttpURLConnection) new URL("http://localhost:" + httpServer.port()).openConnection(); assertEquals(0, urlConnection.getRequestProperties().size()); final String PROPERTY1 = "Accept"; final String PROPERTY2 = "Connection"; urlConnection.setRequestProperty(PROPERTY1, null); urlConnection.setRequestProperty(PROPERTY1, null); urlConnection.setRequestProperty(PROPERTY2, "keep-alive"); assertEquals(2, urlConnection.getRequestProperties().size()); assertNull(urlConnection.getRequestProperty(PROPERTY1)); assertEquals("keep-alive", urlConnection.getRequestProperty(PROPERTY2)); urlConnection.setRequestProperty(PROPERTY1, "/"); urlConnection.setRequestProperty(PROPERTY2, null); assertEquals("/", urlConnection.getRequestProperty(PROPERTY1)); assertNull(urlConnection.getRequestProperty(PROPERTY2)); }
Code Sample 2:
public ActionForward uploadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_response) { ActionMessages errors = new ActionMessages(); ActionMessages messages = new ActionMessages(); String returnPage = "submitPocketSampleInformationPage"; UploadForm form = (UploadForm) actForm; Integer shippingId = null; try { eHTPXXLSParser parser = new eHTPXXLSParser(); String proposalCode; String proposalNumber; String proposalName; String uploadedFileName; String realXLSPath; if (request != null) { proposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE); proposalNumber = String.valueOf(request.getSession().getAttribute(Constants.PROPOSAL_NUMBER)); proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = form.getRequestFile().getFileName(); String fileName = proposalName + "_" + uploadedFileName; realXLSPath = request.getRealPath("\\tmp\\") + "\\" + fileName; FormFile f = form.getRequestFile(); InputStream in = f.getInputStream(); File outputFile = new File(realXLSPath); if (outputFile.exists()) outputFile.delete(); FileOutputStream out = new FileOutputStream(outputFile); while (in.available() != 0) { out.write(in.read()); out.flush(); } out.flush(); out.close(); } else { proposalCode = "ehtpx"; proposalNumber = "1"; proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = "ispyb-template41.xls"; realXLSPath = "D:\\" + uploadedFileName; } FileInputStream inFile = new FileInputStream(realXLSPath); parser.retrieveShippingId(realXLSPath); shippingId = parser.getShippingId(); String requestShippingId = form.getShippingId(); if (requestShippingId != null && !requestShippingId.equals("")) { shippingId = new Integer(requestShippingId); } ClientLogger.getInstance().debug("uploadFile for shippingId " + shippingId); if (shippingId != null) { Log.debug(" ---[uploadFile] Upload for Existing Shipment (DewarTRacking): Deleting Samples from Shipment :"); double nbSamplesContainers = DBAccess_EJB.DeleteAllSamplesAndContainersForShipping(shippingId); if (nbSamplesContainers > 0) parser.getValidationWarnings().add(new XlsUploadException("Shipment contained Samples and/or Containers", "Previous Samples and/or Containers have been deleted and replaced by new ones.")); else parser.getValidationWarnings().add(new XlsUploadException("Shipment contained no Samples and no Containers", "Samples and Containers have been added.")); } Hashtable<String, Hashtable<String, Integer>> listProteinAcronym_SampleName = new Hashtable<String, Hashtable<String, Integer>>(); ProposalFacadeLocal proposal = ProposalFacadeUtil.getLocalHome().create(); ProteinFacadeLocal protein = ProteinFacadeUtil.getLocalHome().create(); CrystalFacadeLocal crystal = CrystalFacadeUtil.getLocalHome().create(); ProposalLightValue targetProposal = (ProposalLightValue) (((ArrayList) proposal.findByCodeAndNumber(proposalCode, new Integer(proposalNumber))).get(0)); ArrayList listProteins = (ArrayList) protein.findByProposalId(targetProposal.getProposalId()); for (int p = 0; p < listProteins.size(); p++) { ProteinValue prot = (ProteinValue) listProteins.get(p); Hashtable<String, Integer> listSampleName = new Hashtable<String, Integer>(); CrystalLightValue listCrystals[] = prot.getCrystals(); for (int c = 0; c < listCrystals.length; c++) { CrystalLightValue _xtal = (CrystalLightValue) listCrystals[c]; CrystalValue xtal = crystal.findByPrimaryKey(_xtal.getPrimaryKey()); BlsampleLightValue listSamples[] = xtal.getBlsamples(); for (int s = 0; s < listSamples.length; s++) { BlsampleLightValue sample = listSamples[s]; listSampleName.put(sample.getName(), sample.getBlSampleId()); } } listProteinAcronym_SampleName.put(prot.getAcronym(), listSampleName); } parser.validate(inFile, listProteinAcronym_SampleName, targetProposal.getProposalId()); List listErrors = parser.getValidationErrors(); List listWarnings = parser.getValidationWarnings(); if (listErrors.size() == 0) { parser.open(realXLSPath); if (parser.getCrystals().size() == 0) { parser.getValidationErrors().add(new XlsUploadException("No crystals have been found", "Empty shipment")); } } Iterator errIt = listErrors.iterator(); while (errIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) errIt.next(); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveErrors(request, errors); } catch (Exception e) { } Iterator warnIt = listWarnings.iterator(); while (warnIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) warnIt.next(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveMessages(request, messages); } catch (Exception e) { } if (listErrors.size() > 0) { resetCounts(shippingId); return mapping.findForward("submitPocketSampleInformationPage"); } if (listWarnings.size() > 0) returnPage = "submitPocketSampleInformationPage"; String crystalDetailsXML; XtalDetails xtalDetailsWebService = new XtalDetails(); CrystalDetailsBuilder cDE = new CrystalDetailsBuilder(); CrystalDetailsElement cd = cDE.createCrystalDetailsElement(proposalName, parser.getCrystals()); cDE.validateJAXBObject(cd); crystalDetailsXML = cDE.marshallJaxBObjToString(cd); xtalDetailsWebService.submitCrystalDetails(crystalDetailsXML); String diffractionPlan; DiffractionPlan diffractionPlanWebService = new DiffractionPlan(); DiffractionPlanBuilder dPB = new DiffractionPlanBuilder(); Iterator it = parser.getDiffractionPlans().iterator(); while (it.hasNext()) { DiffractionPlanElement dpe = (DiffractionPlanElement) it.next(); dpe.setProjectUUID(proposalName); diffractionPlan = dPB.marshallJaxBObjToString(dpe); diffractionPlanWebService.submitDiffractionPlan(diffractionPlan); } String crystalShipping; Shipping shippingWebService = new Shipping(); CrystalShippingBuilder cSB = new CrystalShippingBuilder(); Person person = cSB.createPerson("XLS Upload", null, "ISPyB", null, null, "ISPyB", null, "[email protected]", "0000", "0000", null, null); Laboratory laboratory = cSB.createLaboratory("Generic Laboratory", "ISPyB Lab", "Sandwich", "Somewhere", "UK", "ISPyB", "ispyb.esrf.fr", person); DeliveryAgent deliveryAgent = parser.getDeliveryAgent(); CrystalShipping cs = cSB.createCrystalShipping(proposalName, laboratory, deliveryAgent, parser.getDewars()); String shippingName; shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xls")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xls") : 0); if (shippingName.equalsIgnoreCase("")) shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xlt")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xlt") : 0); cs.setName(shippingName); crystalShipping = cSB.marshallJaxBObjToString(cs); shippingWebService.submitCrystalShipping(crystalShipping, (ArrayList) parser.getDiffractionPlans(), shippingId); ServerLogger.Log4Stat("XLS_UPLOAD", proposalName, uploadedFileName); } catch (XlsUploadException e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.getMessage())); ClientLogger.getInstance().error(e.toString()); saveErrors(request, errors); return mapping.findForward("error"); } catch (Exception e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); ClientLogger.getInstance().error(e.toString()); e.printStackTrace(); saveErrors(request, errors); return mapping.findForward("error"); } setCounts(shippingId); return mapping.findForward(returnPage); } |
Subsets and Splits