label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
| Code Sample 1:
private static Map<String, File> loadServiceCache() { ArrayList<String> preferredOrder = new ArrayList<String>(); HashMap<String, File> serviceFileMapping = new HashMap<String, File>(); File file = new File(IsqlToolkit.getBaseDirectory(), CACHE_FILE); if (!file.exists()) { return serviceFileMapping; } if (file.canRead()) { FileReader fileReader = null; try { fileReader = new FileReader(file); BufferedReader lineReader = new BufferedReader(fileReader); while (lineReader.ready()) { String data = lineReader.readLine(); if (data.charAt(0) == '#') { continue; } int idx0 = 0; int idx1 = data.indexOf(SERVICE_FIELD_SEPERATOR); String name = StringUtilities.decodeASCII(data.substring(idx0, idx1)); String uri = StringUtilities.decodeASCII(data.substring(idx1 + 1)); if (name.equalsIgnoreCase(KEY_SERVICE_LIST)) { StringTokenizer st = new StringTokenizer(uri, SERVICE_SEPERATOR); while (st.hasMoreTokens()) { String serviceName = st.nextToken(); preferredOrder.add(serviceName.toLowerCase().trim()); } continue; } try { URL url = new URL(uri); File serviceFile = new File(url.getFile()); if (serviceFile.isDirectory()) { logger.warn(messages.format("compatability_kit.service_mapped_to_directory", name, uri)); continue; } else if (!serviceFile.canRead()) { logger.warn(messages.format("compatability_kit.service_not_readable", name, uri)); continue; } else if (!serviceFile.exists()) { logger.warn(messages.format("compatability_kit.service_does_not_exist", name, uri)); continue; } String bindName = name.toLowerCase().trim(); InputStream inputStream = null; try { inputStream = url.openStream(); InputSource inputSource = new InputSource(inputStream); bindName = ServiceDigester.parseService(inputSource, IsqlToolkit.getSharedEntityResolver()).getName(); } catch (Exception error) { continue; } if (serviceFileMapping.put(bindName, serviceFile) != null) { logger.warn(messages.format("compatability_kit.service_duplicate_name_error", name, uri)); } } catch (MalformedURLException e) { logger.error(messages.format("compatability_kit.service_uri_error", name, uri), e); } } } catch (IOException ioe) { logger.error("compatability_kit.service_generic_error", ioe); } finally { if (fileReader != null) { try { fileReader.close(); } catch (Throwable ignored) { } } } } return serviceFileMapping; }
Code Sample 2:
public CacheServiceFactoryImpl() { @SuppressWarnings("static-access") URL url = this.getClass().getClassLoader().getResource("mwt/xml/xdbforms/configuration/ehcache.xml"); InputStream is; try { is = url.openStream(); cacheManager = CacheManager.create(is); } catch (IOException ex) { System.err.println("NOn riesco ad aprire il file di configurazione ehcache.xml"); } } |
00
| Code Sample 1:
public List<BadassEntry> parse() { mBadassEntries = new ArrayList<BadassEntry>(); try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; boolean flag1 = false; while ((line = reader.readLine()) != null) { line = line.trim(); if (!flag1 && line.contains(START_PARSE)) flag1 = true; if (flag1 && line.contains(STOP_PARSE)) break; if (flag1) { if (line.contains(ENTRY_HINT)) { parseBadass(line); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mBadassEntries; }
Code Sample 2:
public static String getDigestResponse(String user, String password, String method, String requri, String authstr) { String realm = ""; String nonce = ""; String opaque = ""; String algorithm = ""; String qop = ""; StringBuffer digest = new StringBuffer(); String cnonce; String noncecount; String pAuthStr = authstr; int ptr = 0; String response = ""; int i = 0; StringTokenizer st = new StringTokenizer(pAuthStr, ","); StringTokenizer stprob = null; String str = null; String key = null; String value = null; Properties probs = new Properties(); while (st.hasMoreTokens()) { String nextToken = st.nextToken(); stprob = new StringTokenizer(nextToken, "="); key = stprob.nextToken(); value = stprob.nextToken(); if (value.charAt(0) == '"' || value.charAt(0) == '\'') { value = value.substring(1, value.length() - 1); } probs.put(key, value); } digest.append("Digest username=\"" + user + "\", "); digest.append("realm=\""); digest.append(probs.getProperty("realm")); digest.append("\", "); digest.append("nonce=\""); digest.append(probs.getProperty("nonce")); digest.append("\", "); digest.append("uri=\"" + requri + "\", "); cnonce = "abcdefghi"; noncecount = "00000001"; String toDigest = user + ":" + realm + ":" + password; byte[] digestbuffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toDigest.getBytes()); digestbuffer = md.digest(); } catch (Exception e) { System.err.println("Error creating digest request: " + e); return null; } digest.append("qop=\"auth\", "); digest.append("cnonce=\"" + cnonce + "\", "); digest.append("nc=" + noncecount + ", "); digest.append("response=\"" + response + "\""); if (probs.getProperty("opaque") != null) { digest.append(", opaque=\"" + probs.getProperty("opaque") + "\""); } System.out.println("SipProtocol: Digest calculated."); return digest.toString(); } |
00
| Code Sample 1:
public FTPClient getFTP(final Credentials credentials, final String remoteFile) throws NumberFormatException, SocketException, IOException, AccessDeniedException { String fileName = extractFilename(remoteFile); String fileDirectory = getPathName(remoteFile).substring(0, getPathName(remoteFile).indexOf(fileName)); FTPClient ftp; ftp = new FTPClient(); loadConfig(); logger.info("FTP connection to: " + extractHostname(remoteFile)); logger.info("FTP PORT: " + prop.getProperty("port")); ftp.connect(extractHostname(remoteFile), Integer.parseInt(prop.getProperty("port"))); int reply = ftp.getReplyCode(); if (!(FTPReply.isPositiveCompletion(reply))) { return null; } ftp.setFileTransferMode(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!ftp.login(credentials.getUserName(), credentials.getPassword())) { throw new AccessDeniedException(prop.getProperty("login_message")); } if (fileDirectory != null) { ftp.changeWorkingDirectory(fileDirectory); } return ftp; }
Code Sample 2:
public static void main(String[] arg) throws IOException { XmlPullParserFactory PULL_PARSER_FACTORY; try { PULL_PARSER_FACTORY = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); PULL_PARSER_FACTORY.setNamespaceAware(true); DasParser dp = new DasParser(PULL_PARSER_FACTORY); URL url = new URL("http://www.ebi.ac.uk/das-srv/uniprot/das/uniprot/features?segment=P05067"); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String aLine, xml = ""; while ((aLine = br.readLine()) != null) { xml += aLine; } WritebackDocument wbd = dp.parse(xml); System.out.println("FIN" + wbd); } catch (XmlPullParserException xppe) { throw new IllegalStateException("Fatal Exception thrown at initialisation. Cannot initialise the PullParserFactory required to allow generation of the DAS XML.", xppe); } } |
00
| Code Sample 1:
public void render(ParagraphElement cnt, double x, double y, Graphics2D g, LayoutingContext layoutingContext, FlowContext flowContext) { InlineImageContent ic = (InlineImageContent) cnt; try { URLConnection urlConn = ic.getUrl().openConnection(); urlConn.setConnectTimeout(15000); ImageInputStream iis = ImageIO.createImageInputStream(urlConn.getInputStream()); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { System.out.println("loading image " + ic.getUrl()); ImageReader reader = readers.next(); reader.setInput(iis, true); if (flowContext.pdfContext == null) { RenderedImage img = reader.readAsRenderedImage(0, null); renderOnGraphics(img, x, y, ic, g, layoutingContext, flowContext); } else { BufferedImage img = reader.read(0); renderDirectPdf(img, x, y, ic, g, layoutingContext, flowContext); } reader.dispose(); } else System.err.println("cannot render image " + ic.getUrl() + " - no suitable reader!"); } catch (Exception exc) { System.err.println("cannot render image " + ic.getUrl() + " due to exception:"); System.err.println(exc); exc.printStackTrace(System.err); } }
Code Sample 2:
public static String calcCRC(String phrase) { StringBuffer crcCalc = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(phrase.getBytes()); byte[] tabDigest = md.digest(); for (int i = 0; i < tabDigest.length; i++) { String octet = "0" + Integer.toHexString(tabDigest[i]); crcCalc.append(octet.substring(octet.length() - 2)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return crcCalc.toString(); } |
11
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
@Test public void testCopyOverSize() throws IOException { final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(TEST_DATA.length); final int cpySize = ExtraIOUtils.copy(in, out, TEST_DATA.length + Long.SIZE); assertEquals("Mismatched copy size", TEST_DATA.length, cpySize); final byte[] outArray = out.toByteArray(); assertArrayEquals("Mismatched data", TEST_DATA, outArray); } |
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:
boolean copyFileStructure(File oldFile, File newFile) { if (oldFile == null || newFile == null) return false; File searchFile = newFile; do { if (oldFile.equals(searchFile)) return false; searchFile = searchFile.getParentFile(); } while (searchFile != null); if (oldFile.isDirectory()) { if (progressDialog != null) { progressDialog.setDetailFile(oldFile, ProgressDialog.COPY); } if (simulateOnly) { } else { if (!newFile.mkdirs()) return false; } File[] subFiles = oldFile.listFiles(); if (subFiles != null) { if (progressDialog != null) { progressDialog.addWorkUnits(subFiles.length); } for (int i = 0; i < subFiles.length; i++) { File oldSubFile = subFiles[i]; File newSubFile = new File(newFile, oldSubFile.getName()); if (!copyFileStructure(oldSubFile, newSubFile)) return false; if (progressDialog != null) { progressDialog.addProgress(1); if (progressDialog.isCancelled()) return false; } } } } else { if (simulateOnly) { } else { FileReader in = null; FileWriter out = null; try { in = new FileReader(oldFile); out = new FileWriter(newFile); int count; while ((count = in.read()) != -1) out.write(count); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { return false; } } } } return true; } |
11
| Code Sample 1:
private static String GetSHA1(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 LoginHttpPostProcessor.ConvertToHex(sha1hash); }
Code Sample 2:
public static String encrypt(String algorithm, String[] input) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.reset(); for (int i = 0; i < input.length; i++) { if (input[i] != null) md.update(input[i].getBytes("UTF-8")); } byte[] messageDigest = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString((0xf0 & messageDigest[i]) >> 4)); hexString.append(Integer.toHexString(0x0f & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (NullPointerException e) { return new StringBuffer().toString(); } } |
00
| Code Sample 1:
protected void channelConnected() throws IOException { MessageDigest md = null; String digest = ""; try { String userid = nateon.getUserId(); if (userid.endsWith("@nate.com")) userid = userid.substring(0, userid.lastIndexOf('@')); md = MessageDigest.getInstance("MD5"); md.update(nateon.getPassword().getBytes()); md.update(userid.getBytes()); byte[] bData = md.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bData) { int v = (int) b; v = v < 0 ? v + 0x100 : v; String s = Integer.toHexString(v); if (s.length() == 1) sb.append('0'); sb.append(s); } digest = sb.toString(); } catch (Exception e) { e.printStackTrace(); } NateOnMessage out = new NateOnMessage("LSIN"); out.add(nateon.getUserId()).add(digest).add("MD5").add("3.615"); out.setCallback("processAuth"); writeMessage(out); }
Code Sample 2:
@Override public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("getAudioFileFormat(URL url)"); } InputStream inputStream = url.openStream(); try { return getAudioFileFormat(inputStream); } finally { if (inputStream != null) { inputStream.close(); } } } |
11
| Code Sample 1:
public static String SHA256(String source) { logger.info(source); String result = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(source.getBytes()); byte[] bytes = digest.digest(); result = EncodeUtils.hexEncode(bytes); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } logger.info(result); return result; }
Code Sample 2:
public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hexString.toString(); } |
00
| Code Sample 1:
public SqlScript(URL url, IDbDialect platform, boolean failOnError, String delimiter, Map<String, String> replacementTokens) { try { fileName = url.getFile(); fileName = fileName.substring(fileName.lastIndexOf("/") + 1); log.log(LogLevel.INFO, "Loading sql from script %s", fileName); init(IoUtils.readLines(new InputStreamReader(url.openStream(), "UTF-8")), platform, failOnError, delimiter, replacementTokens); } catch (IOException ex) { log.error(ex); throw new RuntimeException(ex); } }
Code Sample 2:
public static String post(String strUrl, String strPostString) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(true); conn.setAllowUserInteraction(true); conn.setFollowRedirects(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(strPostString); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += s; } in.close(); return sRet; } catch (MalformedURLException e) { System.out.println("Internal Error. Malformed URL."); e.printStackTrace(); } catch (IOException e) { System.out.println("Internal I/O Error."); e.printStackTrace(); } return ""; } |
11
| Code Sample 1:
public boolean updatenum(int num, String pid) { boolean flag = false; Connection conn = null; PreparedStatement pm = null; try { conn = Pool.getConnection(); conn.setAutoCommit(false); pm = conn.prepareStatement("update addwuliao set innum=? where pid=?"); pm.setInt(1, num); pm.setString(2, pid); int a = pm.executeUpdate(); if (a == 0) { flag = false; } else { flag = true; } conn.commit(); Pool.close(pm); Pool.close(conn); } catch (Exception e) { e.printStackTrace(); flag = false; try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } Pool.close(pm); Pool.close(conn); } finally { Pool.close(pm); Pool.close(conn); } return flag; }
Code Sample 2:
public boolean saveNote(NoteData n) { String query; try { conn.setAutoCommit(false); Statement stmt = null; ResultSet rset = null; stmt = conn.createStatement(); query = "select * from notes where noteid = " + n.getID(); rset = stmt.executeQuery(query); if (rset.next()) { query = "UPDATE notes SET title = '" + escapeCharacters(n.getTitle()) + "', keywords = '" + escapeCharacters(n.getKeywords()) + "' WHERE noteid = " + n.getID(); try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; PreparedStatement pstmt = conn.prepareStatement("UPDATE fielddata SET data = ? WHERE noteid = ? AND fieldid = ?"); try { while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(1, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(1, f.getData()); } pstmt.setInt(2, n.getID()); pstmt.setInt(3, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } query = "DELETE FROM links WHERE (note1id = " + n.getID() + " OR note2id = " + n.getID() + ")"; try { stmt.execute(query); } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> associations = n.getAssociations(); ListIterator<Link> itr = associations.listIterator(); Link association = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?, ?)"); try { while (itr.hasNext()) { association = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, association.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } else { query = "INSERT INTO notes (templateid, title, keywords) VALUES (" + n.getTemplate().getID() + ", '" + escapeCharacters(n.getTitle()) + "', '" + escapeCharacters(n.getKeywords()) + "')"; try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; n.setID(Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()"))); PreparedStatement pstmt; try { pstmt = conn.prepareStatement("INSERT INTO fielddata (noteid, fieldid, data) VALUES (?,?,?)"); while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(3, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(3, f.getData()); } pstmt.setInt(1, n.getID()); pstmt.setInt(2, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> assoc = n.getAssociations(); Iterator<Link> itr = assoc.listIterator(); Link l = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?,?)"); try { while (itr.hasNext()) { l = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, l.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } conn.commit(); conn.setAutoCommit(true); } catch (SQLException ex) { ex.printStackTrace(); return false; } return true; } |
11
| Code Sample 1:
private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } }
Code Sample 2:
private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; } |
11
| Code Sample 1:
@SuppressWarnings("static-access") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { filename = URLDecoder.decode(filename, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { is = request.getInputStream(); File newFile = new File(realPath + filename); if (!newFile.exists()) { fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true,detailMsg}"); } else { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false,detailMsg:'文件已经存在!请重命名后上传!'}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + filename + " has existed!"); } } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
Code Sample 2:
public static void copyDirs(File sourceDir, File destDir) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (File file : sourceDir.listFiles()) { if (file.isDirectory()) { copyDirs(file, new File(destDir, file.getName())); } else { FileChannel srcChannel = new FileInputStream(file).getChannel(); File out = new File(destDir, file.getName()); out.createNewFile(); FileChannel dstChannel = new FileOutputStream(out).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } } |
00
| Code Sample 1:
public void go() throws FBConnectionException, FBErrorException, IOException { clearError(); results = new LoginResults(); URL url = new URL(getHost() + getPath()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("X-FB-User", getUser()); conn.setRequestProperty("X-FB-Auth", makeResponse()); conn.setRequestProperty("X-FB-Mode", "Login"); conn.setRequestProperty("X-FB-Login.ClientVersion", agent); conn.connect(); Element fbresponse; try { fbresponse = readXML(conn); } catch (FBConnectionException fbce) { throw fbce; } catch (FBErrorException fbee) { throw fbee; } catch (Exception e) { FBConnectionException fbce = new FBConnectionException("XML parsing failed"); fbce.attachSubException(e); throw fbce; } NodeList nl = fbresponse.getElementsByTagName("LoginResponse"); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element && hasError((Element) nl.item(i))) { error = true; FBErrorException e = new FBErrorException(); e.setErrorCode(errorcode); e.setErrorText(errortext); throw e; } } results.setMessage(DOMUtil.getAllElementText(fbresponse, "Message")); results.setServerTime(DOMUtil.getAllElementText(fbresponse, "ServerTime")); NodeList quotas = fbresponse.getElementsByTagName("Quota"); for (int i = 0; i < quotas.getLength(); i++) { if (quotas.item(i) instanceof Node) { NodeList children = quotas.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (children.item(j) instanceof Element) { Element working = (Element) children.item(j); if (working.getNodeName().equals("Remaining")) { try { results.setQuotaRemaining(Long.parseLong(DOMUtil.getSimpleElementText(working))); } catch (Exception e) { } } if (working.getNodeName().equals("Used")) { try { results.setQuotaUsed(Long.parseLong(DOMUtil.getSimpleElementText(working))); } catch (Exception e) { } } if (working.getNodeName().equals("Total")) { try { results.setQuotaTotal(Long.parseLong(DOMUtil.getSimpleElementText(working))); } catch (Exception e) { } } } } } } results.setRawXML(getLastRawXML()); return; }
Code Sample 2:
public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("�����ļ�ʧ�ܣ�Դ�ļ�" + srcFileName + "������!"); return false; } else if (!srcFile.isFile()) { System.out.println("�����ļ�ʧ�ܣ�" + srcFileName + "����һ���ļ�!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("Ŀ���ļ��Ѵ��ڣ���ɾ��!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("ɾ��Ŀ���ļ�" + descFileName + "ʧ��!"); return false; } } else { System.out.println("�����ļ�ʧ�ܣ�Ŀ���ļ�" + descFileName + "�Ѵ���!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("Ŀ���ļ����ڵ�Ŀ¼�����ڣ�����Ŀ¼!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("����Ŀ���ļ����ڵ�Ŀ¼ʧ��!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("���Ƶ����ļ�" + srcFileName + "��" + descFileName + "�ɹ�!"); return true; } catch (Exception e) { System.out.println("�����ļ�ʧ�ܣ�" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } } |
00
| Code Sample 1:
public void run() { Thread.currentThread().setName("zhongwen.com watcher"); String url = getURL(); try { while (m_shouldBeRunning) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "ISO8859_1")); String line; Vector chatLines = new Vector(); boolean startGrabbing = false; while ((line = reader.readLine()) != null) { if (line.indexOf("</style>") >= 0) { startGrabbing = true; } else if (startGrabbing) { if (line.equals(m_mostRecentKnownLine)) { break; } chatLines.addElement(line); } } reader.close(); for (int i = chatLines.size() - 1; i >= 0; --i) { String chatLine = (String) chatLines.elementAt(i); m_mostRecentKnownLine = chatLine; if (chatLine.indexOf(":") >= 0) { String from = chatLine.substring(0, chatLine.indexOf(":")); String message = stripTags(chatLine.substring(chatLine.indexOf(":"))); m_source.pushMessage(new ZhongWenMessage(m_source, from, message)); } else { m_source.pushMessage(new ZhongWenMessage(m_source, null, stripTags(chatLine))); } } Thread.sleep(SLEEP_TIME); } catch (InterruptedIOException e) { } catch (InterruptedException e) { } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RuntimeException e) { m_source.disconnect(); throw e; } catch (Error e) { m_source.disconnect(); throw e; } }
Code Sample 2:
public void generateHtmlPage(String real_filename, String url_filename) { String str_content = ""; URL m_url = null; URLConnection m_urlcon = null; try { m_url = new URL(url_filename); m_urlcon = m_url.openConnection(); InputStream in_stream = m_urlcon.getInputStream(); byte[] bytes = new byte[1]; Vector v_bytes = new Vector(); while (in_stream.read(bytes) != -1) { v_bytes.add(bytes); bytes = new byte[1]; } byte[] all_bytes = new byte[v_bytes.size()]; for (int i = 0; i < v_bytes.size(); i++) all_bytes[i] = ((byte[]) v_bytes.get(i))[0]; str_content = new String(all_bytes, "GBK"); } catch (Exception urle) { } try { oaFileOperation file_control = new oaFileOperation(); file_control.writeFile(str_content, real_filename, true); String strPath = url_filename.substring(0, url_filename.lastIndexOf("/") + 1); String strUrlFileName = url_filename.substring(url_filename.lastIndexOf("/") + 1); if (strUrlFileName.indexOf(".jsp") > 0) { strUrlFileName = strUrlFileName.substring(0, strUrlFileName.indexOf(".jsp")) + "_1.jsp"; m_url = new URL(strPath + strUrlFileName); m_url.openConnection(); } intWriteFileCount++; intWriteFileCount = (intWriteFileCount > 100000) ? 0 : intWriteFileCount; } catch (Exception e) { } m_urlcon = null; } |
11
| Code Sample 1:
private void updateIngredients(Recipe recipe, int id) throws Exception { PreparedStatement pst1 = null; PreparedStatement pst2 = null; try { conn = getConnection(); pst1 = conn.prepareStatement("DELETE FROM ingredients WHERE recipe_id = ?"); pst1.setInt(1, id); if (pst1.executeUpdate() >= 0) { pst2 = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)"); IngredientContainer ings = recipe.getIngredients(); Ingredient ingBean = null; Iterator it; for (it = ings.getIngredients().iterator(); it.hasNext(); ) { ingBean = (Ingredient) it.next(); pst2.setInt(1, id); pst2.setString(2, ingBean.getName()); pst2.setDouble(3, ingBean.getAmount()); pst2.setInt(4, ingBean.getType()); pst2.setInt(5, ingBean.getShopFlag()); pst2.executeUpdate(); } } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage()); } finally { try { if (pst1 != null) pst1.close(); pst1 = null; if (pst2 != null) pst2.close(); pst2 = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } }
Code Sample 2:
public boolean save(Object obj) { boolean bool = false; this.result = null; if (obj == null) return bool; Connection conn = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); String sql = SqlUtil.getInsertSql(this.getCls()); PreparedStatement ps = conn.prepareStatement(sql); setPsParams(ps, obj); ps.executeUpdate(); ps.close(); conn.commit(); bool = true; } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { } this.result = e.getMessage(); } finally { this.closeConnectWithTransaction(conn); } return bool; } |
00
| Code Sample 1:
private void update() throws IOException { FileOutputStream out = new FileOutputStream(combined); try { File[] _files = listJavascript(); List<File> files = new ArrayList<File>(Arrays.asList(_files)); files.add(0, new File(jsdir.getAbsolutePath() + "/leemba.js")); files.add(0, new File(jsdir.getAbsolutePath() + "/jquery.min.js")); for (File js : files) { FileInputStream fin = null; try { int count = 0; byte buf[] = new byte[16384]; fin = new FileInputStream(js); while ((count = fin.read(buf)) > 0) out.write(buf, 0, count); } catch (Throwable t) { log.error("Failed to read file: " + js.getAbsolutePath(), t); } finally { if (fin != null) fin.close(); } } } finally { out.close(); } }
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) { } } } } |
00
| Code Sample 1:
public static void unzip(String destDir, String zipPath) { PrintWriter stdout = new PrintWriter(System.out, true); int read = 0; byte[] data = new byte[1024]; ZipEntry entry; try { ZipInputStream in = new ZipInputStream(new FileInputStream(zipPath)); stdout.println(zipPath); while ((entry = in.getNextEntry()) != null) { if (entry.getMethod() == ZipEntry.DEFLATED) { stdout.println(" Inflating: " + entry.getName()); } else { stdout.println(" Extracting: " + entry.getName()); } FileOutputStream out = new FileOutputStream(destDir + File.separator + entry.getName()); while ((read = in.read(data, 0, 1024)) != -1) { out.write(data, 0, read); } out.close(); } in.close(); stdout.println(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private void downloadDirectory() throws SocketException, IOException { FTPClient client = new FTPClient(); client.connect(source.getHost()); client.login(username, password); FTPFile[] files = client.listFiles(source.getPath()); for (FTPFile file : files) { if (!file.isDirectory()) { long file_size = file.getSize() / 1024; Calendar cal = file.getTimestamp(); URL source_file = new File(source + file.getName()).toURI().toURL(); DownloadQueue.add(new Download(projectName, parser.getParserID(), source_file, file_size, cal, target + file.getName())); } } } |
11
| Code Sample 1:
public static void fileCopy(String src, String dst) { try { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst); int read = -1; byte[] buf = new byte[8192]; while ((read = fis.read(buf)) != -1) { fos.write(buf, 0, read); } fos.flush(); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void jsFunction_extract(ScriptableFile outputFile) throws IOException, FileSystemException, ArchiveException { InputStream is = file.jsFunction_createInputStream(); OutputStream output = outputFile.jsFunction_createOutputStream(); BufferedInputStream buf = new BufferedInputStream(is); ArchiveInputStream input = ScriptableZipArchive.getFactory().createArchiveInputStream(buf); try { long count = 0; while (input.getNextEntry() != null) { if (count == offset) { IOUtils.copy(input, output); break; } count++; } } finally { input.close(); output.close(); is.close(); } } |
11
| Code Sample 1:
String extractTiffFile(String path) throws IOException { ZipInputStream in = new ZipInputStream(new FileInputStream(path)); OutputStream out = new FileOutputStream(dir + TEMP_NAME); byte[] buf = new byte[1024]; int len; ZipEntry entry = in.getNextEntry(); if (entry == null) return null; String name = entry.getName(); if (!name.endsWith(".tif")) throw new IOException("This ZIP archive does not appear to contain a TIFF file"); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); return name; }
Code Sample 2:
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) { } } catch (FileNotFoundException e) { } } |
11
| Code Sample 1:
public static Object deployNewService(String scNodeRmiName, String userName, String password, String name, String jarName, String serviceClass, String serviceInterface, Logger log) throws RemoteException, MalformedURLException, StartServiceException, NotBoundException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, SessionException { try { SCNodeInterface node = (SCNodeInterface) Naming.lookup(scNodeRmiName); String session = node.login(userName, password); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(new FileInputStream(jarName), baos); ServiceAdapterIfc adapter = node.deploy(session, name, baos.toByteArray(), jarName, serviceClass, serviceInterface); if (adapter != null) { return new ExternalDomain(node, adapter, adapter.getUri(), log).getProxy(Thread.currentThread().getContextClassLoader()); } } catch (Exception e) { log.warn("Could not send deploy command: " + e.getMessage(), e); } return null; }
Code Sample 2:
@Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException, NotFoundException { try { resolveFileAttachment(); } catch (NoFileByTheIdException e) { throw new NotFoundException(e.getLocalizedMessage()); } DefinableEntity owningEntity = fa.getOwner().getEntity(); InputStream in = getFileModule().readFile(owningEntity.getParentBinder(), owningEntity, fa); try { if (range != null) { if (logger.isDebugEnabled()) logger.debug("sendContent: ranged content: " + toString(fa)); PartialGetHelper.writeRange(in, range, out); } else { if (logger.isDebugEnabled()) logger.debug("sendContent: send whole file " + toString(fa)); IOUtils.copy(in, out); } out.flush(); } catch (ReadingException e) { throw new IOException(e); } catch (WritingException e) { throw new IOException(e); } finally { IOUtils.closeQuietly(in); } } |
11
| Code Sample 1:
private void putAlgosFromJar(File jarfile, AlgoDir dir, Model model) throws FileNotFoundException, IOException { URLClassLoader urlLoader = new URLClassLoader(new URL[] { jarfile.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(jarfile)); JarEntry entry = jis.getNextJarEntry(); String name = null; String tmpdir = System.getProperty("user.dir") + File.separator + Application.getProperty("dir.tmp") + File.separator; byte[] buffer = new byte[1000]; while (entry != null) { name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); try { Class<?> cls = urlLoader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && ((cls.getModifiers() & Modifier.ABSTRACT) == 0)) { dir.addAlgorithm(cls); model.putClass(cls.getName(), cls); } else if (ISerializable.class.isAssignableFrom(cls)) { model.putClass(cls.getName(), cls); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else if (Constants.isAllowedImageType(name)) { int lastSep = name.lastIndexOf("/"); if (lastSep != -1) { String dirs = tmpdir + name.substring(0, lastSep); File d = new File(dirs); if (!d.exists()) d.mkdirs(); } String filename = tmpdir + name; File f = new File(filename); if (!f.exists()) { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); int read = -1; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.close(); } } entry = jis.getNextJarEntry(); } }
Code Sample 2:
public void doImport(File f, boolean checkHosp) throws Exception { connector.getConnection().setAutoCommit(false); File base = f.getParentFile(); ZipInputStream in = new ZipInputStream(new FileInputStream(f)); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { String outFileName = entry.getName(); File outFile = new File(base, outFileName); OutputStream out = new FileOutputStream(outFile, false); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); } in.close(); importDirectory(base, checkHosp); connector.getConnection().commit(); } |
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:
private static void copy(File source, File target) throws IOException { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(source)); os = new BufferedOutputStream(new FileOutputStream(target)); int b; while ((b = is.read()) > -1) os.write(b); } finally { try { if (is != null) is.close(); } catch (IOException ignore) { } try { if (os != null) os.close(); } catch (IOException ignore) { } } } |
00
| Code Sample 1:
private static void ftpTest() { FTPClient f = new FTPClient(); try { f.connect("oscomak.net"); System.out.print(f.getReplyString()); f.setFileType(FTPClient.BINARY_FILE_TYPE); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String password = JOptionPane.showInputDialog("Enter password"); if (password == null || password.equals("")) { System.out.println("No password"); return; } try { f.login("oscomak_pointrel", password); System.out.print(f.getReplyString()); } catch (IOException e) { e.printStackTrace(); } try { String workingDirectory = f.printWorkingDirectory(); System.out.println("Working directory: " + workingDirectory); System.out.print(f.getReplyString()); } catch (IOException e1) { e1.printStackTrace(); } try { f.enterLocalPassiveMode(); System.out.print(f.getReplyString()); System.out.println("Trying to list files"); String[] fileNames = f.listNames(); System.out.print(f.getReplyString()); System.out.println("Got file list fileNames: " + fileNames.length); for (String fileName : fileNames) { System.out.println("File: " + fileName); } System.out.println(); System.out.println("done reading stream"); System.out.println("trying alterative way to read stream"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); f.retrieveFile(fileNames[0], outputStream); System.out.println("size: " + outputStream.size()); System.out.println(outputStream.toString()); System.out.println("done with alternative"); System.out.println("Trying to store file back"); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); boolean storeResult = f.storeFile("test.txt", inputStream); System.out.println("Done storing " + storeResult); f.disconnect(); System.out.print(f.getReplyString()); System.out.println("disconnected"); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public HttpURLHandler(URL url, String requestMethod, Map<String, String> parameters, String outputEncoding) throws IOException { logger.debug("Creating http url handler for: " + url + "; using method: " + requestMethod + "; with parameters: " + parameters); if (url == null) throw new IllegalArgumentException("Null pointer in url"); if (!"http".equals(url.getProtocol()) && !"https".equals(url.getProtocol())) throw new IllegalArgumentException("Illegal url protocol: \"" + url.getProtocol() + "\"; must be \"http\" or \"https\""); if (requestMethod == null) throw new IllegalArgumentException("Null pointer in requestMethod"); if (!"GET".equals(requestMethod) && !"POST".equals(requestMethod)) throw new IllegalArgumentException("Illegal request method: " + requestMethod + "; must be \"GET\" or \"POST\""); if (parameters == null) throw new IllegalArgumentException("Null pointer in parameters"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy); connection.setRequestMethod(requestMethod); connection.setUseCaches(false); if (EMPTY_MAP.equals(parameters)) { connection.setDoOutput(false); } else { connection.setDoOutput(true); OutputStream out = connection.getOutputStream(); writeParameters(out, parameters, outputEncoding); out.close(); } inputStream = connection.getInputStream(); } |
11
| Code Sample 1:
protected void copyFile(File src, File dest) throws Exception { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); long transferred = destChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (transferred != srcChannel.size()) throw new Exception("Could not transfer entire file"); srcChannel.close(); destChannel.close(); }
Code Sample 2:
private String copyTutorial() throws IOException { File inputFile = new File(getFilenameForOriginalTutorial()); File outputFile = new File(getFilenameForCopiedTutorial()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return getFilenameForCopiedTutorial(); } |
11
| Code Sample 1:
private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
00
| Code Sample 1:
protected IRunnableWithProgress getProjectCreationRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int remainingWorkUnits = 10; monitor.beginTask("New Modulo Project Creation", remainingWorkUnits); IWorkspace ws = ResourcesPlugin.getWorkspace(); newProject = fMainPage.getProjectHandle(); IProjectDescription description = ws.newProjectDescription(newProject.getName()); String[] natures = { JavaCore.NATURE_ID, ModuloLauncherPlugin.NATURE_ID }; description.setNatureIds(natures); ICommand command = description.newCommand(); command.setBuilderName(JavaCore.BUILDER_ID); ICommand[] commands = { command }; description.setBuildSpec(commands); IJavaProject jproject = JavaCore.create(newProject); ModuloProject modProj = new ModuloProject(); modProj.setJavaProject(jproject); try { newProject.create(description, new SubProgressMonitor(monitor, 1)); newProject.open(new SubProgressMonitor(monitor, 1)); IFolder srcFolder = newProject.getFolder("src"); IFolder javaFolder = srcFolder.getFolder("java"); IFolder buildFolder = newProject.getFolder("build"); IFolder classesFolder = buildFolder.getFolder("classes"); modProj.createFolder(srcFolder); modProj.createFolder(javaFolder); modProj.createFolder(buildFolder); modProj.createFolder(classesFolder); IPath buildPath = newProject.getFolder("build/classes").getFullPath(); jproject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 1)); IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(newProject.getFolder("src/java").getFullPath()), JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER)), JavaCore.newContainerEntry(new Path(ModuloClasspathContainer.CONTAINER_ID)) }; jproject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1)); ModuleDefinition definition = new ModuleDefinition(); definition.setId(fModuloPage.getPackageName()); definition.setVersion(new VersionNumber(1, 0, 0)); definition.setMetaName(fModuloPage.getModuleName()); definition.setMetaDescription("The " + fModuloPage.getModuleName() + " Module."); definition.setModuleClassName(fModuloPage.getPackageName() + "." + fModuloPage.getModuleClassName()); if (fModuloPage.isConfigSelectioned()) definition.setConfigurationClassName(fModuloPage.getPackageName() + "." + fModuloPage.getConfigClassName()); if (fModuloPage.isStatSelectioned()) definition.setStatisticsClassName(fModuloPage.getPackageName() + "." + fModuloPage.getStatClassName()); modProj.setDefinition(definition); modProj.createPackage(); modProj.createModuleXML(); modProj.createMainClass(); if (fModuloPage.isConfigSelectioned()) modProj.createConfigClass(); if (fModuloPage.isStatSelectioned()) modProj.createStatClass(); modProj.createModuleProperties(); modProj.createMessagesProperties(); IFolder binFolder = newProject.getFolder("bin"); binFolder.delete(true, new SubProgressMonitor(monitor, 1)); } catch (CoreException e) { e.printStackTrace(); } finally { monitor.done(); } } }; }
Code Sample 2:
public static final synchronized String md5(final String data) { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(data.getBytes()); final byte[] b = md.digest(); return toHexString(b); } catch (final Exception e) { } return ""; } |
11
| Code Sample 1:
private void preprocessObjects(GeoObject[] objects) throws IOException { System.out.println("objects.length " + objects.length); for (int i = 0; i < objects.length; i++) { String fileName = objects[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("i: " + " world filename " + tmp); File worldFile = new File(tmp); if (worldFile.exists()) { BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); } } File file = new File(objects[i].getPath()); if (file.exists()) { System.out.println("object src file found "); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); objects[i].setPath(tmp); file = new File(fileName); if (file.exists()) { DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } } } }
Code Sample 2:
public void run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); String[] parts = header.getFilename().getSegments(); String filename; if (parts.length > 0) filename = "dl-" + parts[parts.length - 1]; else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } } |
11
| Code Sample 1:
public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) { h = "0" + h; } hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
Code Sample 2:
private static String getVisitorId(String guid, String account, String userAgent, Cookie cookie) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (cookie != null && cookie.getValue() != null) { return cookie.getValue(); } String message; if (!isEmpty(guid)) { message = guid + account; } else { message = userAgent + getRandomNumber() + UUID.randomUUID().toString(); } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(message.getBytes("UTF-8"), 0, message.length()); byte[] sum = m.digest(); BigInteger messageAsNumber = new BigInteger(1, sum); String md5String = messageAsNumber.toString(16); while (md5String.length() < 32) { md5String = "0" + md5String; } return "0x" + md5String.substring(0, 16); } |
11
| Code Sample 1:
public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } }
Code Sample 2:
protected InputStream createIconType(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { JavaliController.debug(JavaliController.LG_VERBOSE, "Creating iconType"); String cHash = PRM_TYPE + "=" + TP_ICON; String iconName = req.getParameter("iconName"); if (iconName == null) { res.sendError(res.SC_NOT_FOUND); return null; } Locale loc = null; HttpSession sess = req.getSession(false); JavaliSession jsess = null; int menuType = -1; String menuTypeString = req.getParameter(PRM_MENU_TYPE); try { menuType = new Integer(menuTypeString).intValue(); } catch (Exception e) { } if (sess != null) jsess = (JavaliSession) sess.getAttribute(FormConstants.SESSION_BINDING); if (jsess != null && jsess.getUser() != null) loc = jsess.getUser().getLocale(); else if (sess != null) loc = (Locale) sess.getAttribute(FormConstants.LOCALE_BINDING); if (loc == null) loc = Locale.getDefault(); if (menuType == -1) menuType = MENU_TYPE_TEXTICON; String iconText = JavaliResource.getString("icon." + iconName, loc); if (iconText == null) { iconText = req.getParameter(PRM_MENU_NAME); if (iconText == null) iconText = ""; } cHash += ", " + PRM_ICON_NAME + "=" + iconName + ", text=" + iconText + ", menuType=" + menuType; String iconFileName = null; String fontName = req.getParameter(PRM_FONT_NAME); if (fontName == null) { fontName = "Helvetica"; } cHash += "," + PRM_FONT_NAME + "=" + fontName; String fontSizeString = req.getParameter(PRM_FONT_SIZE); int fontSize; try { fontSize = Integer.parseInt(fontSizeString); } catch (NumberFormatException nfe) { fontSize = 12; } cHash += "," + PRM_FONT_SIZE + "=" + fontSize; String fontTypeString = req.getParameter(PRM_FONT_TYPE); int fontType = Font.BOLD; if ("PLAIN".equalsIgnoreCase(fontTypeString)) fontType = Font.PLAIN; if ("BOLD".equalsIgnoreCase(fontTypeString)) fontType = Font.BOLD; if ("ITALIC".equalsIgnoreCase(fontTypeString)) fontType = Font.ITALIC; if ("ITALICBOLD".equalsIgnoreCase(fontTypeString) || "BOLDITALIC".equalsIgnoreCase(fontTypeString) || "BOLD_ITALIC".equalsIgnoreCase(fontTypeString) || "ITALIC_BOLD".equalsIgnoreCase(fontTypeString)) { fontType = Font.ITALIC | Font.BOLD; } cHash += "," + PRM_FONT_TYPE + "=" + fontType; String fontColor = req.getParameter(PRM_FONT_COLOR); if (fontColor == null || fontColor.equals("")) fontColor = "0x000000"; cHash += "," + PRM_FONT_COLOR + "=" + fontColor; String fName = cacheInfo.file(cHash); JavaliController.debug(JavaliController.LG_VERBOSE, "Called for: " + fName); if (fName == null) { JavaliController.debug(JavaliController.LG_VERBOSE, "No cache found for: " + cHash); if (getServletConfig() != null && getServletConfig().getServletContext() != null) { if (iconName != null && iconName.startsWith("/")) iconFileName = getServletConfig().getServletContext().getRealPath(iconName + ".gif"); else iconFileName = getServletConfig().getServletContext().getRealPath("/icons/" + iconName + ".gif"); File iconFile = new File(iconFileName); if (!iconFile.exists()) { JavaliController.debug(JavaliController.LG_VERBOSE, "Could not find: " + iconFileName); res.sendError(res.SC_NOT_FOUND); return null; } iconFileName = iconFile.getAbsolutePath(); JavaliController.debug(JavaliController.LG_VERBOSE, "file: " + iconFileName + " and cHash=" + cHash); } else { JavaliController.debug(JavaliController.LG_VERBOSE, "No ServletConfig=" + getServletConfig() + " or servletContext"); res.sendError(res.SC_NOT_FOUND); return null; } File tmp = File.createTempFile(PREFIX, SUFIX, cacheDir); OutputStream out = new FileOutputStream(tmp); if (menuType == MENU_TYPE_ICON) { FileInputStream in = new FileInputStream(iconFileName); byte buf[] = new byte[2048]; int read = -1; while ((read = in.read(buf)) != -1) out.write(buf, 0, read); } else if (menuType == MENU_TYPE_TEXT) MessageImage.sendAsGIF(MessageImage.makeMessageImage(iconText, fontName, fontSize, fontType, fontColor, false, "0x000000", true), out); else MessageImage.sendAsGIF(MessageImage.makeIconImage(iconFileName, iconText, fontName, fontColor, fontSize, fontType), out); out.close(); cacheInfo.putFile(cHash, tmp); fName = cacheInfo.file(cHash); } return new FileInputStream(new File(cacheDir, fName)); } |
00
| Code Sample 1:
public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } |
00
| Code Sample 1:
public static File copyFile(File from, File to) throws IOException { FileOutputStream fos = new FileOutputStream(to); FileInputStream fis = new FileInputStream(from); FileChannel foc = fos.getChannel(); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return to; }
Code Sample 2:
private void sendActionPerformed(java.awt.event.ActionEvent evt) { if (name.getText().length() < 3) { JOptionPane.showMessageDialog(comment, "Too short name (at least 3)"); return; } if (comment.getText().length() < 10) { JOptionPane.showMessageDialog(comment, "Too short comment (at least 10)"); return; } Thread t = new Thread(new Runnable() { public void run() { try { String data = URLEncoder.encode("send_id", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8"); data += "&" + URLEncoder.encode("author", "UTF-8") + "=" + URLEncoder.encode(name.getText(), "UTF-8"); data += "&" + URLEncoder.encode("location", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("user.language"), "UTF-8"); data += "&" + URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(email.getText(), "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(comment.getText(), "UTF-8"); data += "&" + URLEncoder.encode("rate", "UTF-8") + "=" + URLEncoder.encode(rate.getSelectedItem().toString(), "UTF-8"); System.out.println(data); URL url = new URL("http://javablock.sourceforge.net/book/index.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String address = rd.readLine(); JPanel panel = new JPanel(); panel.add(new JLabel("Comment added")); panel.add(new JTextArea("visit: http://javablock.sourceforge.net/")); JOptionPane.showMessageDialog(null, new JLabel("Comment sended correctly!")); wr.close(); rd.close(); hide(); } catch (IOException ex) { Logger.getLogger(guestBook.class.getName()).log(Level.SEVERE, null, ex); } } }); t.start(); } |
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 void logout(String cookieString) throws NetworkException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_LOGOUT); if (cookieString != null && cookieString.length() != 0) get.setHeader("Cookie", cookieString); try { HttpResponse response = client.execute(get); if (response != null && response.getEntity() != null) { HTTPUtil.consume(response.getEntity()); } } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } } |
11
| Code Sample 1:
public static String EncryptString(String method, String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); if (method.equals("SHA1") || method.equals("MD5")) { try { md = MessageDigest.getInstance(method); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); return null; } } else { return null; } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { String tmp = Integer.toHexString(0xff & byteHash[i]); if (tmp.length() < 2) tmp = "0" + tmp; resultString.append(tmp); } return (resultString.toString()); }
Code Sample 2:
public static String md5(String text) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(text.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] bytes = msgDigest.digest(); String md5Str = new String(encodeHex(bytes)); return md5Str; } |
00
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static HttpURLConnection getHttpConn(String urlStr, String Method) throws IOException { URL url = null; HttpURLConnection connection = null; url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod(Method); connection.setUseCaches(false); connection.connect(); return connection; } |
00
| Code Sample 1:
public static void main(String[] args) { FileInputStream fr = null; FileOutputStream fw = null; BufferedInputStream br = null; BufferedOutputStream bw = null; try { fr = new FileInputStream("D:/5.xls"); fw = new FileOutputStream("c:/Dxw.java"); br = new BufferedInputStream(fr); bw = new BufferedOutputStream(fw); int read = br.read(); while (read != -1) { bw.write(read); read = br.read(); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Code Sample 2:
private void download(String address, String localFileName, String host, int porta) { InputStream in = null; URLConnection conn = null; OutputStream out = null; System.out.println("Update.download() BAIXANDO " + address); try { URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); if (host != "" && host != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, porta)); conn = url.openConnection(proxy); } else { conn = url.openConnection(); } in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } System.out.println(localFileName + "\t" + numWritten); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } } |
00
| Code Sample 1:
public static byte[] encrypt(String string) { java.security.MessageDigest messageDigest = null; try { messageDigest = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException exc) { logger.fatal(exc); throw new RuntimeException(); } messageDigest.reset(); messageDigest.update(string.getBytes()); return messageDigest.digest(); }
Code Sample 2:
public static void copyFile(File src, File dst) { try { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst); try { byte[] buf = new byte[1024]; int i = 0; while ((i = fis.read(buf)) != -1) fos.write(buf, 0, i); } catch (IOException e) { throw e; } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } } catch (IOException e) { logger.error("Error coping file from " + src + " to " + dst, e); } } |
00
| Code Sample 1:
public static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); InputStream is = CheckAvailability.class.getResourceAsStream("/isbns.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String isbn = null; HttpGet get = null; while ((isbn = br.readLine().split(" ")[0]) != null) { System.out.println("Target url: \n\t" + String.format(isbnSearchUrl, isbn)); get = new HttpGet(String.format(isbnSearchUrl, isbn)); HttpResponse resp = httpclient.execute(get); Scanner s = new Scanner(resp.getEntity().getContent()); String pattern = s.findWithinHorizon("((\\d*) hold[s]? on first copy returned of (\\d*) )?[cC]opies", 0); if (pattern != null) { MatchResult match = s.match(); if (match.groupCount() == 3) { if (match.group(2) == null) { System.out.println(isbn + ": copies available"); } else { System.out.println(isbn + ": " + match.group(2) + " holds on " + match.group(3) + " copies"); } } } else { System.out.println(isbn + ": no match"); } get.abort(); } }
Code Sample 2:
private static void copy(File source, File target) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); } |
11
| Code Sample 1:
private boolean copyFile(BackupItem item) { try { FileChannel src = new FileInputStream(item.getDrive() + ":" + item.getPath()).getChannel(); createFolderStructure(this.task.getDestinationPath() + "\\" + item.getDrive() + item.getPath()); FileChannel dest = new FileOutputStream(this.task.getDestinationPath() + "\\" + item.getDrive() + item.getPath()).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); Logging.logMessage("file " + item.getDrive() + ":" + item.getPath() + " was backuped"); return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
Code Sample 2:
void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } |
11
| Code Sample 1:
private void initLogging() { File logging = new File(App.getHome(), "logging.properties"); if (!logging.exists()) { InputStream input = getClass().getResourceAsStream("logging.properties-setup"); OutputStream output = null; try { output = new FileOutputStream(logging); IOUtils.copy(input, output); } catch (Exception ex) { } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } FileInputStream input = null; try { input = new FileInputStream(logging); LogManager.getLogManager().readConfiguration(input); } catch (Exception ex) { } finally { IOUtils.closeQuietly(input); } }
Code Sample 2:
public static File copyToLibDirectory(final File file) throws FileNotFoundException, IOException { if (file == null || !file.exists()) { throw new FileNotFoundException(); } File directory = new File("lib/"); File dest = new File(directory, file.getName()); File parent = dest.getParentFile(); while (parent != null && !parent.equals(directory)) { parent = parent.getParentFile(); } if (parent.equals(directory)) { return file; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return dest; } |
11
| Code Sample 1:
public boolean backupLastAuditSchema(File lastAuditSchema) { boolean isBkupFileOK = false; String writeTimestamp = DateFormatUtils.format(new java.util.Date(), configFile.getTimestampPattern()); File target = new File(configFile.getAuditSchemaFileDir() + File.separator + configFile.getAuditSchemaFileName() + ".bkup_" + writeTimestamp); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(lastAuditSchema).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { if ((target != null) && (target.exists()) && (target.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.warning("closing channels failed"); } } return isBkupFileOK; }
Code Sample 2:
public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); } |
11
| Code Sample 1:
public void encryptPassword() { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.out.print(e); } try { digest.update(passwordIn.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.out.println("cannot find char set for getBytes"); } byte digestBytes[] = digest.digest(); passwordHash = (new BASE64Encoder()).encode(digestBytes); }
Code Sample 2:
public static String MD5(byte[] data) throws NoSuchAlgorithmException, UnsupportedEncodingException { String text = convertToHex(data); MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } |
00
| Code Sample 1:
public void testSendMessage() throws ClientProtocolException, IOException { String textMessage = "La%20sua%20prenotazione%20e60%20andata%20a%20buon%20fine"; String customerPhoneNumber = "+393345730726"; DefaultHttpClient httpclient = new DefaultHttpClient(); String other = "http://smswizard.globalitalia.it/smsgateway/send.asp"; String urlProva = other + "?" + "Account=sardricerche" + "&Password=v8LomdZT" + "&PhoneNumbers=+393345730726" + "&SMSData=" + textMessage + "&Recipients=1" + "&Sender=+393337589951" + "&ID=11762"; HttpPost httpPost = new HttpPost(urlProva); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); String txt = EntityUtils.toString(entity); }
Code Sample 2:
void readData() { String[] nextLine; int line; double value; URL url = null; String FileToRead; try { for (int i = 0; i < names.length; i++) { FileToRead = "data/" + names[i] + ".csv"; url = new URL(ja.getCodeBase(), FileToRead); System.out.println(url.toString()); InputStream in = url.openStream(); CSVReader reader = new CSVReader(new InputStreamReader(in)); line = 0; while ((nextLine = reader.readNext()) != null) { allset.months[line] = Integer.parseInt(nextLine[0].substring(0, 2)); allset.years[line] = Integer.parseInt(nextLine[0].substring(6, 10)); value = Double.parseDouble(nextLine[1]); allset.values.getDataRef()[line][i] = value; line++; } } } catch (IOException e) { System.err.println("File Read Exception"); } } |
00
| Code Sample 1:
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); TextView tv = new TextView(this); try { URL url = new URL(""); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); ExampleHandler myExampleHandler = new ExampleHandler(); xr.setContentHandler(myExampleHandler); xr.parse(new InputSource(url.openStream())); ParsedExampleDataSet parsedExampleDataSet = myExampleHandler.getParsedData(); tv.setText(parsedExampleDataSet.toString()); } catch (Exception e) { tv.setText("Error: " + e.getMessage()); Log.e(MY_DEBUG_TAG, "WeatherQueryError", e); } this.setContentView(tv); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
11
| Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); } |
11
| Code Sample 1:
public File copyFile(File f) throws IOException { File t = createNewFile("fm", "cpy"); FileOutputStream fos = new FileOutputStream(t); FileChannel foc = fos.getChannel(); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return t; }
Code Sample 2:
public void xtest11() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/UML2.pdf"); InputStream page1 = manager.cut(pdf, 1, 1); OutputStream outputStream = new FileOutputStream("/tmp/page.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); } |
00
| Code Sample 1:
public void readData() throws IOException { i = 0; j = 0; URL url = getClass().getResource("resources/Chrom_623_620.dat"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); s = br.readLine(); st = new StringTokenizer(s); chrom_x[i][j] = Double.parseDouble(st.nextToken()); temp_prev = chrom_x[i][j]; chrom_y[i][j] = Double.parseDouble(st.nextToken()); gridmin = chrom_x[i][j]; gridmax = chrom_x[i][j]; sext1[i][j] = Double.parseDouble(st.nextToken()); sext2[i][j] = Double.parseDouble(st.nextToken()); sext3[i][j] = Double.parseDouble(st.nextToken()); sext4[i][j] = Double.parseDouble(st.nextToken()); j++; 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; } chrom_x[i][j] = temp_new; chrom_y[i][j] = Double.parseDouble(st.nextToken()); sext1[i][j] = Double.parseDouble(st.nextToken()); sext2[i][j] = Double.parseDouble(st.nextToken()); sext3[i][j] = Double.parseDouble(st.nextToken()); sext4[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; if (chrom_x[i][j] <= gridmin) gridmin = chrom_x[i][j]; if (chrom_x[i][j] >= gridmax) gridmax = chrom_x[i][j]; } }
Code Sample 2:
private void gerarComissao() { int opt = Funcoes.mensagemConfirma(null, "Confirma gerar comiss�es para o vendedor " + txtNomeVend.getVlrString().trim() + "?"); if (opt == JOptionPane.OK_OPTION) { StringBuilder insert = new StringBuilder(); insert.append("INSERT INTO RPCOMISSAO "); insert.append("(CODEMP, CODFILIAL, CODPED, CODITPED, "); insert.append("CODEMPVD, CODFILIALVD, CODVEND, VLRCOMISS ) "); insert.append("VALUES "); insert.append("(?,?,?,?,?,?,?,?)"); PreparedStatement ps; int parameterIndex; boolean gerou = false; try { for (int i = 0; i < tab.getNumLinhas(); i++) { if (((BigDecimal) tab.getValor(i, 8)).floatValue() > 0) { parameterIndex = 1; ps = con.prepareStatement(insert.toString()); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPCOMISSAO")); ps.setInt(parameterIndex++, txtCodPed.getVlrInteger()); ps.setInt(parameterIndex++, (Integer) tab.getValor(i, ETabNota.ITEM.ordinal())); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPVENDEDOR")); ps.setInt(parameterIndex++, txtCodVend.getVlrInteger()); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRCOMIS.ordinal())); ps.executeUpdate(); gerou = true; } } if (gerou) { Funcoes.mensagemInforma(null, "Comiss�o gerada para " + txtNomeVend.getVlrString().trim()); txtCodPed.setText("0"); lcPedido.carregaDados(); carregaTabela(); con.commit(); } else { Funcoes.mensagemInforma(null, "N�o foi possiv�l gerar comiss�o!\nVerifique os valores das comiss�es dos itens."); } } catch (Exception e) { e.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao gerar comiss�o!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } } |
00
| Code Sample 1:
public String ask(String s) { System.out.println("asking ---> " + s); try { String result = null; URL url = new URL("http://www.google.com/search?hl=en&rls=GGLR,GGLR:2005-50,GGLR:en&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=" + URLEncoder.encode(s, "UTF-8")); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(false); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String inputLine; while ((inputLine = in.readLine()) != null) { int textPos = inputLine.indexOf("Web definitions for "); if (textPos >= 0) { int ltrPos = inputLine.indexOf("<font size=-1>", textPos + 18); if (ltrPos >= 0) { int closePos = inputLine.indexOf("<", ltrPos + 14); if (closePos >= 0) { result = inputLine.substring(ltrPos + 14, closePos); } } } else { int ltrPos = inputLine.indexOf("— Location: "); if (ltrPos >= 0) { int closePos = inputLine.indexOf("<br", ltrPos + 18); if (closePos >= 0) { result = inputLine.substring(ltrPos + 18, closePos); } } } } in.close(); if (result != null) { result = result.replaceAll("<b>", ""); result = result.replaceAll("</b>", ""); result = result.replaceAll("("|')", "'"); System.out.println("result ---> " + result); } else { System.out.println("result ---> none!"); String ss = s.toUpperCase(); if (ss.startsWith("WHAT IS ")) { String toSearch = ss.substring(8).trim(); try { String str = getResultStr("http://www.google.com/search?hl=en&q=define%3A" + toSearch); str = cutAfter(str, "on the Web"); str = cutAfter(str, "<li>"); str = getBefore(str, "<br>"); result = str.replaceAll("\n", ""); } catch (Exception ee) { } } } return result; } catch (Exception e) { e.printStackTrace(); } return null; }
Code Sample 2:
public void launch(String xmlControl, String xmlDoc, long docId) { AgentLauncher l; Environment env; Properties prop; Resource res; String token; String deflt; String answ; String key; String entry; ShipService service; de.fhg.igd.util.URL url; java.net.URL wsurl; NodeList flow; InputSource xmlcontrolstream; TreeMap results; synchronized (lock_) { if (xmlControl == null || xmlControl.length() == 0 || xmlDoc == null || xmlDoc.length() == 0) { System.out.println("---- Need control AND XML document! ----"); return; } Vector v_delegations_host = new Vector(); Vector v_delegations_url = new Vector(); Vector v_delegations_method = new Vector(); xmlcontrolstream = new InputSource(new StringReader(xmlControl)); NodeList destinations = SimpleXMLParser.parseDocument(xmlcontrolstream, AgentBehaviour.XML_DELEGATE); for (int i = 0; i < destinations.getLength(); i++) { if (destinations.item(i).getTextContent() != null && destinations.item(i).getTextContent().length() > 0) { System.out.println(destinations.item(i).getTextContent()); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_HOST); v_delegations_host.add(entry); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_URL); v_delegations_url.add(entry); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_METHOD); v_delegations_method.add(entry); } } token = ""; results = new TreeMap(); for (int i = 0; i < TOKEN_LENGTH; i++) { token = token + (char) (Math.random() * 26 + 65); } results.put(token, null); prop = AgentStructure.defaults(); prop.setProperty(AgentStructure.PROP_AGENT_CLASS, AGENT_); prop.setProperty(AgentBehaviour.CTX_DOCID, String.valueOf(docId)); prop.setProperty(AgentBehaviour.CTX_XML, xmlDoc); prop.setProperty("token", token); deflt = prop.getProperty(AgentStructure.PROP_AGENT_EXCLUDE); prop.setProperty(AgentStructure.PROP_AGENT_EXCLUDE, deflt + ":" + ADDITIONAL_EXCLUDES); service = (ShipService) getEnvironment().lookup(WhatIs.stringValue(ShipService.WHATIS)); for (int i = 0; i < v_delegations_host.size(); i++) { System.out.println("\n-----SCANNING DELEGATES-----"); System.out.println("\n-----DELEGATE " + i + "-----"); System.out.println("-----HOST: " + i + ": " + (String) v_delegations_host.elementAt(i)); System.out.println("-----URL: " + i + ": " + (String) v_delegations_url.elementAt(i)); System.out.println("-----METHOD: " + i + ": " + (String) v_delegations_method.elementAt(i)); try { url = new de.fhg.igd.util.URL((String) v_delegations_host.elementAt(i)); boolean alive = service.isAlive(url); System.out.println("-----ALIVE: " + alive); if (alive) { wsurl = new java.net.URL((String) v_delegations_url.elementAt(i)); try { wsurl.openStream(); System.out.println("-----WEBSERVICE: ON"); if (!prop.containsKey(0 + "." + AgentBehaviour.XML_URL)) { System.out.println("-----MIGRATION: First online host found. I will migrate here:)!"); prop.setProperty(0 + "." + AgentBehaviour.XML_HOST, (String) v_delegations_host.elementAt(i)); prop.setProperty(0 + "." + AgentBehaviour.XML_URL, (String) v_delegations_url.elementAt(i)); prop.setProperty(0 + "." + AgentBehaviour.XML_METHOD, (String) v_delegations_method.elementAt(i)); } else { System.out.println("-----MIGRATION: I will not migrate here:(!"); } } catch (IOException ex) { System.out.println("-----WEBSERVICE: Could not connect to the webservice!"); System.out.println("-----MIGRATION: WEBSERVICE NOT FOUND! I will not migrate here:(!"); } } } catch (ShipException she) { System.out.println("-----ALIVE: false"); System.out.println("-----MIGRATION: HOST NOT FOUND! I will not migrate here:(!"); } catch (SecurityException see) { System.out.println("-----EXCEPTION: Access connection to remote SHIP service fails! " + "No proper ShipPermission permission to invoke lookups! " + "Ignoring this host...."); } catch (MalformedURLException murle) { System.out.println("-----EXCEPTION: The host URL is not valid! Ignoring this host...."); } } res = new MemoryResource(); env = Environment.getEnvironment(); key = WhatIs.stringValue(AgentLauncher.WHATIS); l = (AgentLauncher) env.lookup(key); if (l == null) { System.out.println("Can't find the agent launcher"); return; } try { l.launchAgent(res, prop); } catch (IllegalAgentException ex) { System.out.println(ex); } catch (GeneralSecurityException ex) { System.out.println(ex); } catch (IOException ex) { System.out.println(ex); } syncmap_.put(token, results); System.out.println("----- TOKEN = " + token + "------"); } try { synchronized (token) { token.wait(TIMEOUT); Map m_results = (Map) syncmap_.get(token); Collection c_results = m_results.values(); String[] sa_results = (String[]) c_results.toArray(new String[0]); answ = ""; for (int j = 0; j < sa_results.length; j++) { answ = answ + sa_results[j]; } syncmap_.remove(token); System.out.println("----- " + answ + " -----"); callbackWS(xmlControl, answ, docId); } } catch (InterruptedException ex) { System.out.println(ex); } } |
00
| Code Sample 1:
private String hash(String text) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); }
Code Sample 2:
public Service findServiceFor(final int serviceID) throws JAXBException, IOException, BadResponseException { final String USER_AGENT = "SBSIVisual (CSBE, University of Edinburgh)"; String urlToConnectTo = "http://www.biocatalogue.org/services/" + serviceID; URL url = new URL(urlToConnectTo); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT); conn.setRequestProperty("Accept", "application/xml"); int iResponseCode = conn.getResponseCode(); InputStream serverResponse = null; switch(iResponseCode) { case HttpURLConnection.HTTP_OK: serverResponse = conn.getInputStream(); break; case HttpURLConnection.HTTP_BAD_REQUEST: throw new BadResponseException("Received BadResponse from server:" + HttpURLConnection.HTTP_BAD_REQUEST); } Service service = new ResponseParser<Service>().getObjectFor(serverResponse, Service.class); return service; } |
11
| Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
protected static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); URLConnection c = url.openConnection(); c.setConnectTimeout(2000); IOUtils.copy(c.getInputStream(), output); return output.toString(); } |
00
| Code Sample 1:
public void run() { synchronized (stateLock) { if (started) { return; } else { started = true; running = true; } } BufferedInputStream bis = null; BufferedOutputStream bos = null; BufferedReader br = null; try { checkState(); progressString = "Opening connection to remote resource"; progressUpdated = true; final URLConnection link; try { link = url.openConnection(); link.connect(); } catch (Exception e) { progressString = "Failed to open connection to remote resource"; progressUpdated = true; throw e; } checkState(); progressString = "Getting length of remote resource"; progressUpdated = true; final int length = link.getContentLength(); synchronized (lengthLock) { totalLength = length; } progressUpdated = true; checkState(); progressString = "Opening input stream to remote resource"; progressUpdated = true; try { final InputStream input = link.getInputStream(); if (target instanceof File) { bis = new BufferedInputStream(input); } else if (target instanceof StringBuilder) { final String contentType = link.getContentType().toLowerCase(Locale.ENGLISH); String charset = null; final Matcher m = Pattern.compile(".*charset[\\s]*=([^;]++).*").matcher(contentType); if (m.find()) { charset = m.group(1).trim(); } if ((charset != null) && !charset.isEmpty()) { try { br = new BufferedReader(new InputStreamReader(input, charset)); } catch (Exception e) { br = null; } } if (br == null) { br = new BufferedReader(new InputStreamReader(input)); } } } catch (Exception e) { progressString = "Failed to open input stream to remote resource"; progressUpdated = true; throw e; } if (target instanceof File) { checkState(); progressString = "Opening output stream to local file"; progressUpdated = true; try { final File f = (File) target; final File parent = f.getParentFile(); if ((parent != null) && !parent.exists()) { parent.mkdirs(); } bos = new BufferedOutputStream(new FileOutputStream(f)); } catch (Exception e) { progressString = "Failed to open output stream to local file"; progressUpdated = true; throw e; } } progressString = "Downloading"; progressUpdated = true; try { if (target instanceof File) { final byte[] byteBuffer = new byte[BUFFER_SIZE]; while (true) { checkState(); final int byteCount = bis.read(byteBuffer, 0, BUFFER_SIZE); if (byteCount == -1) { break; } bos.write(byteBuffer, 0, byteCount); synchronized (lengthLock) { downloadedLength += byteCount; } progressUpdated = true; } } else if (target instanceof StringBuilder) { final char[] charBuffer = new char[BUFFER_SIZE]; final StringBuilder sb = (StringBuilder) target; while (true) { checkState(); final int charCount = br.read(charBuffer, 0, BUFFER_SIZE); if (charCount == -1) { break; } sb.append(charBuffer, 0, charCount); synchronized (lengthLock) { downloadedLength += charCount; } progressUpdated = true; } } } catch (Exception e) { progressString = "Failed to download remote resource"; progressUpdated = true; throw e; } progressString = "Download completed"; progressUpdated = true; } catch (Exception e) { error = e; } finally { for (Closeable c : new Closeable[] { bis, br, bos }) { if (c != null) { try { c.close(); } catch (Exception e) { } } } synchronized (stateLock) { running = false; completed = true; } } }
Code Sample 2:
public RandomAccessFileOrArray(URL url) throws IOException { InputStream is = url.openStream(); try { this.arrayIn = InputStreamToArray(is); } finally { try { is.close(); } catch (IOException ioe) { } } } |
00
| Code Sample 1:
private void storeConfigurationPropertiesFile(java.net.URL url, String comp) { java.util.Properties p; try { p = new java.util.Properties(); p.load(url.openStream()); } catch (java.io.IOException ie) { System.err.println("error opening: " + url.getPath() + ": " + ie.getMessage()); return; } storeConfiguration(p, comp); return; }
Code Sample 2:
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 void run() { String s; s = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + word); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (((str = in.readLine()) != null) && (!stopped)) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("Main Entry:.+?<br>(.+?)</td>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); java.io.StringWriter wr = new java.io.StringWriter(); HTMLDocument doc = null; HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); try { doc = (HTMLDocument) editor.getDocument(); } catch (Exception e) { } System.out.println(wr); editor.setContentType("text/html"); if (matcher.find()) try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null); } catch (Exception e) { System.out.println(e.getMessage()); } else try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null); } catch (Exception e) { System.out.println(e.getMessage()); } button.setEnabled(true); }
Code Sample 2:
public void run() { if (currentNode == null || currentNode.equals("")) { JOptionPane.showMessageDialog(null, "Please select a genome to download first", "Error", JOptionPane.ERROR_MESSAGE); return; } String localFile = parameter.getTemporaryFilesPath() + currentNode; String remotePath = NCBI_FTP_PATH + currentPath; String remoteFile = remotePath + "/" + currentNode; try { ftp.connect(NCBI_FTP_HOST); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); JOptionPane.showMessageDialog(null, "FTP server refused connection", "Error", JOptionPane.ERROR_MESSAGE); } ftp.login("anonymous", "[email protected]"); inProgress = true; ftp.setFileType(FTPClient.BINARY_FILE_TYPE); long size = getFileSize(remotePath, currentNode); if (size == -1) throw new FileNotFoundException(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(localFile)); BufferedInputStream in = new BufferedInputStream(ftp.retrieveFileStream(remoteFile), ftp.getBufferSize()); byte[] b = new byte[1024]; long bytesTransferred = 0; int tick = 0; int oldTick = 0; int len; while ((len = in.read(b)) != -1) { out.write(b, 0, len); bytesTransferred += 1024; if ((tick = new Long(bytesTransferred * 100 / size).intValue()) > oldTick) { progressBar.setValue(tick < 100 ? tick : 99); oldTick = tick; } } in.close(); out.close(); ftp.completePendingCommand(); progressBar.setValue(100); fileDownloaded = localFile; JOptionPane.showMessageDialog(null, "File successfully downloaded", "Congratulation!", JOptionPane.INFORMATION_MESSAGE); ftp.logout(); } catch (SocketException ex) { JOptionPane.showMessageDialog(null, "Error occurs while trying to connect server", "Error", JOptionPane.ERROR_MESSAGE); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "This file is not found on the server", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error occurs while fetching data", "Error", JOptionPane.ERROR_MESSAGE); } finally { inProgress = false; if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } } |
00
| Code Sample 1:
@SuppressWarnings("unchecked") public static void main(String[] args) { System.out.println("Starting encoding test...."); Properties p = new Properties(); try { InputStream pStream = ClassLoader.getSystemResourceAsStream("sample_weather.properties"); p.load(pStream); } catch (Exception e) { System.err.println("Could not load properties file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } if (WeatherUpdater.DEBUG) { System.out.println("hostname: " + p.getProperty("weather.hostname")); } if (WeatherUpdater.DEBUG) { System.out.println("database: " + p.getProperty("weather.database")); } if (WeatherUpdater.DEBUG) { System.out.println("username: " + p.getProperty("weather.username")); } if (WeatherUpdater.DEBUG) { System.out.println("password: " + p.getProperty("weather.password")); } SqlAccount sqlAccount = new SqlAccount(p.getProperty("weather.hostname"), p.getProperty("weather.database"), p.getProperty("weather.username"), p.getProperty("weather.password")); DatabaseInterface dbi = null; try { dbi = new DatabaseInterface(sqlAccount); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Established connection to database."); String query = "SELECT * FROM Current_Weather WHERE ZipCode = '99702'"; ResultTable results; System.out.println("Executing query: " + query); try { results = dbi.executeQuery(query); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Got results from query."); System.out.println("Converted results into the following table:"); System.out.println(results); System.out.println(); Class<? extends ResultEncoder> encoder_class; Class<? extends ResultDecoder> decoder_class; try { encoder_class = (Class<? extends ResultEncoder>) Class.forName(p.getProperty("mysms.coding.resultEncoder")); decoder_class = (Class<? extends ResultDecoder>) Class.forName(p.getProperty("mysms.coding.resultDecoder")); } catch (Exception e) { System.err.println("Could not find specified encoder: " + p.getProperty("result.encoder")); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Found class of encoder: " + encoder_class); System.out.println("Found class of decoder: " + decoder_class); ResultEncoder encoder; ResultDecoder decoder; try { encoder = encoder_class.newInstance(); if (encoder_class.equals(decoder_class) && decoder_class.isInstance(encoder)) { decoder = (ResultDecoder) encoder; } else { decoder = decoder_class.newInstance(); } } catch (Exception e) { System.err.println("Could not create instances of encoder and decoder."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Created instances of encoder and decoder."); if (decoder.equals(encoder)) { System.out.println("Decoder and encoder are same object."); } ByteBuffer buffer; try { buffer = encoder.encode(null, results); } catch (Exception e) { System.err.println("Could not encode results."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Encoded results to ByteBuffer with size: " + buffer.capacity()); File temp; try { temp = File.createTempFile("encoding_test", ".results"); temp.deleteOnExit(); FileChannel out = new FileOutputStream(temp).getChannel(); out.write(buffer); out.close(); } catch (Exception e) { System.err.println("Could not write buffer to file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Wrote buffer to file: \"" + temp.getName() + "\" with length: " + temp.length()); ByteBuffer re_buffer; try { FileInputStream in = new FileInputStream(temp.getAbsolutePath()); byte[] temp_buffer = new byte[(int) temp.length()]; int totalRead = 0; int numRead = 0; while (totalRead < temp_buffer.length) { numRead = in.read(temp_buffer, totalRead, temp_buffer.length - totalRead); if (numRead < 0) { break; } else { totalRead += numRead; } } re_buffer = ByteBuffer.wrap(temp_buffer); in.close(); } catch (Exception e) { System.err.println("Could not read from temporary file into buffer."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Read file back into buffer with length: " + re_buffer.capacity()); ResultTable re_results; try { re_results = decoder.decode(null, re_buffer); } catch (Exception e) { System.err.println("Could not decode buffer into a ResultTable."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Decoded buffer back into the following table:"); System.out.println(re_results); System.out.println(); System.out.println("... encoding test complete."); }
Code Sample 2:
public static void copierFichier(URL url, File destination) throws CopieException, IOException { if (destination.exists()) { throw new CopieException("ERREUR : Copie du fichier '" + url.getPath() + "' vers '" + destination.getPath() + "' impossible!\n" + "CAUSE : Le fichier destination existe d�j�."); } URLConnection urlConnection = url.openConnection(); InputStream httpStream = urlConnection.getInputStream(); FileOutputStream destinationFile = new FileOutputStream(destination); byte buffer[] = new byte[512 * 1024]; int nbLecture; while ((nbLecture = httpStream.read(buffer)) != -1) { destinationFile.write(buffer, 0, nbLecture); } log.debug("(COPIE) Copie du fichier : " + url.getPath() + " --> " + destination.getPath()); httpStream.close(); destinationFile.close(); } |
00
| Code Sample 1:
public void delete(int id) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String sql = "delete from Instructions where InstructionId = " + id; stmt.executeUpdate(sql); sql = "delete from InstructionGroups where InstructionId = " + id; stmt.executeUpdate(sql); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
Code Sample 2:
private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } } |
11
| Code Sample 1:
@Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
Code Sample 2:
protected int doWork() { SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); reader.getFileHeader().setSortOrder(SORT_ORDER); SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), false, OUTPUT); Iterator<SAMRecord> iterator = reader.iterator(); while (iterator.hasNext()) writer.addAlignment(iterator.next()); reader.close(); writer.close(); return 0; } |
00
| Code Sample 1:
public static byte[] generatePasswordHash(String s) { byte[] password = { 00 }; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.getBytes()); password = md5.digest(); return password; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return password; }
Code Sample 2:
public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); } |
11
| Code Sample 1:
private void copy(File source, File target) throws IOException { FileChannel in = (new FileInputStream(source)).getChannel(); FileChannel out = (new FileOutputStream(target)).getChannel(); in.transferTo(0, source.length(), out); in.close(); out.close(); }
Code Sample 2:
public void SplitFile(File in, File out0, File out1, long pos) throws IOException { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out0); FileChannel fic = fis.getChannel(); FileChannel foc = fos.getChannel(); foc.transferFrom(fic, 0, pos); foc.close(); fos = new FileOutputStream(out1); foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size() - pos); foc.close(); fic.close(); } |
00
| Code Sample 1:
protected InputStream openInputStream(String filename) throws FileNotFoundException { InputStream in = null; try { URL url = new URL(filename); in = url.openConnection().getInputStream(); logger.info("Opening file " + filename); } catch (FileNotFoundException e) { logger.error("Resource file not found: " + filename); throw e; } catch (IOException e) { logger.error("Resource file can not be readed: " + filename); throw new FileNotFoundException("Resource file can not be readed: " + filename); } if (in == null) { logger.error("Resource file not found: " + filename); throw new FileNotFoundException(filename); } return in; }
Code Sample 2:
public String encrypt(String password) { if (password.length() == 40) { return password; } if (salt != null) { password = password + salt; } MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e.getMessage(), e); } messageDigest.reset(); messageDigest.update(password.getBytes()); final byte[] bytes = messageDigest.digest(); String encrypted = new BigInteger(1, bytes).toString(16); if (encrypted.length() < 40) { final StringBuilder builder = new StringBuilder(encrypted); while (builder.length() < 40) { builder.insert(0, '0'); } encrypted = builder.toString(); } return encrypted; } |
00
| Code Sample 1:
public static <T extends Comparable<T>> void BubbleSortComparable1(T[] num) { int j; boolean flag = true; // set flag to true to begin first pass T temp; // holding variable while (flag) { flag = false; // set flag to false awaiting a possible swap for (j = 0; j < num.length - 1; j++) { if (num[j].compareTo(num[j + 1]) > 0) // change to > for ascending sort { temp = num[j]; // swap elements num[j] = num[j + 1]; num[j + 1] = temp; flag = true; // shows a swap occurred } } } }
Code Sample 2:
public static String compressFile(String fileName) throws IOException { String newFileName = fileName + ".gz"; FileInputStream fis = new FileInputStream(fileName); FileOutputStream fos = new FileOutputStream(newFileName); GZIPOutputStream gzos = new GZIPOutputStream(fos); byte[] buf = new byte[10000]; int bytesRead; while ((bytesRead = fis.read(buf)) > 0) gzos.write(buf, 0, bytesRead); fis.close(); gzos.close(); return newFileName; } |
11
| Code Sample 1:
public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
00
| Code Sample 1:
public void sendMail() throws Exception { try { if (param.length > 0) { System.setProperty("mail.host", param[0].trim()); URL url = new URL("mailto:" + param[1].trim()); URLConnection conn = url.openConnection(); PrintWriter out = new PrintWriter(conn.getOutputStream(), true); out.print("To:" + param[1].trim() + "\n"); out.print("Subject: " + param[2] + "\n"); out.print("MIME-Version: 1.0\n"); out.print("Content-Type: multipart/mixed; boundary=\"tcppop000\"\n\n"); out.print("--tcppop000\n"); out.print("Content-Type: text/plain\n"); out.print("Content-Transfer-Encoding: 7bit\n\n\n"); out.print(param[3] + "\n\n\n"); out.print("--tcppop000\n"); String filename = param[4].trim(); int sep = filename.lastIndexOf(File.separator); if (sep > 0) { filename = filename.substring(sep + 1, filename.length()); } out.print("Content-Type: text/html; name=\"" + filename + "\"\n"); out.print("Content-Transfer-Encoding: binary\n"); out.print("Content-Disposition: attachment; filename=\"" + filename + "\"\n\n"); System.out.println("FOR ATTACHMENT Content-Transfer-Encoding: binary "); RandomAccessFile file = new RandomAccessFile(param[4].trim(), "r"); byte[] buffer = new byte[(int) file.length()]; file.readFully(buffer); file.close(); String fileContent = new String(buffer); out.print(fileContent); out.print("\n"); out.print("--tcppop000--"); out.close(); } else { } } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } }
Code Sample 2:
protected void readLockssConfigFile(URL url, List<String> peers) { PrintWriter out = null; try { out = new PrintWriter(new OutputStreamWriter(System.out, "utf8"), true); out.println("unicode-output-ready"); } catch (UnsupportedEncodingException ex) { System.out.println(ex.toString()); return; } XMLInputFactory xmlif = XMLInputFactory.newInstance(); xmlif.setProperty("javax.xml.stream.isCoalescing", java.lang.Boolean.TRUE); xmlif.setProperty("javax.xml.stream.isNamespaceAware", java.lang.Boolean.TRUE); XMLStreamReader xmlr = null; BufferedInputStream stream = null; long starttime = System.currentTimeMillis(); out.println("Starting to parse the remote config xml[" + url + "]"); int elementCount = 0; int topPropertyCounter = 0; int propertyTagLevel = 0; try { stream = new BufferedInputStream(url.openStream()); xmlr = xmlif.createXMLStreamReader(stream, "utf8"); int eventType = xmlr.getEventType(); String curElement = ""; String targetTagName = "property"; String peerListAttrName = "id.initialV3PeerList"; boolean sentinel = false; boolean valueline = false; while (xmlr.hasNext()) { eventType = xmlr.next(); switch(eventType) { case XMLEvent.START_ELEMENT: curElement = xmlr.getLocalName(); if (curElement.equals("property")) { topPropertyCounter++; propertyTagLevel++; int count = xmlr.getAttributeCount(); if (count > 0) { for (int i = 0; i < count; i++) { if (xmlr.getAttributeValue(i).equals(peerListAttrName)) { sentinel = true; out.println("!!!!!! hit the" + peerListAttrName); out.println("attr=" + xmlr.getAttributeName(i)); out.println("vl=" + xmlr.getAttributeValue(i)); out.println(">>>>>>>>>>>>>> start :property tag (" + topPropertyCounter + ") >>>>>>>>>>>>>>"); out.println(">>>>>>>>>>>>>> property tag level (" + propertyTagLevel + ") >>>>>>>>>>>>>>"); out.print(xmlr.getAttributeName(i).toString()); out.print("="); out.print("\""); out.print(xmlr.getAttributeValue(i)); out.println(""); } } } } if (sentinel && curElement.equals("value")) { valueline = true; String ipAd = xmlr.getElementText(); peers.add(ipAd); } break; case XMLEvent.CHARACTERS: break; case XMLEvent.ATTRIBUTE: if (curElement.equals(targetTagName)) { } break; case XMLEvent.END_ELEMENT: if (xmlr.getLocalName().equals("property")) { if (sentinel) { out.println("========= end of the target property element"); sentinel = false; valueline = false; } elementCount++; propertyTagLevel--; } else { } break; case XMLEvent.END_DOCUMENT: } } } catch (MalformedURLException ue) { } catch (IOException ex) { } catch (XMLStreamException ex) { } finally { if (xmlr != null) { try { xmlr.close(); } catch (XMLStreamException ex) { } } if (stream != null) { try { stream.close(); } catch (IOException ex) { } } } } |
11
| Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } } |
00
| Code Sample 1:
@Override public void parse() throws DocumentException, IOException { URL url = new URL(getDataUrl()); URLConnection con = url.openConnection(); BufferedReader bStream = new BufferedReader(new InputStreamReader(con.getInputStream())); String s = bStream.readLine(); bStream.readLine(); while ((s = bStream.readLine()) != null) { String[] tokens = s.split("\\|"); ResultUnit unit = new ResultUnit(tokens[3], Float.valueOf(tokens[4]), Integer.valueOf(tokens[2])); set.add(unit); } }
Code Sample 2:
public static void writeFullImageToStream(Image scaledImage, String javaFormat, OutputStream os) throws IOException { BufferedImage bufImage = new BufferedImage(scaledImage.getWidth(null), scaledImage.getHeight(null), BufferedImage.TYPE_BYTE_BINARY); Graphics gr = bufImage.getGraphics(); gr.drawImage(scaledImage, 0, 0, null); gr.dispose(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bufImage, javaFormat, bos); IOUtils.copyStreams(new ByteArrayInputStream(bos.toByteArray()), os); } |
00
| Code Sample 1:
public boolean saveVideoXMLOnWebserver(String text) { boolean error = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(this.getWebserver().getUrl()); System.out.println("Connected to " + this.getWebserver().getUrl() + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return false; } if (!ftp.login(this.getWebserver().getFtpBenutzer(), this.getWebserver().getFtpPasswort())) { System.err.println("FTP server: Login incorrect"); } String tmpSeminarID = this.getSeminarID(); if (tmpSeminarID == null) tmpSeminarID = "unbekannt"; try { ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/" + this.getId() + "/data"); } catch (Exception e) { ftp.makeDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/" + this.getId() + "/data"); ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/" + this.getId() + "/data"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ByteArrayInputStream videoIn = new ByteArrayInputStream(text.getBytes()); ftp.enterLocalPassiveMode(); ftp.storeFile("video.xml", videoIn); videoIn.close(); ftp.logout(); ftp.disconnect(); } catch (IOException e) { System.err.println("Job " + this.getId() + ": Datei video.xml konnte nicht auf Webserver kopiert werden."); error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return error; }
Code Sample 2:
public static File jar(File in, String outArc, File tempDir, PatchConfigXML conf) { FileOutputStream arcFile = null; JarOutputStream jout = null; DirectoryScanner ds = null; ds = new DirectoryScanner(); ds.setCaseSensitive(true); ds.setBasedir(in); ds.scan(); ds.setCaseSensitive(true); String[] names = ds.getIncludedFiles(); ArrayList exName = new ArrayList(); if (names == null || names.length < 1) return null; File tempArc = new File(tempDir, outArc.substring(0, outArc.length())); try { Manifest mf = null; List v = new ArrayList(); for (int i = 0; i < names.length; i++) { if (names[i].toUpperCase().indexOf("MANIFEST.MF") > -1) { FileInputStream fis = new FileInputStream(in.getAbsolutePath() + "/" + names[i].replace('\\', '/')); mf = new Manifest(fis); } else v.add(names[i]); } String[] toJar = new String[v.size()]; v.toArray(toJar); tempArc.createNewFile(); arcFile = new FileOutputStream(tempArc); if (mf == null) jout = new JarOutputStream(arcFile); else jout = new JarOutputStream(arcFile, mf); byte[] buffer = new byte[1024]; for (int i = 0; i < toJar.length; i++) { if (conf != null) { if (!conf.allowFileAction(toJar[i], PatchConfigXML.OP_CREATE)) { exName.add(toJar[i]); continue; } } String currentPath = in.getAbsolutePath() + "/" + toJar[i]; String entryName = toJar[i].replace('\\', '/'); JarEntry currentEntry = new JarEntry(entryName); jout.putNextEntry(currentEntry); FileInputStream fis = new FileInputStream(currentPath); int len; while ((len = fis.read(buffer)) >= 0) jout.write(buffer, 0, len); fis.close(); jout.closeEntry(); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { jout.close(); arcFile.close(); } catch (IOException e1) { throw new RuntimeException(e1); } } return tempArc; } |
00
| Code Sample 1:
protected void updateJava2ScriptProject(String prjFolder, String binRelative) { try { File cpFile = new File(prjFolder, ".classpath"); FileInputStream fis = new FileInputStream(cpFile); String classpath = J2SLaunchingUtil.readAFile(fis); if (classpath != null) { boolean needUpdate = false; if (classpath.indexOf("ECLIPSE_SWT") == -1 && classpath.indexOf("SWT_LIBRARY") == -1 && classpath.indexOf("eclipse.swt") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry kind=\"var\" path=\"ECLIPSE_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_SWT") == -1 && classpath.indexOf("ajaxswt.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_SWT_SRC\" kind=\"var\" path=\"AJAX_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_RPC") == -1 && classpath.indexOf("ajaxrpc.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_RPC_SRC\" kind=\"var\" path=\"AJAX_RPC\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_PIPE") == -1 && classpath.indexOf("ajaxpipe.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_PIPE_SRC\" kind=\"var\" path=\"AJAX_PIPE\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (needUpdate) { try { FileOutputStream fos = new FileOutputStream(cpFile); fos.write(classpath.getBytes("utf-8")); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } File webinf = new File(prjFolder, "WEB-INF"); webinf.mkdir(); new File(webinf, "classes").mkdir(); File lib = new File(webinf, "lib"); lib.mkdir(); IPath newPath = null; URL starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); String root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxrpc.jar"); File rpcFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(rpcFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxrpc.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxpipe.jar"); File pipeFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(pipeFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxpipe.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } StringBuffer buildxml = new StringBuffer(); buildxml.append("<?xml version=\"1.0\"?>\r\n"); buildxml.append("<project name=\"java2script.servlet.pack\" default=\"pack.war\" basedir=\".\">\r\n"); buildxml.append(" <description>Pack Java2Script Servlet Application</description>\r\n"); buildxml.append("\r\n"); String name = new File(prjFolder).getName(); buildxml.append(" <property name=\"java2script.app.name\" value=\"" + name + "\"/>\r\n"); buildxml.append(" <property name=\"bin.folder\" value=\"${basedir}/../" + binRelative + "\"/>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.war\" depends=\"pack.jar\">\r\n"); buildxml.append(" <tstamp>\r\n"); buildxml.append(" <format property=\"now\" pattern=\"yyyy-MM-dd-HH-mm-ss\"/>\r\n"); buildxml.append(" </tstamp>\r\n"); buildxml.append(" <delete file=\"${basedir}/../${java2script.app.name}.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../${java2script.app.name}.${now}.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/../\">\r\n"); buildxml.append(" <exclude name=\"src/**\"/>\r\n"); buildxml.append(" <exclude name=\"META-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.java\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.class\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" <fileset dir=\"${basedir}/..\">\r\n"); buildxml.append(" <include name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/build.xml\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" <copy file=\"${basedir}/../${java2script.app.name}.${now}.war\"\r\n"); buildxml.append(" tofile=\"${basedir}/../${java2script.app.name}.war\"/>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.jar\">\r\n"); buildxml.append(" <delete file=\"${basedir}/lib/${java2script.app.name}.jar\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/lib/${java2script.app.name}.jar\">\r\n"); buildxml.append(" <fileset dir=\"${bin.folder}\">\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.html\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.js\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.css\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.bmp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.gif\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.png\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpeg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root); String ajaxPath = newPath.toOSString(); String key = "net.sf.j2s.ajax"; int idx = ajaxPath.lastIndexOf(key); if (idx != -1) { ajaxPath = ajaxPath.substring(0, idx) + "net.sf.j2s.lib" + ajaxPath.substring(idx + key.length()); } File libFile = new File(ajaxPath); String j2sRelativePath = FileUtil.toRelativePath(libFile.getAbsolutePath(), webinf.getAbsolutePath()); if (j2sRelativePath.length() > 0 && !j2sRelativePath.endsWith("/")) { j2sRelativePath += "/"; } int slashIndex = j2sRelativePath.lastIndexOf('/', j2sRelativePath.length() - 2); String pluginPath = j2sRelativePath.substring(0, slashIndex); String libPluginPath = j2sRelativePath.substring(slashIndex + 1, j2sRelativePath.length() - 1); buildxml.append(" <target name=\"pack.plugins.j2slib.war\">\r\n"); buildxml.append(" <delete file=\"${basedir}/../plugins.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../plugins.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/" + pluginPath + "/\">\r\n"); buildxml.append(" <include name=\"" + libPluginPath + "/**\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/library.jar\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/META-INF/**\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append("</project>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "build.xml")); fos.write(buildxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } StringBuffer webxml = new StringBuffer(); webxml.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n"); webxml.append("<!DOCTYPE web-app\r\n"); webxml.append(" PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\r\n"); webxml.append(" \"http://java.sun.com/dtd/web-app_2_3.dtd\">\r\n"); webxml.append("<web-app>\r\n"); webxml.append(" <display-name>Java2Script</display-name>\r\n"); webxml.append(" <description>Java2Script application</description>\r\n"); webxml.append(genereateServlet("simplerpc", "net.sf.j2s.ajax.SimpleRPCHttpServlet")); webxml.append(genereateServlet("piperpc", "net.sf.j2s.ajax.CompoundPipeRPCHttpServlet")); webxml.append(" <servlet>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <servlet-class>net.sf.j2s.ajax.SimplePipeHttpServlet</servlet-class>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.query.timeout</param-name>\r\n"); webxml.append(" <param-value>20000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.script.breakout</param-name>\r\n"); webxml.append(" <param-value>1200000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.max.items.per.query</param-name>\r\n"); webxml.append(" <param-value>60</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" </servlet>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplerpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplerpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>piperpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/piperpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplepipe</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append("</web-app>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "web.xml")); fos.write(webxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } }
Code Sample 2:
public void run() { try { HttpPost httpPostRequest = new HttpPost(Feesh.device_URL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("c", "feed")); nameValuePairs.add(new BasicNameValuePair("amount", String.valueOf(foodAmount))); nameValuePairs.add(new BasicNameValuePair("type", String.valueOf(foodType))); httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse httpResponse = (HttpResponse) new DefaultHttpClient().execute(httpPostRequest); HttpEntity entity = httpResponse.getEntity(); String resultString = ""; if (entity != null) { InputStream instream = entity.getContent(); resultString = convertStreamToString(instream); instream.close(); } Message msg_toast = new Message(); msg_toast.obj = resultString; toast_handler.sendMessage(msg_toast); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public synchronized long nextValue(final Session session) { if (sequence < seqLimit) { return ++sequence; } else { final MetaDatabase db = MetaTable.DATABASE.of(table); Connection connection = null; ResultSet res = null; String sql = null; PreparedStatement statement = null; StringBuilder out = new StringBuilder(64); try { connection = session.getSeqConnection(db); String tableName = db.getDialect().printFullTableName(getTable(), true, out).toString(); out.setLength(0); out.setLength(0); sql = db.getDialect().printSequenceNextValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); int i = statement.executeUpdate(); if (i == 0) { out.setLength(0); sql = db.getDialect().printSequenceInit(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.executeUpdate(); } out.setLength(0); sql = db.getDialect().printSequenceCurrentValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); res = statement.executeQuery(); res.next(); seqLimit = res.getLong(1); int step = res.getInt(2); maxValue = res.getLong(3); sequence = (seqLimit - step) + 1; if (maxValue != 0L) { if (seqLimit > maxValue) { seqLimit = maxValue; if (sequence > maxValue) { String msg = "The sequence '" + tableName + "' needs to raise the maximum value: " + maxValue; throw new IllegalStateException(msg); } statement.close(); sql = db.getDialect().printSetMaxSequence(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.execute(); } if (maxValue > Long.MAX_VALUE - step) { String msg = "The sequence attribute '" + tableName + ".maxValue' is too hight," + " the recommended maximal value is: " + (Long.MAX_VALUE - step) + " (Long.MAX_VALUE-step)"; LOGGER.log(Level.WARNING, msg); } } connection.commit(); } catch (Throwable e) { if (connection != null) try { connection.rollback(); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "Rollback fails"); } IllegalStateException exception = e instanceof IllegalStateException ? (IllegalStateException) e : new IllegalStateException("ILLEGAL SQL: " + sql, e); throw exception; } finally { MetaDatabase.close(null, statement, res, true); } return sequence; } }
Code Sample 2:
public boolean compile(URL url, String name) { try { final InputStream stream = url.openStream(); final InputSource input = new InputSource(stream); input.setSystemId(url.toString()); return compile(input, name); } catch (IOException e) { _parser.reportError(Constants.FATAL, new ErrorMsg(e)); return false; } } |
11
| Code Sample 1:
private void copyFile(File src_file, File dest_file) { InputStream src_stream = null; OutputStream dest_stream = null; try { int b; src_stream = new BufferedInputStream(new FileInputStream(src_file)); dest_stream = new BufferedOutputStream(new FileOutputStream(dest_file)); while ((b = src_stream.read()) != -1) dest_stream.write(b); } catch (Exception e) { XRepository.getLogger().warning(this, "Error on copying the plugin file!"); XRepository.getLogger().warning(this, e); } finally { try { src_stream.close(); dest_stream.close(); } catch (Exception ex2) { } } }
Code Sample 2:
private void chopFileDisk() throws IOException { File tempFile = new File("" + logFile + ".tmp"); BufferedInputStream bis = null; BufferedOutputStream bos = null; long startCopyPos; byte readBuffer[] = new byte[2048]; int readCount; long totalBytesRead = 0; if (reductionRatio > 0 && logFile.length() > 0) { startCopyPos = logFile.length() / reductionRatio; } else { startCopyPos = 0; } try { bis = new BufferedInputStream(new FileInputStream(logFile)); bos = new BufferedOutputStream(new FileOutputStream(tempFile)); do { readCount = bis.read(readBuffer, 0, readBuffer.length); if (readCount > 0) { totalBytesRead += readCount; if (totalBytesRead > startCopyPos) { bos.write(readBuffer, 0, readCount); } } } while (readCount > 0); } finally { if (bos != null) { try { bos.close(); } catch (IOException ex) { } } if (bis != null) { try { bis.close(); } catch (IOException ex) { } } } if (tempFile.isFile()) { if (!logFile.delete()) { throw new IOException("Error when attempting to delete the " + logFile + " file."); } if (!tempFile.renameTo(logFile)) { throw new IOException("Error when renaming the " + tempFile + " to " + logFile + "."); } } } |
00
| Code Sample 1:
public static void parse(URL url, ContentHandler handler) { InputStream input = null; try { input = url.openStream(); SAXParser parser = createSaxParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(input)); } catch (SAXException e) { throw new XmlException("Could not parse xml", e); } catch (IOException e) { throw new XmlException("Could not parse xml", e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } }
Code Sample 2:
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } |
00
| Code Sample 1:
public static URLConnection createConnection(URL url) throws java.io.IOException { URLConnection urlConn = url.openConnection(); if (urlConn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setRequestMethod("POST"); } urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setDefaultUseCaches(false); return urlConn; }
Code Sample 2:
protected boolean hasOsmTileETag(String eTag) throws IOException { URL url; url = new URL(tile.getUrl()); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); prepareHttpUrlConnection(urlConn); urlConn.setRequestMethod("HEAD"); urlConn.setReadTimeout(30000); String osmETag = urlConn.getHeaderField("ETag"); if (osmETag == null) return true; return (osmETag.equals(eTag)); } |
11
| Code Sample 1:
public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } }
Code Sample 2:
public static String compressFile(String fileName) throws IOException { String newFileName = fileName + ".gz"; FileInputStream fis = new FileInputStream(fileName); FileOutputStream fos = new FileOutputStream(newFileName); GZIPOutputStream gzos = new GZIPOutputStream(fos); byte[] buf = new byte[10000]; int bytesRead; while ((bytesRead = fis.read(buf)) > 0) gzos.write(buf, 0, bytesRead); fis.close(); gzos.close(); return newFileName; } |
00
| Code Sample 1:
private static void findDictionary() { java.net.URL url = Translator.class.getResource("Translator.class"); String location = url.getFile(); String dictionaryName = (String) Settings.getDefault().getSetting("dictionary"); InputStream inputStream; try { if (location.indexOf(".jar!") == -1) inputStream = new FileInputStream(location.substring(0, location.indexOf("Translator.class")) + dictionaryName); else { JarFile jarFile; if (location.indexOf("rachota.sourceforge.net") != -1) { String fileName = location.substring(0, location.indexOf("!/") + 2); url = new URL("jar:http://rachota.sourceforge.net/rachota_22.jar!/"); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); jarFile = jarConnection.getJarFile(); } else { String fileName = System.getProperty("os.name").indexOf("Windows") == -1 ? "/" : ""; fileName = fileName + location.substring(6, location.indexOf(".jar") + 4); fileName = Tools.replaceAll(fileName, "%20", " "); jarFile = new JarFile(fileName); } ZipEntry entry = jarFile.getEntry("org/cesilko/rachota/core/" + dictionaryName); if (entry == null) { entry = jarFile.getEntry("org/cesilko/rachota/core/Dictionary_en_US.properties"); Settings.getDefault().setSetting("dictionary", "Dictionary_en_US.properties"); } inputStream = jarFile.getInputStream(entry); } dictionary = new PropertyResourceBundle(inputStream); } catch (Exception e) { System.out.println("Error: Reading from " + dictionaryName + " dictionary failed."); e.printStackTrace(); } }
Code Sample 2:
protected String updateTwitter() { if (updatingTwitter) return null; updatingTwitter = true; String highestId = null; final Cursor cursor = query(TWITTER_TABLE, new String[] { KEY_TWEET_ID }, null, null, null); if (cursor.getCount() > 0) { cursor.moveToFirst(); highestId = cursor.getString(cursor.getColumnIndex(KEY_TWEET_ID)); } cursor.close(); final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); nameValuePairs.add(new BasicNameValuePair("screen_name", TWITTER_ACCOUNT)); nameValuePairs.add(new BasicNameValuePair("count", "" + MAX_TWEETS)); if (highestId != null) nameValuePairs.add(new BasicNameValuePair("since_id", highestId)); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final HttpParams params = new BasicHttpParams(); final SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry); final HttpClient httpclient = new DefaultHttpClient(mgr, params); final HttpGet request = new HttpGet(); final String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); String data = ""; try { final URI uri = new URI(TWITTER_URL + "?" + paramString); request.setURI(uri); final HttpResponse response = httpclient.execute(request); final BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) data += inputLine; in.close(); } catch (final URISyntaxException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final ClientProtocolException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final IOException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } try { final JSONArray tweets = new JSONArray(data); if (tweets == null) { updatingTwitter = false; return "failed"; } if (tweets.length() == 0) { updatingTwitter = false; return "none"; } final SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH); final SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH); for (int i = 0; i < tweets.length(); i++) { final JSONObject tweet = tweets.getJSONObject(i); final ContentValues values = new ContentValues(); Log.v(TAG, "Datum van tweet: " + tweet.getString(KEY_TWEET_DATE)); values.put(KEY_TWEET_DATE, formatter.format(parser.parse(tweet.getString(KEY_TWEET_DATE)))); values.put(KEY_TWEET_TEXT, tweet.getString(KEY_TWEET_TEXT)); values.put(KEY_TWEET_ID, tweet.getString(KEY_TWEET_ID)); insert(TWITTER_TABLE, values); } } catch (final JSONException e) { Log.v(TAG, "JSON decodering is mislukt."); e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final ParseException e) { Log.v(TAG, "Datum decodering is mislukt."); e.printStackTrace(); updatingTwitter = false; return "failed"; } purgeTweets(); updatingTwitter = false; return "success"; } |
11
| Code Sample 1:
private void processData(InputStream raw) { String fileName = remoteName; if (localName != null) { fileName = localName; } try { FileOutputStream fos = new FileOutputStream(new File(fileName), true); IOUtils.copy(raw, fos); LOG.info("ok"); } catch (IOException e) { LOG.error("error writing file", e); } }
Code Sample 2:
public String getData() throws ValueFormatException, RepositoryException, IOException { InputStream is = getStream(); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); IOUtils.closeQuietly(is); return sw.toString(); } |
11
| Code Sample 1:
@Override public void run() { try { IOUtils.copy(getSource(), processStdIn); System.err.println("Copy done."); close(); } catch (IOException e) { e.printStackTrace(); IOUtils.closeQuietly(ExternalDecoder.this); } }
Code Sample 2:
public boolean open(String mode) { if (source instanceof String) return false; else if (mode == null) mode = ""; else mode = mode.toLowerCase(); boolean toread = false, towrite = false; if (mode.indexOf("r") >= 0) toread = true; if (mode.indexOf("w") >= 0) towrite = true; if (!toread && !towrite) toread = towrite = true; try { if (toread && input == null) { if (isDirectory()) return true; else if (reader != null) return true; else if (source instanceof File) input = new FileInputStream((File) source); else if (source instanceof Socket) input = ((Socket) source).getInputStream(); else if (source instanceof URL) return getUrlInfo(toread, towrite); else return false; } if (towrite && output == null) { if (isDirectory()) return false; else if (writer != null) return true; else if (source instanceof File) output = new FileOutputStream((File) source); else if (source instanceof Socket) output = ((Socket) source).getOutputStream(); else if (source instanceof URL) return getUrlInfo(toread, towrite); else return false; } return true; } catch (Exception e) { return false; } } |
00
| Code Sample 1:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); HttpSession session = request.getSession(); String session_id = session.getId(); File session_fileDir = new File(destinationDir + java.io.File.separator + session_id); session_fileDir.mkdir(); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); String pathToFile = new String(); try { List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { ; } else { pathToFile = getServletContext().getRealPath("/") + "files" + java.io.File.separator + session_id; File file = new File(pathToFile + java.io.File.separator + item.getName()); item.write(file); getContents(file, pathToFile); ComtorStandAlone.setMode(Mode.CLOUD); Comtor.start(pathToFile); } } try { File reportFile = new File(pathToFile + java.io.File.separator + "comtorReport.txt"); String reportURLString = AWSServices.storeReportS3(reportFile, session_id).toString(); if (reportURLString.startsWith("https")) reportURLString = reportURLString.replaceFirst("https", "http"); String requestURL = request.getRequestURL().toString(); String url = requestURL.substring(0, requestURL.lastIndexOf("/")); out.println("<html><head/><body>"); out.println("<a href=\"" + url + "\">Return to home</a> "); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/><hr/>"); Scanner scan = new Scanner(reportFile); out.println("<pre>"); while (scan.hasNextLine()) out.println(scan.nextLine()); out.println("</pre><hr/>"); out.println("<a href=\"" + url + "\">Return to home</a> "); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/>"); out.println("</body></html>"); } catch (Exception ex) { System.err.println(ex); } } catch (FileUploadException ex) { System.err.println("Error encountered while parsing the request" + ex); } catch (Exception ex) { System.err.println("Error encountered while uploading file" + ex); } }
Code Sample 2:
public String buscaCDA() { Properties prop = new CargaProperties().Carga(); URL url; BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("CDA")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("cda-TRUNK-")) { miLinea = inputLine; miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/dist/cda-TRUNK")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build CDA: " + miLinea); return miLinea; } |
00
| Code Sample 1:
public boolean actualizarIdPartida(int idJugadorDiv, int idRonda, int idPartida) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPartida = " + idPartida + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); }
Code Sample 2:
public SearchHandler(String criteria, int langId) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Catalog.groovy?method=GetProductListByName&criteria=" + criteria + "&language_id=" + langId); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("product"); for (int i = 0; i < nl.getLength(); i++) { Element nodes = (Element) nl.item(i); String id = nodes.getAttribute("id").toString(); NodeList name = nodes.getElementsByTagName("name"); NodeList rank2 = nodes.getElementsByTagName("sales_rank"); NodeList price = nodes.getElementsByTagName("price"); NodeList url2 = nodes.getElementsByTagName("image_url"); String nameS = getCharacterDataFromElement((Element) name.item(0)); String rank2S = getCharacterDataFromElement((Element) rank2.item(0)); String priceS = getCharacterDataFromElement((Element) price.item(0)); String url2S = getCharacterDataFromElement((Element) url2.item(0)); list.add(new ProductShort(id, nameS, rank2S, priceS, url2S)); } } catch (Exception e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
Code Sample 2:
public static String Execute(HttpRequestBase httprequest) throws IOException, ClientProtocolException { httprequest.setHeader("Accept", "application/json"); httprequest.setHeader("Content-type", "application/json"); String result = ""; HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httprequest); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { result += line + "\n"; } return result; } |
11
| Code Sample 1:
public static void main(String args[]) throws Exception { File file = new File("D:/work/love.txt"); @SuppressWarnings("unused") ZipFile zipFile = new ZipFile("D:/work/test1.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("D:/work/test1.zip")); zos.setEncoding("GBK"); ZipEntry entry = null; if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); int readLen = 0; byte[] buf = new byte[2048]; if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 2048)) != -1) { zos.write(buf, 0, readLen); } in.close(); } zos.close(); }
Code Sample 2:
private static boolean copyFile(File src, File dest) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (fis != null) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } if (fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } |
00
| Code Sample 1:
public void doActionxxx() { try { System.out.println("app: ggc"); String server_name = "http://192.168.4.3:8080/"; server_name = server_name.trim(); if (server_name.length() == 0) { server_name = "http://www.atech-software.com/"; } else { if (!server_name.startsWith("http://")) server_name = "http://" + server_name; if (!server_name.endsWith("/")) server_name = server_name + "/"; } URL url = new URL(server_name + "ATechUpdateGetFile?" + "" + "file_id=1" + "&" + "version_requested=1"); InputStream is = url.openStream(); RandomAccessFile raf = new RandomAccessFile("/home/andy/test.jpg", "rw"); ArrayList<Integer> list = new ArrayList<Integer>(); float size = 671200; long current_size = 0; System.out.println("File size: " + is.available()); byte[] array = new byte[1024]; while (is.available() > 0) { if (is.available() < 1024) { array = new byte[is.available()]; } is.read(array); raf.write(array); current_size += array.length; System.out.println("Progress: " + ((current_size / size) * 100)); } System.out.println("Size Arr: " + list.size()); CheckSumUtility csu = new CheckSumUtility(); System.out.println("Checksum: " + csu.getChecksumValue("/home/andy/test.jpg")); } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
public void play(File file) { try { URL url = new URL("http://127.0.0.1:8081/play.html?type=4&file=" + file.getAbsolutePath() + "&name=toto"); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } catch (Exception e) { e.printStackTrace(); } } |
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:
@Override protected String doIt() throws Exception { PreparedStatement insertStmt = null; try { insertStmt = DB.prepareStatement("INSERT INTO AD_Sequence_No(AD_SEQUENCE_ID, CALENDARYEAR, " + "AD_CLIENT_ID, AD_ORG_ID, ISACTIVE, CREATED, CREATEDBY, " + "UPDATED, UPDATEDBY, CURRENTNEXT) " + "(SELECT AD_Sequence_ID, '" + year + "', " + "AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, " + "Updated, UpdatedBy, StartNo " + "FROM AD_Sequence a " + "WHERE StartNewYear = 'Y' AND NOT EXISTS ( " + "SELECT AD_Sequence_ID " + "FROM AD_Sequence_No b " + "WHERE a.AD_Sequence_ID = b.AD_Sequence_ID " + "AND CalendarYear = ?)) ", get_TrxName()); insertStmt.setString(1, year); insertStmt.executeUpdate(); commit(); } catch (Exception ex) { rollback(); throw ex; } finally { DB.close(insertStmt); } return "Sequence No updated successfully"; } |
11
| Code Sample 1:
public static void encryptFile(String input, String output, String pwd) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(input); out = new CipherOutputStream(new FileOutputStream(output), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
Code Sample 2:
protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } } |
11
| Code Sample 1:
public static void httpOnLoad(String fileName, String urlpath) throws Exception { URL url = new URL(urlpath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); int responseCode = conn.getResponseCode(); System.err.println("Code : " + responseCode); System.err.println("getResponseMessage : " + conn.getResponseMessage()); if (responseCode >= 400) { return; } int threadSize = 3; int fileLength = conn.getContentLength(); System.out.println("fileLength:" + fileLength); int block = fileLength / threadSize; int lastBlock = fileLength - (block * (threadSize - 1)); conn.disconnect(); File file = new File(fileName); RandomAccessFile randomFile = new RandomAccessFile(file, "rw"); randomFile.setLength(fileLength); randomFile.close(); for (int i = 2; i < 3; i++) { int startPosition = i * block; if (i == threadSize - 1) { block = lastBlock; } RandomAccessFile threadFile = new RandomAccessFile(file, "rw"); threadFile.seek(startPosition); new TestDownFile(url, startPosition, threadFile, block).start(); } }
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 copyFile(File sourceFile, File destFile, boolean overwrite) throws IOException, DirNotFoundException, FileNotFoundException, FileExistsAlreadyException { File destDir = new File(destFile.getParent()); if (!destDir.exists()) { throw new DirNotFoundException(destDir.getAbsolutePath()); } if (!sourceFile.exists()) { throw new FileNotFoundException(sourceFile.getAbsolutePath()); } if (!overwrite && destFile.exists()) { throw new FileExistsAlreadyException(destFile.getAbsolutePath()); } FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[8 * 1024]; int count = 0; do { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); in.close(); out.close(); }
Code Sample 2:
protected Properties loadFile(String fileName) { Properties prop = new Properties(); try { String packageName = getClass().getName(); packageName = packageName.substring(0, packageName.lastIndexOf(".")); String src = "src"; if (mavenBuild) { src = src + File.separator + "test" + File.separator + "resources"; } packageName = src + File.separator + packageName.replace('.', File.separatorChar); packageName += File.separator; packageName += fileName; URL url0 = new File(packageName).toURI().toURL(); final InputStream input = url0.openStream(); prop.load(input); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return prop; } |
00
| Code Sample 1:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { String req1xml = jTextArea1.getText(); java.net.URL url = new java.net.URL("http://217.34.8.235:8080/newgenlibctxt/PatronServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); java.io.OutputStream os = urlconn.getOutputStream(); java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8"); System.out.println(req1xml); try { java.io.FileOutputStream pw = new java.io.FileOutputStream("C:/log.txt"); pw.write(req1xml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } dos.write(req1xml); dos.flush(); dos.close(); System.out.println("url conn: " + urlconn.getContentEncoding() + " " + urlconn.getContentType()); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(gip)); String reqxml = ""; while (br.ready()) { String line = br.readLine(); reqxml += line; } try { java.io.FileOutputStream pw = new java.io.FileOutputStream("C:/log3.txt"); pw.write(reqxml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(); } }
Code Sample 2:
public String postDownloadRequest(String localFile) throws Exception { String responseString = ""; String requestString = ""; if (localFile == null) { error = true; errorStr = errorStr.concat("No local target for: " + currentFile.getRelativePath() + "\n"); return ""; } try { for (java.util.Iterator i = parameters.entrySet().iterator(); i.hasNext(); ) { java.util.Map.Entry e = (java.util.Map.Entry) i.next(); requestString = requestString + URLEncoder.encode((String) e.getKey(), "UTF-8") + "=" + URLEncoder.encode((String) e.getValue(), "UTF-8") + "&"; } URL url = new URL(urlString); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Length", String.valueOf(requestString.length())); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); connection.connect(); PrintWriter out = new PrintWriter(httpConn.getOutputStream()); out.println(requestString); out.close(); if (httpConn.HTTP_NOT_FOUND == httpConn.getResponseCode()) { error = true; errorStr = errorStr.concat("Cannot find file: " + currentFile.getRelativePath() + "\n"); return responseString; } String localFileName = new String(localFile); File f = new File(localFileName); File dir = new File(f.getParent()); dir.mkdirs(); FileOutputStream fis = new FileOutputStream(f); try { InputStream is = httpConn.getInputStream(); java.util.zip.GZIPInputStream gin = new java.util.zip.GZIPInputStream(new BufferedInputStream(is)); int temp; while ((temp = gin.read()) != -1) { fis.write(temp); } if (fis.getChannel().size() > 0) { fis.getChannel().truncate(fis.getChannel().size() - 1); } responseString = downloadDir + "/" + currentFile.getRelativePath(); is.close(); fis.close(); httpConn.disconnect(); } catch (IOException io) { error = true; errorStr = errorStr.concat("Cannot find file: " + currentFile.getRelativePath() + "\n"); return responseString; } } catch (java.net.ConnectException conne) { error = true; finished = true; errorStr = "Cannot connect to: " + urlString; } catch (java.io.InterruptedIOException e) { error = true; finished = true; errorStr = "Connection to Portal lost: communication is timeouted."; parentWorkflow.getMenuButtonEventHandler().stopAutomaticRefresh(); } catch (java.net.MalformedURLException e) { error = true; finished = true; errorStr = "Error in postDownloadRequest()"; } catch (Exception e) { e.printStackTrace(); error = true; finished = true; errorStr = "Error in Download: " + e.getMessage(); } return responseString; } |
11
| Code Sample 1:
public CopyAllDataToOtherFolderResponse CopyAllDataToOtherFolder(DPWSContext context, CopyAllDataToOtherFolder CopyAllDataInps) throws DPWSException { CopyAllDataToOtherFolderResponse cpyRp = new CopyAllDataToOtherFolderResponseImpl(); int hany = 0; String errorMsg = null; try { if ((rootDir == null) || (rootDir.length() == (-1))) { errorMsg = LocalStorVerify.ISNT_ROOTFLD; } else { String sourceN = CopyAllDataInps.getSourceName(); String targetN = CopyAllDataInps.getTargetName(); if (LocalStorVerify.isValid(sourceN) && LocalStorVerify.isValid(targetN)) { String srcDir = rootDir + File.separator + sourceN; String trgDir = rootDir + File.separator + targetN; if (LocalStorVerify.isLength(srcDir) && LocalStorVerify.isLength(trgDir)) { for (File fs : new File(srcDir).listFiles()) { File ft = new File(trgDir + '\\' + fs.getName()); FileChannel in = null, out = null; try { in = new FileInputStream(fs).getChannel(); out = new FileOutputStream(ft).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); hany++; } } } else { errorMsg = LocalStorVerify.FLD_TOOLNG; } } else { errorMsg = LocalStorVerify.ISNT_VALID; } } } catch (Throwable tr) { tr.printStackTrace(); errorMsg = tr.getMessage(); hany = (-1); } if (errorMsg != null) { } cpyRp.setNum(hany); return cpyRp; }
Code Sample 2:
private void copyFile(File file, File targetFile) { try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] tmp = new byte[8192]; int read = -1; while ((read = bis.read(tmp)) > 0) { bos.write(tmp, 0, read); } bis.close(); bos.close(); } catch (Exception e) { if (!targetFile.delete()) { System.err.println("Ups, created copy cant be deleted (" + targetFile.getAbsolutePath() + ")"); } } } |
00
| Code Sample 1:
public void load(String fileName) { BufferedReader bufReader; loaded = false; vector.removeAllElements(); try { if (fileName.startsWith("http:")) { URL url = new URL(fileName); bufReader = new BufferedReader(new InputStreamReader(url.openStream())); } else bufReader = new BufferedReader(new FileReader(fileName)); String inputLine; while ((inputLine = bufReader.readLine()) != null) { if (listener != null) listener.handleLine(inputLine); else vector.add(inputLine); } bufReader.close(); loaded = true; } catch (IOException e) { errorMsg = e.getMessage(); } }
Code Sample 2:
private HttpURLConnection getHttpURLConnection(String bizDocToExecute) { StringBuffer servletURL = new StringBuffer(); servletURL.append(getBaseServletURL()); servletURL.append("?_BIZVIEW=").append(bizDocToExecute); 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; } |
11
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void render(ServiceContext serviceContext) throws Exception { if (serviceContext.getTemplateName() == null) throw new Exception("no Template defined for service: " + serviceContext.getServiceInfo().getRefName()); File f = new File(serviceContext.getTemplateName()); serviceContext.getResponse().setContentLength((int) f.length()); InputStream in = new FileInputStream(f); IOUtils.copy(in, serviceContext.getResponse().getOutputStream(), 0, (int) f.length()); in.close(); } |
00
| Code Sample 1:
public static byte[] hashFile(File file) { long size = file.length(); long jump = (long) (size / (float) CHUNK_SIZE); MessageDigest digest; FileInputStream stream; try { stream = new FileInputStream(file); digest = MessageDigest.getInstance("SHA-256"); if (size < CHUNK_SIZE * 4) { readAndUpdate(size, stream, digest); } else { if (stream.skip(jump) != jump) return null; readAndUpdate(CHUNK_SIZE, stream, digest); if (stream.skip(jump - CHUNK_SIZE) != jump - CHUNK_SIZE) return null; readAndUpdate(CHUNK_SIZE, stream, digest); if (stream.skip(jump - CHUNK_SIZE) != jump - CHUNK_SIZE) return null; readAndUpdate(CHUNK_SIZE, stream, digest); digest.update(Long.toString(size).getBytes()); } return digest.digest(); } catch (FileNotFoundException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } catch (IOException e) { return null; } }
Code Sample 2:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } |
11
| Code Sample 1:
private File downloadPDB(String pdbId) { File tempFile = new File(path + "/" + pdbId + ".pdb.gz"); File pdbHome = new File(path); if (!pdbHome.canWrite()) { System.err.println("can not write to " + pdbHome); return null; } String ftp = String.format("ftp://ftp.ebi.ac.uk/pub/databases/msd/pdb_uncompressed/pdb%s.ent", pdbId.toLowerCase()); System.out.println("Fetching " + ftp); try { URL url = new URL(ftp); InputStream conn = url.openStream(); System.out.println("writing to " + tempFile); FileOutputStream outPut = new FileOutputStream(tempFile); GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut); PrintWriter pw = new PrintWriter(gzOutPut); BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn)); String line; while ((line = fileBuffer.readLine()) != null) { pw.println(line); } pw.flush(); pw.close(); outPut.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); return null; } return tempFile; }
Code Sample 2:
public String sendXml(URL url, String xmlMessage, boolean isResponseExpected) throws IOException { if (url == null) { throw new IllegalArgumentException("url == null"); } if (xmlMessage == null) { throw new IllegalArgumentException("xmlMessage == null"); } LOGGER.finer("url = " + url); LOGGER.finer("xmlMessage = :" + xmlMessage + ":"); LOGGER.finer("isResponseExpected = " + isResponseExpected); String answer = null; try { URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("Content-type", "text/xml"); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); Writer writer = null; try { writer = new OutputStreamWriter(urlConnection.getOutputStream()); writer.write(xmlMessage); writer.flush(); } finally { if (writer != null) { writer.close(); } } LOGGER.finer("message written"); StringBuilder sb = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); if (isResponseExpected) { String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine).append("\n"); } answer = sb.toString(); LOGGER.finer("response read"); } } catch (FileNotFoundException e) { LOGGER.log(Level.SEVERE, "No response", e); } finally { if (in != null) { in.close(); } } } catch (ConnectException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } LOGGER.finer("answer = :" + answer + ":"); return answer; } |
11
| Code Sample 1:
public void excluirCliente(String cpf) { PreparedStatement pstmt = null; String sql = "delete from cliente where cpf = ?"; try { pstmt = connection.prepareStatement(sql); pstmt.setString(1, cpf); pstmt.executeUpdate(); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao exclir ciente.", ex1); } throw new RuntimeException("Erro ao excluir cliente.", ex); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (SQLException ex) { throw new RuntimeException("Ocorreu um erro no banco de dados.", ex); } } }
Code Sample 2:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); 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 GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } } |
11
| Code Sample 1:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); 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); } }
Code Sample 2:
protected synchronized Long putModel(String table, String linkTable, String type, TupleBinding binding, LocatableModel model) { try { if (model.getId() != null && !"".equals(model.getId())) { ps7.setInt(1, Integer.parseInt(model.getId())); ps7.execute(); ps6.setInt(1, Integer.parseInt(model.getId())); ps6.execute(); } if (persistenceMethod == PostgreSQLStore.BYTEA) { ps1.setString(1, model.getContig()); ps1.setInt(2, model.getStartPosition()); ps1.setInt(3, model.getStopPosition()); ps1.setString(4, type); DatabaseEntry objData = new DatabaseEntry(); binding.objectToEntry(model, objData); ps1.setBytes(5, objData.getData()); ps1.executeUpdate(); } else if (persistenceMethod == PostgreSQLStore.OID || persistenceMethod == PostgreSQLStore.FIELDS) { ps1b.setString(1, model.getContig()); ps1b.setInt(2, model.getStartPosition()); ps1b.setInt(3, model.getStopPosition()); ps1b.setString(4, type); DatabaseEntry objData = new DatabaseEntry(); binding.objectToEntry(model, objData); int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE); LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE); obj.write(objData.getData()); obj.close(); ps1b.setInt(5, oid); ps1b.executeUpdate(); } ResultSet rs = null; PreparedStatement ps = conn.prepareStatement("select currval('" + table + "_" + table + "_id_seq')"); rs = ps.executeQuery(); int modelId = -1; if (rs != null) { if (rs.next()) { modelId = rs.getInt(1); } } rs.close(); ps.close(); for (String key : model.getTags().keySet()) { int tagId = -1; if (tags.get(key) != null) { tagId = tags.get(key); } else { ps2.setString(1, key); rs = ps2.executeQuery(); if (rs != null) { while (rs.next()) { tagId = rs.getInt(1); } } rs.close(); } if (tagId < 0) { ps3.setString(1, key); ps3.setString(2, model.getTags().get(key)); ps3.executeUpdate(); rs = ps4.executeQuery(); if (rs != null) { if (rs.next()) { tagId = rs.getInt(1); tags.put(key, tagId); } } rs.close(); } ps5.setInt(1, tagId); ps5.executeUpdate(); } conn.commit(); return (new Long(modelId)); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } e.printStackTrace(); System.err.println(e.getMessage()); } catch (Exception e) { try { conn.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } e.printStackTrace(); System.err.println(e.getMessage()); } return (null); } |
11
| Code Sample 1:
private void preprocessObjects(GeoObject[] objects) throws IOException { System.out.println("objects.length " + objects.length); for (int i = 0; i < objects.length; i++) { String fileName = objects[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("i: " + " world filename " + tmp); File worldFile = new File(tmp); if (worldFile.exists()) { BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); } } File file = new File(objects[i].getPath()); if (file.exists()) { System.out.println("object src file found "); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); objects[i].setPath(tmp); file = new File(fileName); if (file.exists()) { DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } } } }
Code Sample 2:
public void copyAffix(MailAffix affix, long mailId1, long mailId2) throws Exception { File file = new File(this.getResDir(mailId1) + affix.getAttachAlias()); if (file.exists()) { File file2 = new File(this.getResDir(mailId2) + affix.getAttachAlias()); if (!file2.exists()) { file2.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); in.close(); out.close(); } } else { log.debug(file.getAbsolutePath() + file.getName() + "�����ڣ������ļ�ʧ�ܣ���������"); } } |
00
| Code Sample 1:
public void refreshFileItem(YahooInfo legroup) throws Exception { String lapage = new String(""); String ledir = new String(""); Pattern pat; Matcher mat; Pattern pat2; Matcher mat2; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearItem(legroup); for (int i = 0; i < UrlList.size(); i++) { if (UrlList.get(i).getGroup().equals(legroup.getGroup()) && UrlList.get(i).getDir().startsWith(legroup.getDir())) { if (UrlList.get(i).isGroup()) { System.out.print(UrlList.get(i).getGroup() + " : "); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); conn = myurl.openConnection(); conn.connect(); System.out.println(conn.getHeaderField(0).toString()); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<li> <a href=\"(.+?)\".*?>Files</a></li>"); mat = pat.matcher(lapage); if (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), "/", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } } if (UrlList.get(i).isDir()) { System.out.println(UrlList.get(i).getGroup() + UrlList.get(i).getDir()); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); do { myurl = new URL(myurl.toString()); conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } System.out.print("p"); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?/)\">(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { ledir = new String(UrlList.get(i).getDir()); pat2 = Pattern.compile("([A-Za-z0-9]+)"); mat2 = pat2.matcher(mat.group(2)); while (mat2.find()) { ledir += mat2.group(1); } ledir += "/"; yi = new YahooInfo(UrlList.get(i).getGroup(), ledir, "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?yahoofs.+?)\".*?>(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), UrlList.get(i).getDir(), mat.group(2), myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } System.out.println(""); pat = Pattern.compile("<a href=\"(.+?)\">Next"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); } } } }
Code Sample 2:
private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } } |
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:
@Override protected HttpResponse<HttpURLConnection> execute(HttpRequest<HttpURLConnection> con) throws HttpRequestException { HttpURLConnection unwrap = con.unwrap(); try { unwrap.connect(); } catch (IOException e) { throw new HttpRequestException(e); } return new UrlHttpResponse(unwrap); } |
00
| Code Sample 1:
public static String getImportFileBody(String fileName, HttpSession session) { FTPClient ftp = new FTPClient(); CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); String fileTransferFolder = CofaxToolsServlet.fileTransferFolder; String importFTPServer = (String) user.workingPubConfigElementsHash.get("IMPORTFTPSERVER"); String importFTPLogin = (String) user.workingPubConfigElementsHash.get("IMPORTFTPLOGIN"); String importFTPPassword = (String) user.workingPubConfigElementsHash.get("IMPORTFTPPASSWORD"); String importFTPFilePath = (String) user.workingPubConfigElementsHash.get("IMPORTFTPFILEPATH"); String body = (""); try { int reply; ftp.connect(importFTPServer); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody connecting to server " + importFTPServer); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ("CofaxToolsFTP getImportFileBody ERROR: FTP server refused connection."); } else { ftp.login(importFTPLogin, importFTPPassword); } try { boolean change = ftp.changeWorkingDirectory(importFTPFilePath); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody changing to directory: " + importFTPFilePath); CofaxToolsUtil.log("Results: " + change); OutputStream output; output = new FileOutputStream(fileTransferFolder + fileName); boolean retrieve = ftp.retrieveFile(fileName, output); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody retrieving file: " + fileName); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody results: " + change); output.close(); body = CofaxToolsUtil.readFile(fileTransferFolder + fileName, true); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody deleting remote file: " + importFTPFilePath + fileName); boolean delete = ftp.deleteFile(importFTPFilePath + fileName); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody results: " + delete); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody disconnecting from server:" + importFTPServer); ftp.logout(); ftp.disconnect(); } catch (java.io.IOException e) { return ("CofaxToolsFTP getImportFileBody ERROR: cannot write file: " + fileName); } } catch (IOException e) { return ("CofaxToolsFTP getImportFileBody ERROR: could not connect to server: " + e); } return (body); }
Code Sample 2:
public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) { h = "0" + h; } hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } |
11
| Code Sample 1:
protected static boolean copyFile(File src, File dest) { try { if (!dest.exists()) { dest.createNewFile(); } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); byte[] temp = new byte[1024 * 8]; int readSize = 0; do { readSize = fis.read(temp); fos.write(temp, 0, readSize); } while (readSize == temp.length); temp = null; fis.close(); fos.flush(); fos.close(); } catch (Exception e) { return false; } return true; }
Code Sample 2:
public static void copyFile(File source, File destination, long copyLength) throws IOException { if (!source.exists()) { String message = "File " + source + " does not exist"; throw new FileNotFoundException(message); } if (destination.getParentFile() != null && !destination.getParentFile().exists()) { forceMkdir(destination.getParentFile()); } if (destination.exists() && !destination.canWrite()) { String message = "Unable to open file " + destination + " for writing."; throw new IOException(message); } if (source.getCanonicalPath().equals(destination.getCanonicalPath())) { String message = "Unable to write file " + source + " on itself."; throw new IOException(message); } if (copyLength == 0) { truncateFile(destination, 0); } FileInputStream input = null; FileOutputStream output = null; try { input = new FileInputStream(source); output = new FileOutputStream(destination); long lengthLeft = copyLength; byte[] buffer = new byte[(int) Math.min(BUFFER_LENGTH, lengthLeft + 1)]; int read; while (lengthLeft > 0) { read = input.read(buffer); if (read == -1) { break; } lengthLeft -= read; output.write(buffer, 0, read); } output.flush(); output.getFD().sync(); } finally { IOUtil.closeQuietly(input); IOUtil.closeQuietly(output); } destination.setLastModified(source.lastModified()); } |
00
| Code Sample 1:
public static String md(String passwd) { MessageDigest md5 = null; String digest = passwd; try { md5 = MessageDigest.getInstance("MD5"); md5.update(passwd.getBytes()); byte[] digestData = md5.digest(); digest = byteArrayToHex(digestData); } catch (NoSuchAlgorithmException e) { LOG.warn("MD5 not supported. Using plain string as password!"); } catch (Exception e) { LOG.warn("Digest creation failed. Using plain string as password!"); } return digest; }
Code Sample 2:
public void initGet() throws Exception { URL url = new URL(getURL()); con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Accept", "*/*"); con.setRequestProperty("Range", "bytes=" + getPosition() + "-" + getRangeEnd()); con.setUseCaches(false); con.connect(); setInputStream(con.getInputStream()); } |
11
| Code Sample 1:
public static void main(String[] args) throws IOException { System.out.println("Start filtering zgps..."); final Config config = ConfigUtils.loadConfig(args[0]); final String CONFIG_MODULE = "GPSFilterZGPS"; File sourceFileSelectedStages = new File(config.findParam(CONFIG_MODULE, "sourceFileSelectedStages")); File sourceFileZGPS = new File(config.findParam(CONFIG_MODULE, "sourceFileZGPS")); File targetFile = new File(config.findParam(CONFIG_MODULE, "targetFile")); System.out.println("Start reading selected stages..."); FilterZGPSSelectedStages selectedStages = new FilterZGPSSelectedStages(); selectedStages.createSelectedStages(sourceFileSelectedStages); System.out.println("Done. " + selectedStages.getSelectedStages().size() + " stages were stored"); System.out.println("Start reading and writing zgps..."); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFileZGPS))); BufferedWriter out = new BufferedWriter(new FileWriter(targetFile)); out.write(in.readLine()); out.newLine(); String lineFromInputFile; while ((lineFromInputFile = in.readLine()) != null) { String[] entries = lineFromInputFile.split("\t"); if (selectedStages.containsStage(Integer.parseInt(entries[0]), Integer.parseInt(entries[1]), Integer.parseInt(entries[2]))) { out.write(lineFromInputFile); out.newLine(); out.flush(); } } in.close(); out.close(); } catch (FileNotFoundException e) { System.out.println("Could not find source file for selected stages."); e.printStackTrace(); } catch (IOException e) { System.out.println("IO Exception while reading or writing zgps."); e.printStackTrace(); } System.out.println("Done."); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
00
| Code Sample 1:
private static void loadCommandList() { final URL url; try { url = IOUtils.getResource(null, PYTHON_MENU_FILE); } catch (final FileNotFoundException ex) { log.error("File '" + PYTHON_MENU_FILE + "': " + ex.getMessage()); return; } final List<String> cmdList = new ArrayList<String>(); try { final InputStream inputStream = url.openStream(); try { final Reader reader = new InputStreamReader(inputStream, IOUtils.MAP_ENCODING); try { final BufferedReader bufferedReader = new BufferedReader(reader); try { while (true) { final String inputLine = bufferedReader.readLine(); if (inputLine == null) { break; } final String line = inputLine.trim(); if (line.length() > 0 && !line.startsWith("#")) { final int k = line.indexOf('('); if (k > 0) { cmdList.add(line.substring(0, k) + "()"); } else { log.error("Parse error in " + url + ":"); log.error(" \"" + line + "\" missing '()'"); cmdList.add(line + "()"); } } } Collections.sort(cmdList, String.CASE_INSENSITIVE_ORDER); if (!cmdList.isEmpty()) { menuEntries = cmdList.toArray(new String[cmdList.size()]); } } finally { bufferedReader.close(); } } finally { reader.close(); } } finally { inputStream.close(); } } catch (final FileNotFoundException ex) { log.error("File '" + url + "' not found: " + ex.getMessage()); } catch (final EOFException ignored) { } catch (final UnsupportedEncodingException ex) { log.error("Cannot decode file '" + url + "': " + ex.getMessage()); } catch (final IOException ex) { log.error("Cannot read file '" + url + "': " + ex.getMessage()); } }
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; } |
00
| Code Sample 1:
protected static boolean checkVersion(String address) { Scanner scanner = null; try { URL url = new URL(address); InputStream iS = url.openStream(); scanner = new Scanner(iS); if (scanner == null && DEBUG) System.out.println("SCANNER NULL"); String firstLine = scanner.nextLine(); double latestVersion = Double.valueOf(firstLine.trim()); double thisVersion = JCards.VERSION; if (thisVersion >= latestVersion) { JCards.latestVersion = true; } else { displaySimpleAlert(null, JCards.VERSION_PREFIX + latestVersion + " is available online!\n" + "Look under the file menu for a link to the download site."); } } catch (Exception e) { if (VERBOSE || DEBUG) { System.out.println("Can't decide latest version"); e.printStackTrace(); } return false; } return true; }
Code Sample 2:
public String postData(String result, DefaultHttpClient httpclient) { try { HttpPost post = new HttpPost("http://3dforandroid.appspot.com/api/v1/note/create"); StringEntity se = new StringEntity(result); se.setContentEncoding(HTTP.UTF_8); se.setContentType("application/json"); post.setEntity(se); post.setHeader("Content-Type", "application/json"); post.setHeader("Accept", "*/*"); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); InputStream instream; instream = entity.getContent(); responseMessage = read(instream); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return responseMessage; } |
Subsets and Splits