label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
| Code Sample 1:
public byte process(ProcessorContext<PublishRequest> context) throws InterruptedException, ProcessorException { logger.info("MapTileChacheTask:process"); PublishRequest req = context.getItem().getEntity(); if (StringUtils.isEmpty(req.getBackMap())) return TaskState.STATE_TILE_CACHED; final PublicMapPost post; final GenericDAO<PublicMapPost> postDao = DAOFactory.createDAO(PublicMapPost.class); try { ReadOnlyTransaction.beginTransaction(); } catch (DatabaseException e) { logger.error("error", e); throw new ProcessorException(e); } int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); post = postDao.findUniqueByCriteria(Expression.eq("guid", req.getPostGuid())); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(post.getSWLat(), post.getSWLon()), new LatLngPoint(post.getNELat(), post.getNELon())); final String backMapGuid = "gst"; final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid); dstDir.mkdir(); for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) { final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z); final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z); for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) { NASAMapTile tile = new NASAMapTile((int) x, (int) y, z); XFile file = new XFile(dstDir, tile.toKeyString()); if (file.exists() && file.isFile()) continue; backTiles.add(tile); } } try { for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) throw new IllegalAccessException("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); } else throw new IllegalStateException("opened stream is null"); } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 100 == 0) { logger.info(numCachedTiles + " tiles cached"); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw new ProcessorException(e); } } catch (ProcessorException e) { logger.error("map tile caching has failed: ", e); throw e; } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw new ProcessorException(e); } finally { ReadOnlyTransaction.closeTransaction(); logger.info(numCachedTiles + " tiles cached"); } return TaskState.STATE_TILE_CACHED; }
Code Sample 2:
protected boolean writeFile(Interest outstandingInterest) throws IOException { File fileToWrite = ccnNameToFilePath(outstandingInterest.name()); Log.info("CCNFileProxy: extracted request for file: " + fileToWrite.getAbsolutePath() + " exists? ", fileToWrite.exists()); if (!fileToWrite.exists()) { Log.warning("File {0} does not exist. Ignoring request.", fileToWrite.getAbsoluteFile()); return false; } FileInputStream fis = null; try { fis = new FileInputStream(fileToWrite); } catch (FileNotFoundException fnf) { Log.warning("Unexpected: file we expected to exist doesn't exist: {0}!", fileToWrite.getAbsolutePath()); return false; } CCNTime modificationTime = new CCNTime(fileToWrite.lastModified()); ContentName versionedName = VersioningProfile.addVersion(new ContentName(_prefix, outstandingInterest.name().postfix(_prefix).components()), modificationTime); CCNFileOutputStream ccnout = new CCNFileOutputStream(versionedName, _handle); ccnout.addOutstandingInterest(outstandingInterest); byte[] buffer = new byte[BUF_SIZE]; int read = fis.read(buffer); while (read >= 0) { ccnout.write(buffer, 0, read); read = fis.read(buffer); } fis.close(); ccnout.close(); return true; } |
00
| Code Sample 1:
public URLConnection getResourceConnection(String name) throws ResourceException { if (context == null) throw new ResourceException("There is no ServletContext to get the requested resource"); URL url = null; try { url = context.getResource("/WEB-INF/scriptags/" + name); return url.openConnection(); } catch (Exception e) { throw new ResourceException(String.format("Resource '%s' could not be found (url: %s)", name, url), e); } }
Code Sample 2:
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(); } } |
11
| Code Sample 1:
public static String encodeFromFile(String filename) throws java.io.IOException, URISyntaxException { String encodedData = null; Base641.InputStream bis = null; File file; try { URL url = new URL(filename); URLConnection conn = url.openConnection(); file = new File("myfile.doc"); java.io.InputStream inputStream = (java.io.InputStream) conn.getInputStream(); FileOutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; int length = 0; int numBytes = 0; bis = new Base641.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base641.ENCODE); while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } encodedData = new String(buffer, 0, length, Base641.PREFERRED_ENCODING); } catch (java.io.IOException e) { throw e; } finally { try { bis.close(); } catch (Exception e) { } } return encodedData; }
Code Sample 2:
public static void copyFile(String fromPath, String toPath) { try { File inputFile = new File(fromPath); String dirImg = (new File(toPath)).getParent(); File tmp = new File(dirImg); if (!tmp.exists()) { tmp.mkdir(); } File outputFile = new File(toPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); } } |
00
| Code Sample 1:
private void gravaOp(Vector<?> op) { PreparedStatement ps = null; String sql = null; ResultSet rs = null; int seqop = 0; Date dtFabrOP = null; try { sql = "SELECT MAX(SEQOP) FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { seqop = rs.getInt(1) + 1; } rs.close(); ps.close(); con.commit(); sql = "SELECT DTFABROP FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, txtSeqOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { dtFabrOP = rs.getDate(1); } rs.close(); ps.close(); con.commit(); sql = "INSERT INTO PPOP (CODEMP,CODFILIAL,CODOP,SEQOP,CODEMPPD,CODFILIALPD,CODPROD,SEQEST,DTFABROP," + "QTDPREVPRODOP,QTDFINALPRODOP,DTVALIDPDOP,CODEMPLE,CODFILIALLE,CODLOTE,CODEMPTM,CODFILIALTM,CODTIPOMOV," + "CODEMPAX,CODFILIALAX,CODALMOX,CODEMPOPM,CODFILIALOPM,CODOPM,SEQOPM,QTDDISTIOP,QTDSUGPRODOP)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, seqop); ps.setInt(5, Aplicativo.iCodEmp); ps.setInt(6, ListaCampos.getMasterFilial("PPESTRUTURA")); ps.setInt(7, ((Integer) op.elementAt(4)).intValue()); ps.setInt(8, ((Integer) op.elementAt(6)).intValue()); ps.setDate(9, dtFabrOP); ps.setFloat(10, ((BigDecimal) op.elementAt(7)).floatValue()); ps.setFloat(11, 0); ps.setDate(12, (Funcoes.strDateToSqlDate((String) op.elementAt(11)))); ps.setInt(13, Aplicativo.iCodEmp); ps.setInt(14, ListaCampos.getMasterFilial("EQLOTE")); ps.setString(15, ((String) op.elementAt(10))); ps.setInt(16, Aplicativo.iCodEmp); ps.setInt(17, ListaCampos.getMasterFilial("EQTIPOMOV")); ps.setInt(18, buscaTipoMov()); ps.setInt(19, ((Integer) op.elementAt(13)).intValue()); ps.setInt(20, ((Integer) op.elementAt(14)).intValue()); ps.setInt(21, ((Integer) op.elementAt(12)).intValue()); ps.setInt(22, Aplicativo.iCodEmp); ps.setInt(23, ListaCampos.getMasterFilial("PPOP")); ps.setInt(24, txtCodOP.getVlrInteger().intValue()); ps.setInt(25, txtSeqOP.getVlrInteger().intValue()); ps.setFloat(26, ((BigDecimal) op.elementAt(9)).floatValue()); ps.setFloat(27, ((BigDecimal) op.elementAt(7)).floatValue()); ps.executeUpdate(); ps.close(); con.commit(); geraRMA(seqop); } catch (SQLException e) { Funcoes.mensagemErro(null, "Erro ao gerar OP's de distribui��o!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException eb) { } } }
Code Sample 2:
static byte[] genDigest(String pad, byte[] passwd) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance(DIGEST_ALGORITHM); digest.update(pad.getBytes()); digest.update(passwd); return digest.digest(); } |
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 generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { log.error("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); } |
11
| Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
Code Sample 2:
public static void 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:
private int writeTraceFile(final File destination_file, final String trace_file_name, final String trace_file_path) { URL url = null; BufferedInputStream is = null; FileOutputStream fo = null; BufferedOutputStream os = null; int b = 0; if (destination_file == null) { return 0; } try { url = new URL("http://" + trace_file_path + "/" + trace_file_name); is = new BufferedInputStream(url.openStream()); fo = new FileOutputStream(destination_file); os = new BufferedOutputStream(fo); while ((b = is.read()) != -1) { os.write(b); } os.flush(); is.close(); os.close(); } catch (Exception e) { System.err.println(url.toString()); Utilities.unexpectedException(e, this, CONTACT); return 0; } return 1; }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
00
| Code Sample 1:
static void invalidSlave(String msg, Socket sock) throws IOException { BufferedReader _sinp = null; PrintWriter _sout = null; try { _sout = new PrintWriter(sock.getOutputStream(), true); _sinp = new BufferedReader(new InputStreamReader(sock.getInputStream())); _sout.println(msg); logger.info("NEW< " + msg); String txt = AsyncSlaveListener.readLine(_sinp, 30); String sname = ""; String spass = ""; String shash = ""; try { String[] items = txt.split(" "); sname = items[1].trim(); spass = items[2].trim(); shash = items[3].trim(); } catch (Exception e) { throw new IOException("Slave Inititalization Faailed"); } String pass = sname + spass + _pass; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(pass.getBytes()); String hash = AsyncSlaveListener.hash2hex(md5.digest()).toLowerCase(); if (!hash.equals(shash)) { throw new IOException("Slave Inititalization Faailed"); } } catch (Exception e) { } throw new IOException("Slave Inititalization Faailed"); }
Code Sample 2:
public static ByteBuffer readShaderBinary(Class context, String path) { try { URL url = Locator.getResource(context, path); if (url == null) { return null; } return StreamUtil.readAll2Buffer(new BufferedInputStream(url.openStream())); } catch (IOException e) { throw new RuntimeException(e); } } |
00
| Code Sample 1:
private File uploadFile(InputStream inputStream, File file) { FileOutputStream fileOutputStream = null; try { File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } FileUtils.touch(file); fileOutputStream = new FileOutputStream(file); IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new FileOperationException("Failed to save uploaded image", e); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { LOGGER.warn("Failed to close resources on uploaded file", e); } } return file; }
Code Sample 2:
void loadImage(Frame frame, URL url) throws Exception { URLConnection conn = url.openConnection(); String mimeType = conn.getContentType(); long length = conn.getContentLength(); InputStream is = conn.getInputStream(); loadImage(frame, is, length, mimeType); } |
00
| Code Sample 1:
public static String getMD5Str(String source) { String s = null; char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(source.getBytes()); byte tmp[] = md.digest(); char str[] = new char[16 * 2]; int k = 0; for (int i = 0; i < 16; i++) { byte byte0 = tmp[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } s = new String(str); } catch (Exception e) { e.printStackTrace(); } return s; }
Code Sample 2:
private static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { if (!destFile.createNewFile()) { throw new IOException("Destination file cannot be created: " + destFile.getPath()); } } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } |
00
| Code Sample 1:
public void putChunk(String chunk) throws JacsonException { try { URL url = new URL(chunk); InputStream is = url.openStream(); if (inverse) drain.putChunk(chunk); is.close(); } catch (IOException broken) { if (!inverse) drain.putChunk(chunk); } }
Code Sample 2:
public static String getStringFromAFileAtURL(String anURL) { String htmlCode = "<html><body></body></html>"; try { URL url = new URL(anURL); URLConnection urlConnection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine = ""; htmlCode = ""; while ((inputLine = in.readLine()) != null) htmlCode += inputLine + "\n"; in.close(); } catch (Exception e) { logs.info("URLResolver : lien mort"); JOptionPane.showMessageDialog(null, "lien mort"); return "<html><body></body></html>"; } return checkXMLTagsLowerCase(htmlCode); } |
11
| Code Sample 1:
public static long writeInputStreamToOutputStream(final InputStream in, final OutputStream out) { long size = 0; try { size = IOUtils.copyLarge(in, out); } catch (IOException e1) { e1.printStackTrace(); } return size; }
Code Sample 2:
public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = dest.getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } |
00
| Code Sample 1:
public boolean executeUpdate(String strSql, HashMap<Integer, Object> prams) throws SQLException, ClassNotFoundException { getConnection(); boolean flag = false; try { pstmt = con.prepareStatement(strSql); setParamet(pstmt, prams); logger.info("###############::执行SQL语句操作(更新数据 有参数):" + strSql); if (0 < pstmt.executeUpdate()) { close_DB_Object(); flag = true; con.commit(); } } catch (SQLException ex) { logger.info("###############Error DBManager Line121::执行SQL语句操作(更新数据 无参数):" + strSql + "失败!"); flag = false; con.rollback(); throw ex; } catch (ClassNotFoundException ex) { logger.info("###############Error DBManager Line152::执行SQL语句操作(更新数据 无参数):" + strSql + "失败! 参数设置类型错误!"); con.rollback(); throw ex; } return flag; }
Code Sample 2:
public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } } |
00
| Code Sample 1:
public int download() { FTPClient client = null; URL url = null; try { client = new FTPClient(); url = new URL(ratingsUrl); if (log.isDebugEnabled()) log.debug("Downloading " + url); client.connect(url.getHost()); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { if (log.isErrorEnabled()) log.error("Connection to " + url + " refused"); return RESULT_CONNECTION_REFUSED; } if (log.isDebugEnabled()) log.debug("Logging in l:" + getUserName() + " p:" + getPassword()); client.login(getUserName(), getPassword()); client.changeWorkingDirectory(url.getPath()); FTPFile[] files = client.listFiles(url.getPath()); if ((files == null) || (files.length != 1)) throw new FileNotFoundException("No remote file"); FTPFile remote = files[0]; if (log.isDebugEnabled()) log.debug("Remote file data: " + remote); File local = new File(getOutputFile()); if (local.exists()) { if ((local.lastModified() == remote.getTimestamp().getTimeInMillis())) { if (log.isDebugEnabled()) log.debug("File " + local.getAbsolutePath() + " is not changed on the server"); return RESULT_NO_NEW_FILE; } } if (log.isDebugEnabled()) log.debug("Setting binary transfer modes"); client.mode(FTPClient.BINARY_FILE_TYPE); client.setFileType(FTPClient.BINARY_FILE_TYPE); OutputStream fos = new FileOutputStream(local); boolean result = client.retrieveFile(url.getPath(), fos); if (log.isDebugEnabled()) log.debug("The transfer result is :" + result); fos.flush(); fos.close(); local.setLastModified(remote.getTimestamp().getTimeInMillis()); if (result) uncompress(); if (result) return RESULT_OK; else return RESULT_TRANSFER_ERROR; } catch (MalformedURLException e) { return RESULT_ERROR; } catch (SocketException e) { return RESULT_ERROR; } catch (FileNotFoundException e) { return RESULT_ERROR; } catch (IOException e) { return RESULT_ERROR; } finally { if (client != null) { try { if (log.isDebugEnabled()) log.debug("Logging out"); client.logout(); } catch (Exception e) { } try { if (log.isDebugEnabled()) log.debug("Disconnecting"); client.disconnect(); } catch (Exception e) { } } } }
Code Sample 2:
public void run() { try { File f = new File(repository + fileName); if (!f.exists()) { URL url = new URL(urlString); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream dis = url.openStream(); File dir = new File(repository); if (!dir.exists()) dir.mkdirs(); f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); byte[] buffer = new byte[4096]; int len = 0; while ((len = dis.read(buffer)) > -1) fos.write(buffer, 0, len); fos.close(); dis.close(); } fireFileDownloadedListener(fileName); } catch (Exception e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public UpdaterView(SingleFrameApplication app, String[] args) { super(app); if (args.length != 3) { System.out.println("Args must be passed."); System.exit(1); } else { currentVersion = Double.parseDouble(args[0]); currentDBVersion = Double.parseDouble(args[1]); dbAdmin = args[2].equals("true") ? true : false; } initComponents(); try { URL url = new URL(BASE_URL + "version.txt"); InputStream in = url.openStream(); BufferedInputStream buffIn = new BufferedInputStream(in); String tmp = ""; int data = buffIn.read(); while (data != -1) { tmp = tmp.concat(Character.toString((char) data)); data = buffIn.read(); } String[] versionEntries = tmp.split("\n"); if (versionEntries.length > 0) { String[] components = versionEntries[0].split(":"); if (dbAdmin || Double.parseDouble(components[4]) == currentDBVersion) { byteCount = Integer.parseInt(components[2]); lblCurrent.setText(new Double(currentVersion).toString()); lblLatest.setText(components[0]); latestVersionNum = Double.parseDouble(components[0]); lblNotes.setText("<html>" + components[1]); md5Hash = components[3]; latestDBVersion = Double.parseDouble(components[4]); upgradeURL = components[5]; progressBar.setMaximum(byteCount); if (dbAdmin && Double.parseDouble(components[4]) > currentDBVersion) { schemaUpdatesNeeded = true; schemaChanges.addFirst(latestDBVersion); double lastVersion = latestDBVersion; for (int i = 1; i < versionEntries.length; i++) { components = versionEntries[i].split(":"); double nextVers = Double.parseDouble(components[4]); if (nextVers != currentDBVersion) { if (lastVersion != nextVers) { schemaChanges.addFirst(nextVers); lastVersion = nextVers; } } else { schemaChanges.addFirst(currentDBVersion); break; } } } } else { for (int i = 1; i < versionEntries.length; i++) { components = versionEntries[i].split(":"); if (Double.parseDouble(components[4]) == currentDBVersion) { byteCount = Integer.parseInt(components[2]); lblCurrent.setText(new Double(currentVersion).toString()); lblLatest.setText(components[0]); latestVersionNum = Double.parseDouble(components[0]); lblNotes.setText("<html>" + components[1]); md5Hash = components[3]; latestDBVersion = Double.parseDouble(components[4]); upgradeURL = components[5]; progressBar.setMaximum(byteCount); schemaUpdatesNeeded = true; break; } } } } else { throw new InvalidUpdateFileFormatException("File Format is Wrong."); } if (latestVersionNum == currentVersion) { if (schemaUpdatesNeeded) { javax.swing.JOptionPane.showMessageDialog(super.getComponent(), "Updates are available but they require database changes. Please contact your system administrator to perform the upgrade.", "Myopa Updater", javax.swing.JOptionPane.INFORMATION_MESSAGE); } else { javax.swing.JOptionPane.showMessageDialog(super.getComponent(), "No Updates are available - your software is up to date!", "Myopa Updater", javax.swing.JOptionPane.INFORMATION_MESSAGE); } System.exit(0); } else { jButton1.setEnabled(true); } } catch (InvalidUpdateFileFormatException e) { } catch (MalformedURLException e) { System.out.println("EXCP " + e); } catch (IOException io) { System.out.println("IO" + io); } ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String) (evt.getNewValue()); statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer) (evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); }
Code Sample 2:
public static void main(String[] args) { boolean rotateLeft = false; boolean rotateRight = false; boolean exclude = false; boolean reset = false; float quality = 0f; int thumbArea = 12000; for (int i = 0; i < args.length; i++) { if (args[i].equals("-rotl")) rotateLeft = true; else if (args[i].equals("-rotr")) rotateRight = true; else if (args[i].equals("-exclude")) exclude = true; else if (args[i].equals("-reset")) reset = true; else if (args[i].equals("-quality")) quality = Float.parseFloat(args[++i]); else if (args[i].equals("-area")) thumbArea = Integer.parseInt(args[++i]); else { File f = new File(args[i]); try { Tools t = new Tools(f); if (exclude) { URL url = t.getClass().getResource("exclude.jpg"); InputStream is = url.openStream(); File dest = t.getExcludeFile(); OutputStream os = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); t.getOutFile().delete(); t.getThumbFile().delete(); System.exit(0); } if (reset) { t.getOutFile().delete(); t.getThumbFile().delete(); t.getExcludeFile().delete(); System.exit(0); } if (quality > 0) t.setQuality(quality); if (t.getType() == Tools.THUMB || t.getType() == Tools.EXCLUDE) t.load(t.getBaseFile()); else t.load(t.getSourceFile()); File out = t.getOutFile(); if (rotateLeft) t.rotateLeft(); else if (rotateRight) t.rotateRight(); t.save(out); t.getExcludeFile().delete(); t.getThumbFile().delete(); System.exit(0); } catch (Throwable e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "The operation could not be performed", "JPhotoAlbum", JOptionPane.ERROR_MESSAGE); System.exit(1); } } } } |
11
| Code Sample 1:
protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); }
Code Sample 2:
private void sendFile(File file, HttpServletResponse response) throws IOException { response.setContentLength((int) file.length()); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(inputStream); } } |
11
| Code Sample 1:
private static String digest(String myinfo) { try { MessageDigest alga = MessageDigest.getInstance("SHA"); alga.update(myinfo.getBytes()); byte[] digesta = alga.digest(); return byte2hex(digesta); } catch (Exception ex) { return myinfo; } }
Code Sample 2:
public static synchronized String hash(String plaintext) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { return null; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return null; } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); } |
00
| Code Sample 1:
public void createPartControl(Composite parent) { FormToolkit toolkit; toolkit = new FormToolkit(parent.getDisplay()); form = toolkit.createForm(parent); form.setText("Apple Inc."); toolkit.decorateFormHeading(form); form.getBody().setLayout(new GridLayout()); chart = createChart(); final DateAxis dateAxis = new DateAxis(); viewer = new GraphicalViewerImpl(); viewer.setRootEditPart(new ScalableRootEditPart()); viewer.setEditPartFactory(new ChartEditPartFactory(dateAxis)); viewer.createControl(form.getBody()); viewer.setContents(chart); viewer.setEditDomain(new EditDomain()); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { System.err.println("selectionChanged " + event.getSelection()); } }); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { deleteAction.update(); } }); ActionRegistry actionRegistry = new ActionRegistry(); createActions(actionRegistry); ContextMenuProvider cmProvider = new BlockContextMenuProvider(viewer, actionRegistry); viewer.setContextMenu(cmProvider); getSite().setSelectionProvider(viewer); deleteAction.setSelectionProvider(viewer); viewer.getEditDomain().getCommandStack().addCommandStackEventListener(new CommandStackEventListener() { public void stackChanged(CommandStackEvent event) { undoAction.setEnabled(viewer.getEditDomain().getCommandStack().canUndo()); redoAction.setEnabled(viewer.getEditDomain().getCommandStack().canRedo()); } }); Data data = Data.getData(); chart.setInput(data); DateRange dateRange = new DateRange(0, 50); dateAxis.setDates(data.date); dateAxis.setSelectedRange(dateRange); slider = new Slider(form.getBody(), SWT.NONE); slider.setMinimum(0); slider.setMaximum(data.close.length - 1); slider.setSelection(dateRange.start); slider.setThumb(dateRange.length); slider.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { DateRange r = new DateRange(slider.getSelection(), slider.getThumb()); dateAxis.setSelectedRange(r); } }); final Scale spinner = new Scale(form.getBody(), SWT.NONE); spinner.setMinimum(5); spinner.setMaximum(data.close.length - 1); spinner.setSelection(dateRange.length); spinner.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { slider.setThumb(spinner.getSelection()); DateRange r = new DateRange(slider.getSelection(), slider.getThumb()); dateAxis.setSelectedRange(r); } }); GridDataFactory.defaultsFor(viewer.getControl()).grab(true, true).align(GridData.FILL, GridData.FILL).applyTo(viewer.getControl()); GridDataFactory.defaultsFor(slider).grab(true, false).align(GridData.FILL, GridData.FILL).grab(true, false).applyTo(slider); GridDataFactory.defaultsFor(spinner).grab(true, false).align(GridData.FILL, GridData.FILL).grab(true, false).applyTo(spinner); getSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this); }
Code Sample 2:
public void login(LoginData loginData) throws ConnectionEstablishException, AccessDeniedException { try { int reply; this.ftpClient.connect(loginData.getFtpServer()); reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); throw (new ConnectionEstablishException("FTP server refused connection.")); } } catch (IOException e) { if (this.ftpClient.isConnected()) { try { this.ftpClient.disconnect(); } catch (IOException f) { } } e.printStackTrace(); throw (new ConnectionEstablishException("Could not connect to server.", e)); } try { if (!this.ftpClient.login(loginData.getFtpBenutzer(), loginData.getFtpPasswort())) { this.logout(); throw (new AccessDeniedException("Could not login into server.")); } } catch (IOException ioe) { ioe.printStackTrace(); throw (new AccessDeniedException("Could not login into server.", ioe)); } } |
00
| Code Sample 1:
public final void copyFile(final File fromFile, final File toFile) throws IOException { this.createParentPathIfNeeded(toFile); final FileChannel sourceChannel = new FileInputStream(fromFile).getChannel(); final FileChannel targetChannel = new FileOutputStream(toFile).getChannel(); final long sourceFileSize = sourceChannel.size(); sourceChannel.transferTo(0, sourceFileSize, targetChannel); }
Code Sample 2:
public static FTPClient createConnection(String hostname, int port, char[] username, char[] password, String workingDirectory, FileSystemOptions fileSystemOptions) throws FileSystemException { if (username == null) username = "anonymous".toCharArray(); if (password == null) password = "anonymous".toCharArray(); try { final FTPClient client = new FTPClient(); String key = FtpFileSystemConfigBuilder.getInstance().getEntryParser(fileSystemOptions); if (key != null) { FTPClientConfig config = new FTPClientConfig(key); String serverLanguageCode = FtpFileSystemConfigBuilder.getInstance().getServerLanguageCode(fileSystemOptions); if (serverLanguageCode != null) config.setServerLanguageCode(serverLanguageCode); String defaultDateFormat = FtpFileSystemConfigBuilder.getInstance().getDefaultDateFormat(fileSystemOptions); if (defaultDateFormat != null) config.setDefaultDateFormatStr(defaultDateFormat); String recentDateFormat = FtpFileSystemConfigBuilder.getInstance().getRecentDateFormat(fileSystemOptions); if (recentDateFormat != null) config.setRecentDateFormatStr(recentDateFormat); String serverTimeZoneId = FtpFileSystemConfigBuilder.getInstance().getServerTimeZoneId(fileSystemOptions); if (serverTimeZoneId != null) config.setServerTimeZoneId(serverTimeZoneId); String[] shortMonthNames = FtpFileSystemConfigBuilder.getInstance().getShortMonthNames(fileSystemOptions); if (shortMonthNames != null) { StringBuffer shortMonthNamesStr = new StringBuffer(40); for (int i = 0; i < shortMonthNames.length; i++) { if (shortMonthNamesStr.length() > 0) shortMonthNamesStr.append("|"); shortMonthNamesStr.append(shortMonthNames[i]); } config.setShortMonthNames(shortMonthNamesStr.toString()); } client.configure(config); } FTPFileEntryParserFactory myFactory = FtpFileSystemConfigBuilder.getInstance().getEntryParserFactory(fileSystemOptions); if (myFactory != null) client.setParserFactory(myFactory); try { client.connect(hostname, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) throw new FileSystemException("vfs.provider.ftp/connect-rejected.error", hostname); if (!client.login(UserAuthenticatorUtils.toString(username), UserAuthenticatorUtils.toString(password))) throw new FileSystemException("vfs.provider.ftp/login.error", new Object[] { hostname, UserAuthenticatorUtils.toString(username) }, null); if (!client.setFileType(FTP.BINARY_FILE_TYPE)) throw new FileSystemException("vfs.provider.ftp/set-binary.error", hostname); Integer dataTimeout = FtpFileSystemConfigBuilder.getInstance().getDataTimeout(fileSystemOptions); if (dataTimeout != null) client.setDataTimeout(dataTimeout.intValue()); try { FtpFileSystemConfigBuilder.getInstance().setHomeDir(fileSystemOptions, client.printWorkingDirectory()); } catch (IOException ex) { throw new FileSystemException("Error obtaining working directory!"); } Boolean userDirIsRoot = FtpFileSystemConfigBuilder.getInstance().getUserDirIsRoot(fileSystemOptions); if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue())) if (!client.changeWorkingDirectory(workingDirectory)) throw new FileSystemException("vfs.provider.ftp/change-work-directory.error", workingDirectory); Boolean passiveMode = FtpFileSystemConfigBuilder.getInstance().getPassiveMode(fileSystemOptions); if (passiveMode != null && passiveMode.booleanValue()) client.enterLocalPassiveMode(); } catch (final IOException e) { if (client.isConnected()) client.disconnect(); throw e; } return client; } catch (final Exception exc) { throw new FileSystemException("vfs.provider.ftp/connect.error", new Object[] { hostname }, exc); } } |
11
| Code Sample 1:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config = getServletConfig(); ServletContext context = config.getServletContext(); try { String driver = context.getInitParameter("driver"); Class.forName(driver); String dbURL = context.getInitParameter("db"); String username = context.getInitParameter("username"); String password = ""; connection = DriverManager.getConnection(dbURL, username, password); } catch (ClassNotFoundException e) { System.out.println("Database driver not found."); } catch (SQLException e) { System.out.println("Error opening the db connection: " + e.getMessage()); } String action = ""; HttpSession session = request.getSession(); session.setMaxInactiveInterval(300); if (request.getParameter("action") != null) { action = request.getParameter("action"); } else { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp"); dispatcher.forward(request, response); return; } if (action.equals("login")) { String username = request.getParameter("username"); String password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { error = "There was an error encrypting password."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { error = "There was an error encrypting password."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } String encrypted_password = (new BASE64Encoder()).encode(md.digest()); try { String sql = "SELECT * FROM person WHERE email LIKE '" + username + "' AND password='" + encrypted_password + "'"; dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); if (dbResultSet.next()) { Person person = new Person(dbResultSet.getString("fname"), dbResultSet.getString("lname"), dbResultSet.getString("address1"), dbResultSet.getString("address2"), dbResultSet.getString("city"), dbResultSet.getString("state"), dbResultSet.getString("zip"), dbResultSet.getString("email"), dbResultSet.getString("password"), dbResultSet.getInt("is_admin")); String member_type = dbResultSet.getString("member_type"); String person_id = Integer.toString(dbResultSet.getInt("id")); session.setAttribute("person", person); session.setAttribute("member_type", member_type); session.setAttribute("person_id", person_id); } else { notice = "Your username and/or password is incorrect."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } catch (SQLException e) { error = "There was an error trying to login. (SQL Statement)"; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Unable to log you in. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp"); dispatcher.forward(request, response); return; } } |
00
| Code Sample 1:
private static void copyContent(final File srcFile, final File dstFile, final boolean gzipContent) throws IOException { final File dstFolder = dstFile.getParentFile(); dstFolder.mkdirs(); if (!dstFolder.exists()) { throw new RuntimeException("Unable to create the folder " + dstFolder.getAbsolutePath()); } final InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(dstFile); if (gzipContent) { out = new GZIPOutputStream(out); } try { final byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { in.close(); out.close(); } }
Code Sample 2:
public static Cursor load(URL url, String descriptor) { if (url == null) { log.log(Level.WARNING, "Trying to load a cursor with a null url."); return null; } String cursorFile = url.getFile(); BufferedReader reader = null; int lineNumber = 0; try { DirectoryTextureLoader loader; URL cursorUrl; if (cursorFile.endsWith(cursorDescriptorFile)) { cursorUrl = url; Cursor cached = cursorCache.get(url); if (cached != null) return cached; reader = new BufferedReader(new InputStreamReader(url.openStream())); loader = new DirectoryTextureLoader(url, false); } else if (cursorFile.endsWith(cursorArchiveFile)) { loader = new DirectoryTextureLoader(url, true); if (descriptor == null) descriptor = defaultDescriptorFile; cursorUrl = loader.makeUrl(descriptor); Cursor cached = cursorCache.get(url); if (cached != null) return cached; ZipInputStream zis = new ZipInputStream(url.openStream()); ZipEntry entry; boolean found = false; while ((entry = zis.getNextEntry()) != null) { if (descriptor.equals(entry.getName())) { found = true; break; } } if (!found) { throw new IOException("Descriptor file \"" + descriptor + "\" was not found."); } reader = new BufferedReader(new InputStreamReader(zis)); } else { log.log(Level.WARNING, "Invalid cursor fileName \"{0}\".", cursorFile); return null; } Cursor cursor = new Cursor(); cursor.url = cursorUrl; List<Integer> delays = new ArrayList<Integer>(); List<String> frameFileNames = new ArrayList<String>(); Map<String, Texture> textureCache = new HashMap<String, Texture>(); String line; while ((line = reader.readLine()) != null) { lineNumber++; int commentIndex = line.indexOf(commentString); if (commentIndex != -1) { line = line.substring(0, commentIndex); } StringTokenizer tokens = new StringTokenizer(line, delims); if (!tokens.hasMoreTokens()) continue; String prefix = tokens.nextToken(); if (prefix.equals(hotSpotXPrefix)) { cursor.hotSpotOffset.x = Integer.valueOf(tokens.nextToken()); } else if (prefix.equals(hotSpotYPrefix)) { cursor.hotSpotOffset.y = Integer.valueOf(tokens.nextToken()); } else if (prefix.equals(timePrefix)) { delays.add(Integer.valueOf(tokens.nextToken())); if (tokens.nextToken().equals(imagePrefix)) { String file = tokens.nextToken(""); file = file.substring(file.indexOf('=') + 1); file.trim(); frameFileNames.add(file); if (textureCache.get(file) == null) { textureCache.put(file, loader.loadTexture(file)); } } else { throw new NoSuchElementException(); } } } cursor.frameFileNames = frameFileNames.toArray(new String[0]); cursor.textureCache = textureCache; cursor.delays = new int[delays.size()]; cursor.images = new Image[frameFileNames.size()]; cursor.textures = new Texture[frameFileNames.size()]; for (int i = 0; i < cursor.frameFileNames.length; i++) { cursor.textures[i] = textureCache.get(cursor.frameFileNames[i]); cursor.images[i] = cursor.textures[i].getImage(); cursor.delays[i] = delays.get(i); } if (delays.size() == 1) cursor.delays = null; if (cursor.images.length == 0) { log.log(Level.WARNING, "The cursor has no animation frames."); return null; } cursor.width = cursor.images[0].getWidth(); cursor.height = cursor.images[0].getHeight(); cursorCache.put(cursor.url, cursor); return cursor; } catch (MalformedURLException mue) { log.log(Level.WARNING, "Unable to load cursor.", mue); } catch (IOException ioe) { log.log(Level.WARNING, "Unable to load cursor.", ioe); } catch (NumberFormatException nfe) { log.log(Level.WARNING, "Numerical error while parsing the " + "file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } catch (IndexOutOfBoundsException ioobe) { log.log(Level.WARNING, "Error, \"=\" expected in the file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } catch (NoSuchElementException nsee) { log.log(Level.WARNING, "Error while parsing the file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { log.log(Level.SEVERE, "Unable to close the steam.", ioe); } } } return null; } |
11
| Code Sample 1:
public static void unzipFile(File zipFile, File destFile, boolean removeSrcFile) throws Exception { ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipentry = zipinputstream.getNextEntry(); int BUFFER_SIZE = 4096; while (zipentry != null) { String entryName = zipentry.getName(); log.info("<<<<<< ZipUtility.unzipFile - Extracting: " + zipentry.getName()); File newFile = null; if (destFile.isDirectory()) newFile = new File(destFile, entryName); else newFile = destFile; if (zipentry.isDirectory() || entryName.endsWith(File.separator + ".")) { newFile.mkdirs(); } else { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); byte[] bufferArray = buffer.array(); FileUtilities.createDirectory(newFile.getParentFile()); FileChannel destinationChannel = new FileOutputStream(newFile).getChannel(); while (true) { buffer.clear(); int lim = zipinputstream.read(bufferArray); if (lim == -1) break; buffer.flip(); buffer.limit(lim); destinationChannel.write(buffer); } destinationChannel.close(); zipinputstream.closeEntry(); } zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); if (removeSrcFile) { if (zipFile.exists()) zipFile.delete(); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
public String getHtmlCode(String urlString) { StringBuffer result = new StringBuffer(); BufferedReader in = null; try { URL url = new URL((urlString)); URLConnection con = url.openConnection(); in = new BufferedReader(new InputStreamReader(con.getInputStream(), "ISO-8859-1")); String line = null; while ((line = in.readLine()) != null) { result.append(line + "\r\n"); } in.close(); } catch (MalformedURLException e) { System.out.println("Unable to connect to URL: " + urlString); } catch (IOException e) { System.out.println("IOException when connecting to URL: " + urlString); } finally { if (in != null) { try { in.close(); } catch (Exception ex) { System.out.println("Exception throws at finally close reader when connecting to URL: " + urlString); } } } return result.toString(); }
Code Sample 2:
public void readData(int choice) throws IOException { for (i = 0; i < max; i++) for (j = 0; j < max; j++) { phase_x[i][j] = 0.0; phase_y[i][j] = 0.0; } URL url; InputStream is; InputStreamReader isr; if (choice == 0) { url = getClass().getResource("resources/Phase_623_620_Achromat.dat"); is = url.openStream(); isr = new InputStreamReader(is); } else { url = getClass().getResource("resources/Phase_623_620_NoAchromat.dat"); is = url.openStream(); isr = new InputStreamReader(is); } BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); i = 0; j = 0; phase_x[i][j] = 4 * Double.parseDouble(st.nextToken()); phase_y[i][j] = 4 * Double.parseDouble(st.nextToken()); xgridmin = phase_x[i][j]; ygridmin = phase_y[i][j]; temp_prev = phase_x[i][j]; kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); j++; int k = 0; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = 4 * Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } phase_x[i][j] = temp_new; phase_y[i][j] = 4 * Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; k++; } xgridmax = phase_x[i][j - 1]; ygridmax = phase_y[i][j - 1]; } |
11
| Code Sample 1:
public static SimpleDataTable loadDataFromFile(URL urlMetadata, URL urlData) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(urlMetadata.openStream())); List<String> columnNamesList = new ArrayList<String>(); String[] lineParts = null; String line; in.readLine(); while ((line = in.readLine()) != null) { lineParts = line.split(","); columnNamesList.add(lineParts[0]); } String[] columnNamesArray = new String[columnNamesList.size()]; int index = 0; for (String s : columnNamesList) { columnNamesArray[index] = s; index++; } SimpleDataTable table = new SimpleDataTable("tabulka s daty", columnNamesArray); in = new BufferedReader(new InputStreamReader(urlData.openStream())); lineParts = null; line = null; SimpleDataTableRow tableRow; double[] rowData; while ((line = in.readLine()) != null) { lineParts = line.split(","); rowData = new double[columnNamesList.size()]; for (int i = 0; i < columnNamesArray.length; i++) { rowData[i] = Double.parseDouble(lineParts[i + 1]); } tableRow = new SimpleDataTableRow(rowData, lineParts[0]); table.add(tableRow); } return table; }
Code Sample 2:
public String sendRequestHTTPTunelling(java.lang.String servletName, java.lang.String request) { String reqxml = ""; org.jdom.Document retdoc = null; String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", ""); String myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080"); if (myport == null || myport.trim().equals("")) { myport = "80"; } if (this.serverURL == null) { try { java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase(); if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost"; } catch (Exception exp) { exp.printStackTrace(); serverURL = "localhost"; } newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport); ipdig.show(); serverURL = myurl = ipdig.getIPAddress(); myport = ipdig.getPortNo(); java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL); java.util.prefs.Preferences.systemRoot().put("portno", myport); System.out.println(serverURL); } try { System.out.println("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URL url = new java.net.URL("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); 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(); String req1xml = request; 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("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.InputStreamReader br = new java.io.InputStreamReader(gip, "UTF-8"); retdoc = (new org.jdom.input.SAXBuilder()).build(br); try { java.io.FileOutputStream pw = new java.io.FileOutputStream("log3.txt"); pw.write(reqxml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(System.out); javax.swing.JOptionPane.showMessageDialog(null, "<html>Could not establish connection with the server, <br>Please verify server name/IP adress, <br>Also check if NewGenLib server is running</html>", "Critical error", javax.swing.JOptionPane.ERROR_MESSAGE); } System.out.println(reqxml); return (new org.jdom.output.XMLOutputter()).outputString(retdoc); } |
11
| Code Sample 1:
static void createCompleteXML(File file) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(errorFile); fos = new FileOutputStream(file); byte[] data = new byte[Integer.parseInt(BlueXStatics.prop.getProperty("allocationUnit"))]; int offset; while ((offset = fis.read(data)) != -1) fos.write(data, 0, offset); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } try { fos.close(); } catch (Exception e) { } } FileWriter fw = null; try { fw = new FileWriter(file, true); fw.append("</detail>"); fw.append("\n</exception>"); fw.append("\n</log>"); } catch (Exception e) { e.printStackTrace(); } finally { try { fw.close(); } catch (Exception e) { } } }
Code Sample 2:
private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
@Override public void start() { System.err.println("start AutoplotApplet " + VERSION + " @ " + (System.currentTimeMillis() - t0) + " msec"); super.start(); model = new ApplicationModel(); model.setExceptionHandler(new ExceptionHandler() { public void handle(Throwable t) { t.printStackTrace(); } public void handleUncaught(Throwable t) { t.printStackTrace(); } }); model.setApplet(true); model.dom.getOptions().setAutolayout(false); System.err.println("ApplicationModel created @ " + (System.currentTimeMillis() - t0) + " msec"); model.addDasPeersToApp(); System.err.println("done addDasPeersToApp @ " + (System.currentTimeMillis() - t0) + " msec"); try { System.err.println("Formatters: " + DataSourceRegistry.getInstance().getFormatterExtensions()); } catch (Exception ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } ApplicationModel appmodel = model; dom = model.getDocumentModel(); String debug = getParameter("debug"); if (debug != null && !debug.equals("true")) { } int width = getIntParameter("width", 700); int height = getIntParameter("height", 400); String fontParam = getStringParameter("font", ""); String column = getStringParameter("column", ""); String row = getStringParameter("row", ""); String scolor = getStringParameter("color", ""); String srenderType = getStringParameter("renderType", ""); String stimeRange = getStringParameter("timeRange", ""); String sfillColor = getStringParameter("fillColor", ""); String sforegroundColor = getStringParameter("foregroundColor", ""); String sbackgroundColor = getStringParameter("backgroundColor", ""); String title = getStringParameter("plot.title", ""); String xlabel = getStringParameter("plot.xaxis.label", ""); String xrange = getStringParameter("plot.xaxis.range", ""); String xlog = getStringParameter("plot.xaxis.log", ""); String xdrawTickLabels = getStringParameter("plot.xaxis.drawTickLabels", ""); String ylabel = getStringParameter("plot.yaxis.label", ""); String yrange = getStringParameter("plot.yaxis.range", ""); String ylog = getStringParameter("plot.yaxis.log", ""); String ydrawTickLabels = getStringParameter("plot.yaxis.drawTickLabels", ""); String zlabel = getStringParameter("plot.zaxis.label", ""); String zrange = getStringParameter("plot.zaxis.range", ""); String zlog = getStringParameter("plot.zaxis.log", ""); String zdrawTickLabels = getStringParameter("plot.zaxis.drawTickLabels", ""); statusCallback = getStringParameter("statusCallback", ""); timeCallback = getStringParameter("timeCallback", ""); clickCallback = getStringParameter("clickCallback", ""); if (srenderType.equals("fill_to_zero")) { srenderType = "fillToZero"; } setInitializationStatus("readParameters"); System.err.println("done readParameters @ " + (System.currentTimeMillis() - t0) + " msec"); String vap = getParameter("vap"); if (vap != null) { InputStream in = null; try { URL url = new URL(vap); System.err.println("load vap " + url + " @ " + (System.currentTimeMillis() - t0) + " msec"); in = url.openStream(); System.err.println("open vap stream " + url + " @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.doOpen(in, null); System.err.println("done open vap @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.waitUntilIdle(false); System.err.println("done load vap and waitUntilIdle @ " + (System.currentTimeMillis() - t0) + " msec"); Canvas cc = appmodel.getDocumentModel().getCanvases(0); System.err.println("vap height, width= " + cc.getHeight() + "," + cc.getWidth()); width = getIntParameter("width", cc.getWidth()); height = getIntParameter("height", cc.getHeight()); System.err.println("output height, width= " + width + "," + height); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } finally { try { in.close(); } catch (IOException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } } appmodel.getCanvas().setSize(width, height); appmodel.getCanvas().revalidate(); appmodel.getCanvas().setPrintingTag(""); dom.getOptions().setAutolayout("true".equals(getParameter("autolayout"))); if (!dom.getOptions().isAutolayout() && vap == null) { if (!row.equals("")) { dom.getController().getCanvas().getController().setRow(row); } if (!column.equals("")) { dom.getController().getCanvas().getController().setColumn(column); } dom.getCanvases(0).getRows(0).setTop("0%"); dom.getCanvases(0).getRows(0).setBottom("100%"); } if (!fontParam.equals("")) { appmodel.canvas.setBaseFont(Font.decode(fontParam)); } JMenuItem item; item = new JMenuItem(new AbstractAction("Reset Zoom") { public void actionPerformed(ActionEvent e) { resetZoom(); } }); dom.getPlots(0).getController().getDasPlot().getDasMouseInputAdapter().addMenuItem(item); overviewMenuItem = new JCheckBoxMenuItem(new AbstractAction("Context Overview") { public void actionPerformed(ActionEvent e) { addOverview(); } }); dom.getPlots(0).getController().getDasPlot().getDasMouseInputAdapter().addMenuItem(overviewMenuItem); if (sforegroundColor != null && !sforegroundColor.equals("")) { appmodel.canvas.setForeground(Color.decode(sforegroundColor)); } if (sbackgroundColor != null && !sbackgroundColor.equals("")) { appmodel.canvas.setBackground(Color.decode(sbackgroundColor)); } getContentPane().setLayout(new BorderLayout()); System.err.println("done set parameters @ " + (System.currentTimeMillis() - t0) + " msec"); String surl = getParameter("url"); String process = getStringParameter("process", ""); String script = getStringParameter("script", ""); if (surl == null) { surl = getParameter("dataSetURL"); } if (surl != null && !surl.equals("")) { DataSource dsource; try { dsource = DataSetURI.getDataSource(surl); System.err.println("get dsource for " + surl + " @ " + (System.currentTimeMillis() - t0) + " msec"); System.err.println(" got dsource=" + dsource); System.err.println(" dsource.getClass()=" + dsource.getClass()); } catch (NullPointerException ex) { throw new RuntimeException("No such data source: ", ex); } catch (Exception ex) { ex.printStackTrace(); dsource = null; } DatumRange timeRange1 = null; if (!stimeRange.equals("")) { timeRange1 = DatumRangeUtil.parseTimeRangeValid(stimeRange); TimeSeriesBrowse tsb = dsource.getCapability(TimeSeriesBrowse.class); if (tsb != null) { System.err.println("do tsb.setTimeRange @ " + (System.currentTimeMillis() - t0) + " msec"); tsb.setTimeRange(timeRange1); System.err.println("done tsb.setTimeRange @ " + (System.currentTimeMillis() - t0) + " msec"); } } QDataSet ds; if (dsource != null) { TimeSeriesBrowse tsb = dsource.getCapability(TimeSeriesBrowse.class); if (tsb == null) { try { System.err.println("do getDataSet @ " + (System.currentTimeMillis() - t0) + " msec"); System.err.println(" dsource=" + dsource); System.err.println(" dsource.getClass()=" + dsource.getClass()); if (dsource.getClass().toString().contains("CsvDataSource")) System.err.println(" WHY IS THIS CsvDataSource!?!?"); ds = dsource == null ? null : dsource.getDataSet(loadInitialMonitor); for (int i = 0; i < Math.min(12, ds.length()); i++) { System.err.printf("ds[%d]=%s\n", i, ds.slice(i)); } System.err.println("loaded ds: " + ds); System.err.println("done getDataSet @ " + (System.currentTimeMillis() - t0) + " msec"); } catch (Exception ex) { throw new RuntimeException(ex); } } } System.err.println("do setDataSource @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.setDataSource(dsource); System.err.println("done setDataSource @ " + (System.currentTimeMillis() - t0) + " msec"); setInitializationStatus("dataSourceSet"); if (stimeRange != null && !stimeRange.equals("")) { try { System.err.println("wait for idle @ " + (System.currentTimeMillis() - t0) + " msec (due to stimeRange)"); appmodel.waitUntilIdle(true); System.err.println("done wait for idle @ " + (System.currentTimeMillis() - t0) + " msec"); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } if (UnitsUtil.isTimeLocation(dom.getTimeRange().getUnits())) { dom.setTimeRange(timeRange1); } } setInitializationStatus("dataSetLoaded"); } System.err.println("done dataSetLoaded @ " + (System.currentTimeMillis() - t0) + " msec"); Plot p = dom.getController().getPlot(); if (!title.equals("")) { p.setTitle(title); } Axis axis = p.getXaxis(); if (!xlabel.equals("")) { axis.setLabel(xlabel); } if (!xrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(xrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!xlog.equals("")) { axis.setLog("true".equals(xlog)); } if (!xdrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(xdrawTickLabels)); } axis = p.getYaxis(); if (!ylabel.equals("")) { axis.setLabel(ylabel); } if (!yrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(yrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!ylog.equals("")) { axis.setLog("true".equals(ylog)); } if (!ydrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(ydrawTickLabels)); } axis = p.getZaxis(); if (!zlabel.equals("")) { axis.setLabel(zlabel); } if (!zrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(zrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!zlog.equals("")) { axis.setLog("true".equals(zlog)); } if (!zdrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(zdrawTickLabels)); } if (srenderType != null && !srenderType.equals("")) { try { RenderType renderType = RenderType.valueOf(srenderType); dom.getController().getPlotElement().setRenderType(renderType); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } } System.err.println("done setRenderType @ " + (System.currentTimeMillis() - t0) + " msec"); if (!scolor.equals("")) { try { dom.getController().getPlotElement().getStyle().setColor(Color.decode(scolor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sfillColor.equals("")) { try { dom.getController().getPlotElement().getStyle().setFillColor(Color.decode(sfillColor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sforegroundColor.equals("")) { try { dom.getOptions().setForeground(Color.decode(sforegroundColor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sbackgroundColor.equals("")) { try { dom.getOptions().setBackground(Color.decode(sbackgroundColor)); } catch (Exception ex) { ex.printStackTrace(); } } surl = getParameter("dataSetURL"); if (surl != null) { if (surl.startsWith("about:")) { setDataSetURL(surl); } else { } } getContentPane().remove(progressComponent); getContentPane().add(model.getCanvas()); System.err.println("done add to applet @ " + (System.currentTimeMillis() - t0) + " msec"); validate(); System.err.println("done applet.validate @ " + (System.currentTimeMillis() - t0) + " msec"); repaint(); appmodel.getCanvas().setVisible(true); initializing = false; repaint(); System.err.println("ready @ " + (System.currentTimeMillis() - t0) + " msec"); setInitializationStatus("ready"); dom.getController().getPlot().getXaxis().addPropertyChangeListener(Axis.PROP_RANGE, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { timeCallback(String.valueOf(evt.getNewValue())); } }); if (!clickCallback.equals("")) { String clickCallbackLabel = "Applet Click"; int i = clickCallback.indexOf(","); if (i != -1) { int i2 = clickCallback.indexOf("label="); if (i2 != -1) clickCallbackLabel = clickCallback.substring(i2 + 6).trim(); clickCallback = clickCallback.substring(0, i).trim(); } final DasPlot plot = dom.getPlots(0).getController().getDasPlot(); MouseModule mm = new MouseModule(plot, new CrossHairRenderer(plot, null, plot.getXAxis(), plot.getYAxis()), clickCallbackLabel) { @Override public void mousePressed(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } @Override public void mouseDragged(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } @Override public void mouseReleased(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } }; plot.getDasMouseInputAdapter().setPrimaryModule(mm); } p.getController().getDasPlot().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getXaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getYaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getZaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); if (getStringParameter("contextOverview", "off").equals("on")) { Runnable run = new Runnable() { public void run() { dom.getController().waitUntilIdle(); try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } dom.getController().waitUntilIdle(); doSetOverview(true); } }; new Thread(run).start(); } System.err.println("done start AutoplotApplet " + VERSION + " @ " + (System.currentTimeMillis() - t0) + " msec"); }
Code Sample 2:
public Long processAddHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return null; } PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_LIST_HOLDING"); seq.setTableName("WM_LIST_HOLDING"); seq.setColumnName("ID_HOLDING"); Long sequenceValue = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_LIST_HOLDING " + "( ID_HOLDING, full_name_HOLDING, NAME_HOLDING )" + "values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?, ?, ? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); int num = 1; RsetTools.setLong(ps, num++, sequenceValue); ps.setString(num++, holdingBean.getName()); ps.setString(num++, holdingBean.getShortName()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); HoldingBean bean = new HoldingBean(holdingBean); bean.setId(sequenceValue); processInsertRelatedCompany(dbDyn, bean, authSession); dbDyn.commit(); return sequenceValue; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } |
00
| Code Sample 1:
public static String getMd5(String str) { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); final byte b[] = md.digest(); int i; final StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } return buf.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
Code Sample 2:
public void refreshStatus() { if (!enabledDisplay) return; try { String url = getServerFortURL(); BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String data = null; int counter = 0; while ((data = reader.readLine()) != null && counter < 9) { status[counter] = UNKNOWN; if (data.matches(".*_alsius.gif.*")) { status[counter] = ALSIUS; counter++; } if (data.matches(".*_syrtis.gif.*")) { status[counter] = SYRTIS; counter++; } if (data.matches(".*_ignis.gif.*")) { status[counter] = IGNIS; counter++; } } } catch (Exception exc) { for (int i = 0; i < status.length; i++) status[i] = UNKNOWN; } } |
11
| Code Sample 1:
public static void main(final String[] args) throws RecognitionException, TokenStreamException, IOException, IllegalOptionValueException, UnknownOptionException { try { CmdLineParser cmdLineParser = new CmdLineParser(); Option formatOption = cmdLineParser.addStringOption('f', "format"); Option encodingOption = cmdLineParser.addStringOption('c', "charset"); cmdLineParser.parse(args); String format = (String) cmdLineParser.getOptionValue(formatOption); String encoding = (String) cmdLineParser.getOptionValue(encodingOption); if (encoding == null || encoding.trim().equals("")) { encoding = "utf-8"; System.out.println("Defaulting to output charset utf-8 as argument -c is missing or not valid."); } String[] remainingArgs = cmdLineParser.getRemainingArgs(); if (remainingArgs.length != 2) { printUsage("Input and output file are not specified correctly. "); } File inputFile = new File(remainingArgs[0]); if (!inputFile.exists()) { printUsage("Input file " + remainingArgs[0] + " does not exist. "); } File outputFile = new File(remainingArgs[1]); if (!outputFile.exists()) { outputFile.createNewFile(); } if (format == null || format.trim().equals("")) { format = (String) FileUtil.cutExtension(outputFile.getName()).getValue(); } if ("tex".equals(format)) { Reader reader = new LatexEncoderReader(new FileReader(inputFile)); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outputFile), encoding); char[] buffer = new char[1024]; int read; do { read = reader.read(buffer); if (read > 0) { out.write(buffer, 0, read); } } while (read != -1); out.flush(); out.close(); } else { printUsage("Format not specified via argument -f. Also guessing for the extension of output file " + outputFile.getName() + " failed"); } } catch (Exception ex) { ex.printStackTrace(); printUsage(ex.getMessage()); } }
Code Sample 2:
@Override @RemoteMethod public boolean encrypt(int idAnexo) { try { Anexo anexo = anexoService.selectById(idAnexo); aes.init(Cipher.ENCRYPT_MODE, aeskeySpec); FileInputStream fis = new FileInputStream(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho()); CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(config.baseDir + "/arquivos_upload_direto/encrypt/" + anexo.getAnexoCaminho()), aes); IOUtils.copy(fis, cos); cos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } |
11
| Code Sample 1:
public static Photo createPhoto(String title, String userLogin, String pathToPhoto, String basePathImage) throws NoSuchAlgorithmException, IOException { String id = CryptSHA1.genPhotoID(userLogin, title); String extension = pathToPhoto.substring(pathToPhoto.lastIndexOf(".")); String destination = basePathImage + id + extension; FileInputStream fis = new FileInputStream(pathToPhoto); FileOutputStream fos = new FileOutputStream(destination); FileChannel fci = fis.getChannel(); FileChannel fco = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int read = fci.read(buffer); if (read == -1) break; buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); fco.close(); fos.close(); fis.close(); ImageIcon image; ImageIcon thumb; String destinationThumb = basePathImage + "thumb/" + id + extension; image = new ImageIcon(destination); int maxSize = 150; int origWidth = image.getIconWidth(); int origHeight = image.getIconHeight(); if (origWidth > origHeight) { thumb = new ImageIcon(image.getImage().getScaledInstance(maxSize, -1, Image.SCALE_SMOOTH)); } else { thumb = new ImageIcon(image.getImage().getScaledInstance(-1, maxSize, Image.SCALE_SMOOTH)); } BufferedImage bi = new BufferedImage(thumb.getIconWidth(), thumb.getIconHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.drawImage(thumb.getImage(), 0, 0, null); try { ImageIO.write(bi, "JPG", new File(destinationThumb)); } catch (IOException ioe) { System.out.println("Error occured saving thumbnail"); } Photo photo = new Photo(id); photo.setTitle(title); photo.basePathImage = basePathImage; return photo; }
Code Sample 2:
@Override public void actionPerformed(ActionEvent e) { if (copiedFiles_ != null) { File[] tmpFiles = new File[copiedFiles_.length]; File tmpDir = new File(Settings.getPropertyString(ConstantKeys.project_dir), "tmp/"); tmpDir.mkdirs(); for (int i = copiedFiles_.length - 1; i >= 0; i--) { Frame f = FrameManager.getInstance().getFrameAtIndex(i); try { File in = f.getFile(); File out = new File(tmpDir, f.getFile().getName()); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); tmpFiles[i] = out; } catch (IOException e1) { e1.printStackTrace(); } } try { FrameManager.getInstance().insertFrames(getTable().getSelectedRow(), FrameManager.INSERT_TYPE.MOVE, tmpFiles); } catch (IOException e1) { e1.printStackTrace(); } } } |
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:
@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."); } |
00
| Code Sample 1:
private void loadServers() { try { URL url = new URL(VirtualDeckConfig.SERVERS_URL); cmbServer.addItem("Local"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; if (in.readLine().equals("[list]")) { while ((str = in.readLine()) != null) { String[] host_line = str.split(";"); Host h = new Host(); h.setIp(host_line[0]); h.setPort(Integer.parseInt(host_line[1])); h.setName(host_line[2]); getServers().add(h); cmbServer.addItem(h.getName()); } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
Code Sample 2:
private static boolean prepareQualifyingFile(String completePath, String outputFile) { try { File inFile = new File(completePath + fSep + "qualifying.txt"); FileChannel inC = new FileInputStream(inFile).getChannel(); BufferedReader br = new BufferedReader(new FileReader(inFile)); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + outputFile); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); boolean endOfFile = true; short movieName = 0; int customer = 0; while (endOfFile) { String line = br.readLine(); if (line != null) { if (line.indexOf(":") >= 0) { movieName = new Short(line.substring(0, line.length() - 1)).shortValue(); } else { customer = new Integer(line.substring(0, line.indexOf(","))).intValue(); ByteBuffer outBuf = ByteBuffer.allocate(6); outBuf.putShort(movieName); outBuf.putInt(customer); outBuf.flip(); outC.write(outBuf); } } else endOfFile = false; } br.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } } |
00
| Code Sample 1:
public void downloadQFromMinibix(int ticketNo) { String minibixDomain = Preferences.userRoot().node("Spectatus").get("MBAddr", "http://mathassess.caret.cam.ac.uk"); String minibixPort = Preferences.userRoot().node("Spectatus").get("MBPort", "80"); String url = minibixDomain + ":" + minibixPort + "/qtibank-webserv/deposits/all/" + ticketNo; File file = new File(tempdir + sep + "minibix.zip"); try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); int l; byte[] tmp = new byte[2048]; while ((l = instream.read(tmp)) != -1) { out.write(tmp, 0, l); } out.close(); instream.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static final File getFile(final URL url) throws IOException { final File shortcutFile; final File currentFile = files.get(url); if (currentFile == null || !currentFile.exists()) { shortcutFile = File.createTempFile("windowsIsLame", ".vbs"); shortcutFile.deleteOnExit(); files.put(url, shortcutFile); final InputStream stream = url.openStream(); final FileOutputStream out = new FileOutputStream(shortcutFile); try { StreamUtils.copy(stream, out); } finally { out.close(); stream.close(); } } else shortcutFile = currentFile; return shortcutFile; } |
11
| Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public void backupXML() { try { TimeStamp timeStamp = new TimeStamp(); String fnameIn = this.fnameXML(); String pathBackup = this.pathXML + "\\Backup\\"; String fnameOut = fnameIn.substring(fnameIn.indexOf(this.fname), fnameIn.length()); fnameOut = fnameOut.substring(0, fnameOut.indexOf("xml")); fnameOut = pathBackup + fnameOut + timeStamp.now("yyyyMMdd-kkmmss") + ".xml"; System.out.println("fnameIn: " + fnameIn); System.out.println("fnameOut: " + fnameOut); FileChannel in = new FileInputStream(fnameIn).getChannel(); FileChannel out = new FileOutputStream(fnameOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { central.inform("ORM.backupXML: " + e.toString()); } } |
11
| Code Sample 1:
private static long saveAndClosePDFDocument(PDDocument document, OutputStreamProvider outProvider) throws IOException, COSVisitorException { File tempFile = null; InputStream in = null; OutputStream out = null; try { tempFile = File.createTempFile("temp", "pdf"); OutputStream tempFileOut = new FileOutputStream(tempFile); tempFileOut = new BufferedOutputStream(tempFileOut); document.save(tempFileOut); document.close(); tempFileOut.close(); long length = tempFile.length(); in = new BufferedInputStream(new FileInputStream(tempFile)); out = new BufferedOutputStream(outProvider.getOutputStream()); IOUtils.copy(in, out); return length; } finally { if (in != null) { IOUtils.closeQuietly(in); } if (out != null) { IOUtils.closeQuietly(out); } if (tempFile != null && !FileUtils.deleteQuietly(tempFile)) { tempFile.deleteOnExit(); } } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
00
| Code Sample 1:
public String getShortToken(String md5Str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(md5Str.getBytes(JspRunConfig.charset)); } catch (Exception e) { e.printStackTrace(); } StringBuffer token = toHex(md5.digest()); return token.substring(8, 24); }
Code Sample 2:
public Function findFunction(String functionName) { String code = ""; UserFunction function = (UserFunction) getCachedFunction(functionName); if (function != null) return function; ErrorLogger.debugLine("MFileWebLoader: loading >" + functionName + ".m<"); try { URL url = new URL(codeBase, directory + "/" + functionName + ".m"); InputStream in = url.openStream(); BufferedReader inReader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = inReader.readLine()) != null) { code += line + "\n"; } inReader.close(); } catch (Exception e) { Errors.throwMathLibException("MFileWebLoader: m-file exception via web"); } ErrorLogger.debugLine("MFileWebLoader: code: begin \n" + code + "\ncode end"); FunctionParser funcParser = new FunctionParser(); function = funcParser.parseFunction(code); function.setName(functionName); cacheFunction(function); ErrorLogger.debugLine("MFileWebLoader: finished webloading >" + functionName + ".m<"); return function; } |
11
| Code Sample 1:
public static String calculateHA1(String username, byte[] password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(username, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(DAAP_REALM, ISO_8859_1)); md.update((byte) ':'); md.update(password); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
Code Sample 2:
public static String getEncryptedPassword(String clearTextPassword) { if (StringUtil.isEmpty(clearTextPassword)) return ""; try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(clearTextPassword.getBytes()); return new sun.misc.BASE64Encoder().encode(md.digest()); } catch (NoSuchAlgorithmException e) { _log.error("Failed to encrypt password.", e); } return ""; } |
11
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void nioJoinFiles(FileLib.FileValidator validator, File target, File[] sources) { boolean big_files = false; for (int i = 0; i < sources.length; i++) { if (sources[i].length() > Integer.MAX_VALUE) { big_files = true; break; } } if (big_files) { joinFiles(validator, target, sources); } else { System.out.println(i18n.getString("jdk14_comment")); FileOutputStream fos = null; try { fos = new FileOutputStream(target); FileChannel fco = fos.getChannel(); FileInputStream fis = null; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); FileChannel fci = fis.getChannel(); java.nio.MappedByteBuffer map; try { map = fci.map(FileChannel.MapMode.READ_ONLY, 0, (int) sources[i].length()); fco.write(map); fci.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); try { fis.close(); fos.close(); } catch (IOException e) { } } finally { fis.close(); } } fco.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } } |
00
| Code Sample 1:
@Test public void testOther() throws Exception { filter.init(this.mockConfig); ByteArrayOutputStream jpg = new ByteArrayOutputStream(); IOUtils.copy(this.getClass().getResourceAsStream("Buffalo-Theory.jpg"), jpg); MockFilterChain mockChain = new MockFilterChain(); mockChain.setContentType("image/jpg"); mockChain.setOutputData(jpg.toByteArray()); MockResponse mockResponse = new MockResponse(); filter.doFilter(this.mockRequest, mockResponse, mockChain); Assert.assertTrue("Time stamp content type", "image/jpg".equals(mockResponse.getContentType())); Assert.assertTrue("OutputStream as original", ArrayUtils.isEquals(jpg.toByteArray(), mockResponse.getMockServletOutputStream().getBytes())); }
Code Sample 2:
private BoardPattern[] getBoardPatterns() { Resource[] resources = boardManager.getResources("boards"); BoardPattern[] boardPatterns = new BoardPattern[resources.length]; for (int i = 0; i < resources.length; i++) boardPatterns[i] = (BoardPattern) resources[i]; for (int i = 0; i < resources.length; i++) { for (int j = 0; j < resources.length - (i + 1); j++) { String name1 = boardPatterns[j].getName(); String name2 = boardPatterns[j + 1].getName(); if (name1.compareTo(name2) > 0) { BoardPattern tmp = boardPatterns[j]; boardPatterns[j] = boardPatterns[j + 1]; boardPatterns[j + 1] = tmp; } } } return boardPatterns; } |
00
| Code Sample 1:
private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); }
Code Sample 2:
protected Object doExecute() throws Exception { if (args.size() == 1 && "-".equals(args.get(0))) { log.info("Printing STDIN"); cat(new BufferedReader(io.in), io); } else { for (String filename : args) { BufferedReader reader; try { URL url = new URL(filename); log.info("Printing URL: " + url); reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (MalformedURLException ignore) { File file = new File(filename); log.info("Printing file: " + file); reader = new BufferedReader(new FileReader(file)); } try { cat(reader, io); } finally { IOUtil.close(reader); } } } return SUCCESS; } |
11
| Code Sample 1:
@SuppressWarnings("unchecked") protected void processTransformAction(HttpServletRequest request, HttpServletResponse response, String action) throws Exception { File transformationFile = null; String tr = request.getParameter(Definitions.REQUEST_PARAMNAME_XSLT); if (StringUtils.isNotBlank(tr)) { transformationFile = new File(xslBase, tr); if (!transformationFile.isFile()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"" + Definitions.REQUEST_PARAMNAME_XSLT + "\" " + "with value \"" + tr + "\" refers to non existing file"); return; } } StreamResult result; ByteArrayOutputStream baos = null; if (isDevelopmentMode) { baos = new ByteArrayOutputStream(); if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(baos, Base64.DECODE)); } else { result = new StreamResult(baos); } } else { if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(response.getOutputStream(), Base64.DECODE)); } else { result = new StreamResult(response.getOutputStream()); } } HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); String method = transformer.getOutputProperties().getProperty(OutputKeys.METHOD, "xml"); String contentType; if (method.endsWith("html")) { contentType = Definitions.MIMETYPE_HTML; } else if (method.equals("xml")) { contentType = Definitions.MIMETYPE_XML; } else { contentType = Definitions.MIMETYPE_TEXTPLAIN; } String encoding = transformer.getOutputProperties().getProperty(OutputKeys.ENCODING, "UTF-8"); response.setContentType(contentType + ";charset=" + encoding); DataSourceIf dataSource = new NullSource(); transformer.transform((Source) dataSource, result); if (isDevelopmentMode) { IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; }
Code Sample 2:
public static boolean copyFile(final File src, final File dst) throws FileNotFoundException { if (src == null || dst == null || src.equals(dst)) { return false; } boolean result = false; if (src.exists()) { if (dst.exists() && !dst.canWrite()) { return false; } final FileInputStream srcStream = new FileInputStream(src); final FileOutputStream dstStream = new FileOutputStream(dst); final FileChannel srcChannel = srcStream.getChannel(); final FileChannel dstChannel = dstStream.getChannel(); FileLock dstLock = null; FileLock srcLock = null; try { srcLock = srcChannel.tryLock(0, Long.MAX_VALUE, true); dstLock = dstChannel.tryLock(); if (srcLock != null && dstLock != null) { int maxCount = 64 * 1024 * 1024 - 32 * 1024; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, maxCount, dstChannel); } } } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } finally { if (srcChannel != null) { try { if (srcLock != null) { srcLock.release(); } srcChannel.close(); srcStream.close(); } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } if (dstChannel != null) { try { if (dstLock != null) { dstLock.release(); } dstChannel.close(); dstStream.close(); result = true; } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } } } return result; } |
00
| Code Sample 1:
public static String[] viewFilesToImport(HttpSession session) { FTPClient ftp = new FTPClient(); CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); 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[] dirList = null; if (importFTPServer.equals("") || importFTPLogin.equals("") || importFTPPassword.equals("")) { return dirList; } boolean loggedIn = false; try { int reply; ftp.connect(importFTPServer); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport connecting: " + ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.logout(); ftp.disconnect(); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport ERROR: FTP server refused connection."); } else { loggedIn = ftp.login(importFTPLogin, importFTPPassword); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport Logging in: " + importFTPLogin + " " + importFTPPassword); } if (loggedIn) { try { ftp.changeWorkingDirectory(importFTPFilePath); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport changing dir: " + importFTPFilePath); if (!FTPReply.isPositiveCompletion(reply)) { CofaxToolsUtil.log("ERROR: cannot change directory"); } FTPFile[] remoteFileList = ftp.listFiles(); ArrayList tmpArray = new ArrayList(); for (int i = 0; i < remoteFileList.length; i++) { FTPFile testFile = remoteFileList[i]; if (testFile.getType() == FTP.ASCII_FILE_TYPE) { tmpArray.add(testFile.getName()); } } dirList = (String[]) tmpArray.toArray(new String[0]); ftp.logout(); ftp.disconnect(); } catch (java.io.IOException e) { CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport cannot read directory: " + importFTPFilePath); } } } catch (IOException e) { CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport could not connect to server: " + e); } return (dirList); }
Code Sample 2:
private void onOKAction() { if (url == null) { optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); JOptionPane.showMessageDialog(this, "URL field cannot be empty", "Empty URL", JOptionPane.ERROR_MESSAGE); } else { try { URLConnection sourceConnection = url.openConnection(); sourceConnection.setConnectTimeout(10); if (sourceConnection.getContentLength() == -1) { throw new IOException("Can't connect to " + url.toString()); } exit_status = OK; setVisible(false); dispose(); } catch (IOException e) { optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); JOptionPane.showMessageDialog(this, "Please enter valid, resolvable source and target URLs...\n " + e.getMessage(), "Invalid URL", JOptionPane.ERROR_MESSAGE); } } } |
11
| Code Sample 1:
public void copyTo(Bean bean, OutputStream out, int offset, int length) throws Exception { BeanInfo beanInfo = getBeanInfo(bean.getClass()); validate(bean, beanInfo, "copyTo"); if (blobCache != null && length < MAX_BLOB_CACHE_LENGHT) { byte[] bytes = null; synchronized (this) { String key = makeUniqueKey(bean, beanInfo, offset, length); if (blobCache.contains(key)) bytes = (byte[]) blobCache.get(key); else blobCache.put(key, bytes = toByteArray(bean, offset, length, beanInfo)); } InputStream in = new ByteArrayInputStream(bytes); IOUtils.copy(in, out); in.close(); } else { jdbcManager.queryScript(beanInfo.getBlobInfo(jdbcManager.getDb()).getReadScript(), bean, new JdbcOutputStreamRowMapper(out, offset, length)); } }
Code Sample 2:
@Test public void testEncryptDecrypt() throws IOException { BlockCipher cipher = new SerpentEngine(); Random rnd = new Random(); byte[] key = new byte[256 / 8]; rnd.nextBytes(key); byte[] iv = new byte[cipher.getBlockSize()]; rnd.nextBytes(iv); byte[] data = new byte[1230000]; new Random().nextBytes(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); CryptOutputStream eout = new CryptOutputStream(bout, cipher, key); eout.write(data); eout.close(); byte[] eData = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(eData); CryptInputStream din = new CryptInputStream(bin, cipher, key); bout = new ByteArrayOutputStream(); IOUtils.copy(din, bout); eData = bout.toByteArray(); Assert.assertTrue(Arrays.areEqual(data, eData)); } |
11
| Code Sample 1:
public void run() { if (getCommand() == null) throw new IllegalArgumentException("Given command is null!"); if (getSocketProvider() == null) throw new IllegalArgumentException("Given connection is not open!"); if (getCommand() instanceof ListCommand) { try { setReply(ReplyWorker.readReply(getSocketProvider(), true)); setStatus(ReplyWorker.FINISHED); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } return; } else if (getCommand() instanceof RetrieveCommand) { RetrieveCommand retrieveCommand = (RetrieveCommand) getCommand(); if (retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_I || retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Download file: " + retrieveCommand.getFromFile().toString()); FileOutputStream out = null; FileChannel channel = null; if (getDownloadMethod() == RetrieveCommand.FILE_BASED) { out = new FileOutputStream(retrieveCommand.getToFile().getFile()); channel = out.getChannel(); if (retrieveCommand.getResumePosition() != -1) { try { channel.position(retrieveCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } int amount; try { while ((amount = getSocketProvider().read(buffer)) != -1) { if (amount == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); setStatus(ReplyWorker.FINISHED); if (channel != null) channel.close(); if (this.outputPipe != null) this.outputPipe.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for download!"); return; } else if (getCommand() instanceof StoreCommand) { StoreCommand storeCommand = (StoreCommand) getCommand(); if (storeCommand.getToFile().getTransferType().intern() == Command.TYPE_I || storeCommand.getToFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Upload file: " + storeCommand.getFromFile()); InputStream in = storeCommand.getStream(); int amount; int socketWrite; int socketAmount = 0; if (in instanceof FileInputStream) { FileChannel channel = ((FileInputStream) in).getChannel(); if (storeCommand.getResumePosition() != -1) { try { channel.position(storeCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } try { while ((amount = channel.read(buffer)) != -1) { buffer.flip(); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount += socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); channel.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } else { try { while ((amount = in.read(buffer.array())) != -1) { buffer.flip(); buffer.limit(amount); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount = socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); in.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { in.close(); getSocketProvider().close(); } catch (Exception e) { } } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for upload!"); } else throw new IllegalArgumentException("Given command is not supported!"); }
Code Sample 2:
private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } } |
00
| Code Sample 1:
public static Test suite() throws Exception { java.net.URL url = ClassLoader.getSystemResource("host0.jndi.properties"); java.util.Properties host0JndiProps = new java.util.Properties(); host0JndiProps.load(url.openStream()); java.util.Properties systemProps = System.getProperties(); systemProps.putAll(host0JndiProps); System.setProperties(systemProps); TestSuite suite = new TestSuite(); suite.addTest(new TestSuite(T06OTSInterpositionUnitTestCase.class)); TestSetup wrapper = new JBossTestSetup(suite) { protected void setUp() throws Exception { super.setUp(); deploy("dtmpassthrough2ots.jar"); } protected void tearDown() throws Exception { undeploy("dtmpassthrough2ots.jar"); super.tearDown(); } }; return wrapper; }
Code Sample 2:
public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); } |
00
| Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void 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); } } |
00
| Code Sample 1:
private static FileChannel getFileChannel(File file, boolean isOut, boolean append) throws OpenR66ProtocolSystemException { FileChannel fileChannel = null; try { if (isOut) { FileOutputStream fileOutputStream = new FileOutputStream(file.getPath(), append); fileChannel = fileOutputStream.getChannel(); if (append) { try { fileChannel.position(file.length()); } catch (IOException e) { } } } else { if (!file.exists()) { throw new OpenR66ProtocolSystemException("File does not exist"); } FileInputStream fileInputStream = new FileInputStream(file.getPath()); fileChannel = fileInputStream.getChannel(); } } catch (FileNotFoundException e) { throw new OpenR66ProtocolSystemException("File not found", e); } return fileChannel; }
Code Sample 2:
public static String rename_file(String sessionid, String key, String newFileName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_file"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_file")); nameValuePairs.add(new BasicNameValuePair("new_name", newFileName)); nameValuePairs.add(new BasicNameValuePair("key", key)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; } |
11
| Code Sample 1:
protected void checkWeavingJar() throws IOException { OutputStream out = null; try { final File weaving = new File(getWeavingPath()); if (!weaving.exists()) { new File(getWeavingFolder()).mkdir(); weaving.createNewFile(); final Path src = new Path("weaving/openfrwk-weaving.jar"); final InputStream in = FileLocator.openStream(getBundle(), src, false); out = new FileOutputStream(getWeavingPath(), true); IOUtils.copy(in, out); Logger.log(Logger.INFO, "Put weaving jar at location " + weaving); } else { Logger.getLog().info("File openfrwk-weaving.jar already exists at " + weaving); } } catch (final SecurityException e) { Logger.log(Logger.ERROR, "[SECURITY EXCEPTION] Not enough privilegies to create " + "folder and copy NexOpen weaving jar at location " + getWeavingFolder()); Logger.logException(e); } finally { if (out != null) { out.flush(); out.close(); } } }
Code Sample 2:
public void _saveWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String subcmd) throws WebAssetException, Exception { long maxsize = 50; long maxwidth = 3000; long maxheight = 3000; long minheight = 10; ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); try { UploadPortletRequest uploadReq = PortalUtil.getUploadPortletRequest(req); String parent = ParamUtil.getString(req, "parent"); int countFiles = ParamUtil.getInteger(req, "countFiles"); int fileCounter = 0; Folder folder = (Folder) InodeFactory.getInode(parent, Folder.class); _checkUserPermissions(folder, user, PERMISSION_WRITE); String userId = user.getUserId(); String customMessage = "Some file does not match the filters specified by the folder: "; boolean filterError = false; for (int k = 0; k < countFiles; k++) { File file = new File(); String title = ParamUtil.getString(req, "title" + k); String friendlyName = ParamUtil.getString(req, "friendlyName" + k); Date publishDate = new Date(); String fileName = ParamUtil.getString(req, "fileName" + k); fileName = checkMACFileName(fileName); if (!FolderFactory.matchFilter(folder, fileName)) { customMessage += fileName + ", "; filterError = true; continue; } if (fileName.length() > 0) { String mimeType = FileFactory.getMimeType(fileName); String URI = folder.getPath() + fileName; String suffix = UtilMethods.getFileExtension(fileName); file.setTitle(title); file.setFileName(fileName); file.setFriendlyName(friendlyName); file.setPublishDate(publishDate); file.setModUser(userId); InodeFactory.saveInode(file); String filePath = FileFactory.getRealAssetsRootPath(); new java.io.File(filePath).mkdir(); java.io.File uploadedFile = uploadReq.getFile("uploadedFile" + k); Logger.debug(this, "bytes" + uploadedFile.length()); file.setSize((int) uploadedFile.length() - 2); file.setMimeType(mimeType); Host host = HostFactory.getCurrentHost(httpReq); Identifier ident = IdentifierFactory.getIdentifierByURI(URI, host); String message = ""; if ((FileFactory.existsFileName(folder, fileName))) { InodeFactory.deleteInode(file); message = "The uploaded file " + fileName + " already exists in this folder"; SessionMessages.add(req, "custommessage", message); } else { String fileInodePath = String.valueOf(file.getInode()); if (fileInodePath.length() == 1) { fileInodePath = fileInodePath + "0"; } fileInodePath = fileInodePath.substring(0, 1) + java.io.File.separator + fileInodePath.substring(1, 2); new java.io.File(filePath + java.io.File.separator + fileInodePath.substring(0, 1)).mkdir(); new java.io.File(filePath + java.io.File.separator + fileInodePath).mkdir(); java.io.File f = new java.io.File(filePath + java.io.File.separator + fileInodePath + java.io.File.separator + file.getInode() + "." + suffix); java.io.FileOutputStream fout = new java.io.FileOutputStream(f); FileChannel outputChannel = fout.getChannel(); FileChannel inputChannel = new java.io.FileInputStream(uploadedFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); outputChannel.force(false); outputChannel.close(); inputChannel.close(); Logger.debug(this, "SaveFileAction New File in =" + filePath + java.io.File.separator + fileInodePath + java.io.File.separator + file.getInode() + "." + suffix); if (suffix.equals("jpg") || suffix.equals("gif")) { com.dotmarketing.util.Thumbnail.resizeImage(filePath + java.io.File.separator + fileInodePath + java.io.File.separator, String.valueOf(file.getInode()), suffix); int height = javax.imageio.ImageIO.read(f).getHeight(); file.setHeight(height); Logger.debug(this, "File height=" + height); int width = javax.imageio.ImageIO.read(f).getWidth(); file.setWidth(width); Logger.debug(this, "File width=" + width); long size = (f.length() / 1024); WebAssetFactory.createAsset(file, userId, folder); } else { WebAssetFactory.createAsset(file, userId, folder); } WorkingCache.addToWorkingAssetToCache(file); _setFilePermissions(folder, file, user); fileCounter += 1; if ((subcmd != null) && subcmd.equals(com.dotmarketing.util.Constants.PUBLISH)) { try { PublishFactory.publishAsset(file, httpReq); if (fileCounter > 1) { SessionMessages.add(req, "message", "message.file_asset.save"); } else { SessionMessages.add(req, "message", "message.fileupload.save"); } } catch (WebAssetException wax) { Logger.error(this, wax.getMessage(), wax); SessionMessages.add(req, "error", "message.webasset.published.failed"); } } } } } if (filterError) { customMessage = customMessage.substring(0, customMessage.lastIndexOf(",")); SessionMessages.add(req, "custommessage", customMessage); } } catch (IOException e) { Logger.error(this, "Exception saving file: " + e.getMessage()); throw new ActionException(e.getMessage()); } } |
00
| Code Sample 1:
private void backupOriginalFile(String myFile) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S"); String datePortion = format.format(date); try { FileInputStream fis = new FileInputStream(myFile); FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html"); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); fis.close(); fos.close(); System.out.println("**** Backup of file made."); } catch (Exception e) { System.out.println(e); } }
Code Sample 2:
static void test() throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; Savepoint sp = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); st = conn.createStatement(); String sql = "update user set money=money-10 where id=1"; st.executeUpdate(sql); sp = conn.setSavepoint(); sql = "update user set money=money-10 where id=3"; st.executeUpdate(sql); sql = "select money from user where id=2"; rs = st.executeQuery(sql); float money = 0.0f; if (rs.next()) { money = rs.getFloat("money"); } if (money > 300) throw new RuntimeException("�Ѿ��������ֵ��"); sql = "update user set money=money+10 where id=2"; st.executeUpdate(sql); conn.commit(); } catch (RuntimeException e) { if (conn != null && sp != null) { conn.rollback(sp); conn.commit(); } throw e; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { JdbcUtils.free(rs, st, conn); } } |
11
| Code Sample 1:
public String encryptPassword(String password) { StringBuffer encPasswd = new StringBuffer(); try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); } } catch (NoSuchAlgorithmException ex) { } return encPasswd.toString(); }
Code Sample 2:
protected void innerProcess(CrawlURI curi) throws InterruptedException { if (!curi.isHttpTransaction()) { return; } if (!TextUtils.matches("^text.*$", curi.getContentType())) { return; } long maxsize = DEFAULT_MAX_SIZE_BYTES.longValue(); try { maxsize = ((Long) getAttribute(curi, ATTR_MAX_SIZE_BYTES)).longValue(); } catch (AttributeNotFoundException e) { logger.severe("Missing max-size-bytes attribute when processing " + curi.toString()); } if (maxsize < curi.getContentSize() && maxsize > -1) { return; } String regexpr = ""; try { regexpr = (String) getAttribute(curi, ATTR_STRIP_REG_EXPR); } catch (AttributeNotFoundException e2) { logger.severe("Missing strip-reg-exp when processing " + curi.toString()); return; } ReplayCharSequence cs = null; try { cs = curi.getHttpRecorder().getReplayCharSequence(); } catch (Exception e) { curi.addLocalizedError(this.getName(), e, "Failed get of replay char sequence " + curi.toString() + " " + e.getMessage()); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr.length() == 0) { s = cs.toString(); } else { Matcher m = TextUtils.getMatcher(regexpr, cs); s = m.replaceAll(" "); TextUtils.recycleMatcher(m); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); if (logger.isLoggable(Level.FINEST)) { logger.finest("Recalculated content digest for " + curi.toString() + " old: " + Base32.encode((byte[]) curi.getContentDigest()) + ", new: " + Base32.encode(newDigestValue)); } curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } } |
00
| Code Sample 1:
public static String getMD5(String password) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (byte aB : b) { sb.append((Integer.toHexString((aB & 0xFF) | 0x100)).substring(1, 3)); } return sb.toString(); }
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 version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } |
11
| Code Sample 1:
public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void launchJob(final String workingDir, final AppConfigType appConfig) throws FaultType { logger.info("called for job: " + jobID); MessageContext mc = MessageContext.getCurrentContext(); HttpServletRequest req = (HttpServletRequest) mc.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); String clientDN = (String) req.getAttribute(GSIConstants.GSI_USER_DN); if (clientDN != null) { logger.info("Client's DN: " + clientDN); } else { clientDN = "Unknown client"; } String remoteIP = req.getRemoteAddr(); SOAPService service = mc.getService(); String serviceName = service.getName(); if (serviceName == null) { serviceName = "Unknown service"; } if (appConfig.isParallel()) { if (AppServiceImpl.drmaaInUse) { if (AppServiceImpl.drmaaPE == null) { logger.error("drmaa.pe property must be specified in opal.properties " + "for parallel execution using DRMAA"); throw new FaultType("drmaa.pe property must be specified in opal.properties " + "for parallel execution using DRMAA"); } if (AppServiceImpl.mpiRun == null) { logger.error("mpi.run property must be specified in opal.properties " + "for parallel execution using DRMAA"); throw new FaultType("mpi.run property must be specified in " + "opal.properties for parallel execution " + "using DRMAA"); } } else if (!AppServiceImpl.globusInUse) { if (AppServiceImpl.mpiRun == null) { logger.error("mpi.run property must be specified in opal.properties " + "for parallel execution without using Globus"); throw new FaultType("mpi.run property must be specified in " + "opal.properties for parallel execution " + "without using Globus"); } } if (jobIn.getNumProcs() == null) { logger.error("Number of processes unspecified for parallel job"); throw new FaultType("Number of processes unspecified for parallel job"); } else if (jobIn.getNumProcs().intValue() > AppServiceImpl.numProcs) { logger.error("Processors required - " + jobIn.getNumProcs() + ", available - " + AppServiceImpl.numProcs); throw new FaultType("Processors required - " + jobIn.getNumProcs() + ", available - " + AppServiceImpl.numProcs); } } try { status.setCode(GramJob.STATUS_PENDING); status.setMessage("Launching executable"); status.setBaseURL(new URI(AppServiceImpl.tomcatURL + jobID)); } catch (MalformedURIException mue) { logger.error("Cannot convert base_url string to URI - " + mue.getMessage()); throw new FaultType("Cannot convert base_url string to URI - " + mue.getMessage()); } if (!AppServiceImpl.dbInUse) { AppServiceImpl.statusTable.put(jobID, status); } else { Connection conn = null; try { conn = DriverManager.getConnection(AppServiceImpl.dbUrl, AppServiceImpl.dbUser, AppServiceImpl.dbPasswd); } catch (SQLException e) { logger.error("Cannot connect to database - " + e.getMessage()); throw new FaultType("Cannot connect to database - " + e.getMessage()); } String time = new SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.US).format(new Date()); String sqlStmt = "insert into job_status(job_id, code, message, base_url, " + "client_dn, client_ip, service_name, start_time, last_update) " + "values ('" + jobID + "', " + status.getCode() + ", " + "'" + status.getMessage() + "', " + "'" + status.getBaseURL() + "', " + "'" + clientDN + "', " + "'" + remoteIP + "', " + "'" + serviceName + "', " + "'" + time + "', " + "'" + time + "');"; try { Statement stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); conn.close(); } catch (SQLException e) { logger.error("Cannot insert job status into database - " + e.getMessage()); throw new FaultType("Cannot insert job status into database - " + e.getMessage()); } } String args = appConfig.getDefaultArgs(); if (args == null) { args = jobIn.getArgList(); } else { String userArgs = jobIn.getArgList(); if (userArgs != null) args += " " + userArgs; } if (args != null) { args = args.trim(); } logger.debug("Argument list: " + args); if (AppServiceImpl.drmaaInUse) { String cmd = null; String[] argsArray = null; if (appConfig.isParallel()) { cmd = "/bin/sh"; String newArgs = AppServiceImpl.mpiRun + " -machinefile $TMPDIR/machines" + " -np " + jobIn.getNumProcs() + " " + appConfig.getBinaryLocation(); if (args != null) { args = newArgs + " " + args; } else { args = newArgs; } logger.debug("CMD: " + args); argsArray = new String[] { "-c", args }; } else { cmd = appConfig.getBinaryLocation(); if (args == null) args = ""; logger.debug("CMD: " + cmd + " " + args); argsArray = args.split(" "); } try { logger.debug("Working directory: " + workingDir); JobTemplate jt = session.createJobTemplate(); if (appConfig.isParallel()) jt.setNativeSpecification("-pe " + AppServiceImpl.drmaaPE + " " + jobIn.getNumProcs()); jt.setRemoteCommand(cmd); jt.setArgs(argsArray); jt.setJobName(jobID); jt.setWorkingDirectory(workingDir); jt.setErrorPath(":" + workingDir + "/stderr.txt"); jt.setOutputPath(":" + workingDir + "/stdout.txt"); drmaaJobID = session.runJob(jt); logger.info("DRMAA job has been submitted with id " + drmaaJobID); session.deleteJobTemplate(jt); } catch (Exception ex) { logger.error(ex); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via DRMAA - " + ex.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } status.setCode(GramJob.STATUS_ACTIVE); status.setMessage("Execution in progress"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } } else if (AppServiceImpl.globusInUse) { String rsl = null; if (appConfig.isParallel()) { rsl = "&(directory=" + workingDir + ")" + "(executable=" + appConfig.getBinaryLocation() + ")" + "(count=" + jobIn.getNumProcs() + ")" + "(jobtype=mpi)" + "(stdout=stdout.txt)" + "(stderr=stderr.txt)"; } else { rsl = "&(directory=" + workingDir + ")" + "(executable=" + appConfig.getBinaryLocation() + ")" + "(stdout=stdout.txt)" + "(stderr=stderr.txt)"; } if (args != null) { args = "\"" + args + "\""; args = args.replaceAll("[\\s]+", "\" \""); rsl += "(arguments=" + args + ")"; } logger.debug("RSL: " + rsl); try { job = new GramJob(rsl); GlobusCredential globusCred = new GlobusCredential(AppServiceImpl.serviceCertPath, AppServiceImpl.serviceKeyPath); GSSCredential gssCred = new GlobusGSSCredentialImpl(globusCred, GSSCredential.INITIATE_AND_ACCEPT); job.setCredentials(gssCred); job.addListener(this); job.request(AppServiceImpl.gatekeeperContact); } catch (Exception ge) { logger.error(ge); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via Globus - " + ge.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } } else { String cmd = null; if (appConfig.isParallel()) { cmd = new String(AppServiceImpl.mpiRun + " " + "-np " + jobIn.getNumProcs() + " " + appConfig.getBinaryLocation()); } else { cmd = new String(appConfig.getBinaryLocation()); } if (args != null) { cmd += " " + args; } logger.debug("CMD: " + cmd); try { logger.debug("Working directory: " + workingDir); proc = Runtime.getRuntime().exec(cmd, null, new File(workingDir)); stdoutThread = writeStdOut(proc, workingDir); stderrThread = writeStdErr(proc, workingDir); } catch (IOException ioe) { logger.error(ioe); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via fork - " + ioe.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } status.setCode(GramJob.STATUS_ACTIVE); status.setMessage("Execution in progress"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } } new Thread() { public void run() { try { waitForCompletion(); } catch (FaultType f) { logger.error(f); synchronized (status) { status.notifyAll(); } return; } if (AppServiceImpl.drmaaInUse || !AppServiceImpl.globusInUse) { done = true; status.setCode(GramJob.STATUS_STAGE_OUT); status.setMessage("Writing output metadata"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update status database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } } } try { if (!AppServiceImpl.drmaaInUse && !AppServiceImpl.globusInUse) { try { logger.debug("Waiting for all outputs to be written out"); stdoutThread.join(); stderrThread.join(); logger.debug("All outputs successfully written out"); } catch (InterruptedException ignore) { } } File stdOutFile = new File(workingDir + File.separator + "stdout.txt"); if (!stdOutFile.exists()) { throw new IOException("Standard output missing for execution"); } File stdErrFile = new File(workingDir + File.separator + "stderr.txt"); if (!stdErrFile.exists()) { throw new IOException("Standard error missing for execution"); } if (AppServiceImpl.archiveData) { logger.debug("Archiving output files"); File f = new File(workingDir); File[] outputFiles = f.listFiles(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(workingDir + File.separator + jobID + ".zip")); byte[] buf = new byte[1024]; try { for (int i = 0; i < outputFiles.length; i++) { FileInputStream in = new FileInputStream(outputFiles[i]); out.putNextEntry(new ZipEntry(outputFiles[i].getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); } catch (IOException e) { logger.error(e); logger.error("Error not fatal - moving on"); } } File f = new File(workingDir); File[] outputFiles = f.listFiles(); OutputFileType[] outputFileObj = new OutputFileType[outputFiles.length - 2]; int j = 0; for (int i = 0; i < outputFiles.length; i++) { if (outputFiles[i].getName().equals("stdout.txt")) { outputs.setStdOut(new URI(AppServiceImpl.tomcatURL + jobID + "/stdout.txt")); } else if (outputFiles[i].getName().equals("stderr.txt")) { outputs.setStdErr(new URI(AppServiceImpl.tomcatURL + jobID + "/stderr.txt")); } else { OutputFileType next = new OutputFileType(); next.setName(outputFiles[i].getName()); next.setUrl(new URI(AppServiceImpl.tomcatURL + jobID + "/" + outputFiles[i].getName())); outputFileObj[j++] = next; } } outputs.setOutputFile(outputFileObj); } catch (IOException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot retrieve outputs after finish - " + e.getMessage()); logger.error(e); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } } synchronized (status) { status.notifyAll(); } return; } if (!AppServiceImpl.dbInUse) { AppServiceImpl.outputTable.put(jobID, outputs); } else { Connection conn = null; try { conn = DriverManager.getConnection(AppServiceImpl.dbUrl, AppServiceImpl.dbUser, AppServiceImpl.dbPasswd); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot connect to database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } String sqlStmt = "insert into job_output(job_id, std_out, std_err) " + "values ('" + jobID + "', " + "'" + outputs.getStdOut().toString() + "', " + "'" + outputs.getStdErr().toString() + "');"; Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update job output database after finish - " + e.getMessage()); logger.error(e); try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } synchronized (status) { status.notifyAll(); } return; } OutputFileType[] outputFile = outputs.getOutputFile(); for (int i = 0; i < outputFile.length; i++) { sqlStmt = "insert into output_file(job_id, name, url) " + "values ('" + jobID + "', " + "'" + outputFile[i].getName() + "', " + "'" + outputFile[i].getUrl().toString() + "');"; try { stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update output_file DB after finish - " + e.getMessage()); logger.error(e); try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } synchronized (status) { status.notifyAll(); } return; } } } if (terminatedOK()) { status.setCode(GramJob.STATUS_DONE); status.setMessage("Execution complete - " + "check outputs to verify successful execution"); } else { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Execution failed"); } if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update status database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } } AppServiceImpl.jobTable.remove(jobID); synchronized (status) { status.notifyAll(); } logger.info("Execution complete for job: " + jobID); } }.start(); } |
11
| Code Sample 1:
public static void reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, out); writer.setPdfVersion(PdfWriter.VERSION_1_3); writer.setFullCompression(); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STRENGTH128BITS, password, null, securityType); } final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } else if (base_url != null) { document.addTitle(base_url); } final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } else { document.addCreator(IHtmlToPdfTransformer.VERSION); } final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.addProducer(sproducer); } else { document.addProducer(IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer); } document.open(); } PdfImportedPage page; for (int j = 0; j < n; ) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } } document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext(); ) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i).replaceAll("<pagecount>", "" + n); final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } else { reader = new PdfReader(tmp2.getAbsolutePath()); } final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STRENGTH128BITS, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } if (reason != null) { sap.setReason(reason); } if (location != null) { sap.setLocation(location); } stp.close(); oldOut.flush(); } } catch (final Exception e) { throw new CConvertException("ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } finally { try { tmp.delete(); } catch (final Exception ignore) { } try { tmp2.delete(); } catch (final Exception ignore) { } } }
Code Sample 2:
public boolean copy(File src, File dest, byte[] b) { if (src.isDirectory()) { String[] ss = src.list(); for (int i = 0; i < ss.length; i++) if (!copy(new File(src, ss[i]), new File(dest, ss[i]), b)) return false; return true; } delete(dest); dest.getParentFile().mkdirs(); try { FileInputStream fis = new FileInputStream(src); try { FileOutputStream fos = new FileOutputStream(dest); try { int read; while ((read = fis.read(b)) != -1) fos.write(b, 0, read); } finally { try { fos.close(); } catch (IOException ignore) { } register(dest); } } finally { fis.close(); } if (log.isDebugEnabled()) log.debug("Success: M-COPY " + src + " -> " + dest); return true; } catch (IOException e) { log.error("Failed: M-COPY " + src + " -> " + dest, e); return false; } } |
00
| Code Sample 1:
public XlsBook(String path) throws IOException { boolean isHttp = path.startsWith("http://"); InputStream is = null; if (isHttp) { URL url = new URL(path); is = url.openStream(); } else { File file = new File(path); is = new FileInputStream(file); } workbook = XlsBook.createWorkbook(is); is.close(); }
Code Sample 2:
public char check(String password) { if (captchaRandom.equals("null")) { return 's'; } if (captchaRandom.equals("used")) { return 'm'; } String encryptionBase = secret + captchaRandom; if (!alphabet.equals(ALPHABET_DEFAULT) || letters != LETTERS_DEFAULT) { encryptionBase += ":" + alphabet + ":" + letters; } MessageDigest md5; byte[] digest = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; try { md5 = MessageDigest.getInstance("MD5"); md5.update(encryptionBase.getBytes()); digest = md5.digest(); } catch (NoSuchAlgorithmException e) { } String correctPassword = ""; int index; for (int i = 0; i < letters; i++) { index = (digest[i] + 256) % 256 % alphabet.length(); correctPassword += alphabet.substring(index, index + 1); } if (!password.equals(correctPassword)) { return 'w'; } else { captchaRandom = "used"; return 't'; } } |
11
| Code Sample 1:
public List<String> query(String query) throws IOException { List<String> list = new LinkedList<String>(); query = URLEncoder.encode(query, "UTF-8"); String queryurl = baseurl + "?type=tuples&lang=itql&format=csv&query=" + query; URL url = new URL(queryurl); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = reader.readLine(); while (line != null) { list.add(line); line = reader.readLine(); } reader.close(); return list; }
Code Sample 2:
private String getData(String method, String arg) { try { URL url; String str; StringBuilder strBuilder; BufferedReader stream; url = new URL(API_BASE_URL + "/2.1/" + method + "/en/xml/" + API_KEY + "/" + URLEncoder.encode(arg, "UTF-8")); stream = new BufferedReader(new InputStreamReader(url.openStream())); strBuilder = new StringBuilder(); while ((str = stream.readLine()) != null) { strBuilder.append(str); } stream.close(); return strBuilder.toString(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } } |
11
| Code Sample 1:
private void exportJar(File root, List<File> list, Manifest manifest) throws Exception { JarOutputStream jarOut = null; FileInputStream fin = null; try { jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest); for (int i = 0; i < list.size(); i++) { String filename = list.get(i).getAbsolutePath(); filename = filename.substring(root.getAbsolutePath().length() + 1); fin = new FileInputStream(list.get(i)); JarEntry entry = new JarEntry(filename.replace('\\', '/')); jarOut.putNextEntry(entry); byte[] buf = new byte[4096]; int read; while ((read = fin.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); jarOut.flush(); } } finally { if (fin != null) { try { fin.close(); } catch (Exception e) { ExceptionOperation.operate(e); } } if (jarOut != null) { try { jarOut.close(); } catch (Exception e) { } } } }
Code Sample 2:
public static File copyFileAs(String path, String newName) { File src = new File(path); File dest = new File(newName); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; } |
11
| Code Sample 1:
public static void unzip(File zipInFile, File outputDir) throws Exception { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(zipInFile); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipInFile)); ZipEntry entry = (ZipEntry) zipInputStream.getNextEntry(); File curOutDir = outputDir; while (entry != null) { if (entry.isDirectory()) { curOutDir = new File(curOutDir, entry.getName()); curOutDir.mkdirs(); continue; } File outFile = new File(curOutDir, entry.getName()); File tempDir = outFile.getParentFile(); if (!tempDir.exists()) tempDir.mkdirs(); outFile.createNewFile(); BufferedOutputStream outstream = new BufferedOutputStream(new FileOutputStream(outFile)); int n; byte[] buf = new byte[1024]; while ((n = zipInputStream.read(buf, 0, 1024)) > -1) outstream.write(buf, 0, n); outstream.flush(); outstream.close(); zipInputStream.closeEntry(); entry = zipInputStream.getNextEntry(); } zipInputStream.close(); zipFile.close(); }
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.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } } |
00
| Code Sample 1:
@ActionMethod public void download() throws IOException { final JPanel message = new JPanel(new GridBagLayout()); final GridBagConstraints gbcLabel = new GridBagConstraints(); final GridBagConstraints gbcField = new GridBagConstraints(); gbcLabel.weightx = 0.0; gbcField.weightx = 1.0; gbcField.fill = GridBagConstraints.HORIZONTAL; gbcField.insets = new Insets(2, 2, 2, 2); final JTextField deviceField, fullnameField, versionField; deviceField = new JTextField(); fullnameField = new JTextField(); versionField = new JTextField(); gbcField.gridwidth = GridBagConstraints.REMAINDER; message.add(new JLabel("device"), gbcLabel); message.add(deviceField, gbcField); message.add(new JLabel("fullname"), gbcLabel); message.add(fullnameField, gbcField); message.add(new JLabel("version"), gbcLabel); message.add(versionField, gbcField); final int result = JOptionPane.showConfirmDialog(frame, message, "Download parameters", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result != JOptionPane.OK_OPTION) { return; } final String device = deviceField.getText(); final String fullname = fullnameField.getText(); final String version = versionField.getText(); final URL url = new URL("http://127.0.0.1:" + testPort + "/databases/" + fullname + "?device=" + device + "&version=" + version); final HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestProperty(Http11Header.AUTHORIZATION, "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); con.setRequestProperty(Http11Header.WWW_AUTHENTICATE, "Basic realm=\"karatasi\""); final InputStream in = con.getInputStream(); try { final int fileResult = fileChooser.showSaveDialog(frame); if (fileResult != JFileChooser.APPROVE_OPTION) { return; } final OutputStream out = new FileOutputStream(fileChooser.getSelectedFile()); try { Util.copy(in, out); } finally { out.close(); } } finally { in.close(); } }
Code Sample 2:
public static void copyFile(String oldPath, String newPath) throws IOException { 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; fs.write(buffer, 0, byteread); } inStream.close(); } } |
00
| Code Sample 1:
void search(String query, String display) { try { String safeUrl; try { safeUrl = baseUrl + URLEncoder.encode(query, "UTF-8"); } catch (UnsupportedEncodingException ex) { safeUrl = baseUrl + query; Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } URL url_connection = new URL(safeUrl); url_connection.openConnection(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(url_connection.openStream()); Vector<SoundEntry> entries = new Vector<SoundEntry>(); Vector<String> path = new Vector<String>(); path.add("Results"); for (Hashtable<String, String> field : DocumentManager.getSubTable(document, path, "Entry")) { entries.add(new SoundEntry(field)); } int index; ButtonTabComponent btc = new ButtonTabComponent(tpnResults); btc.setInheritsPopupMenu(true); if (entries.isEmpty()) { JLabel msg = new JLabel("No results found"); tpnResults.add(display, msg); index = tpnResults.indexOfComponent(msg); } else { Enumeration<String> iter = entries.firstElement().fields.keys(); while (iter.hasMoreElements()) { String field = iter.nextElement(); if (!header.contains(field)) { header.addDefaultField(field); } } JTable result = new JTable(); Vector<String> fieldNames = header.getShownNames(); DefaultTableModel model = new DefaultTableModel(fieldNames, 0); for (SoundEntry entry : entries) { model.addRow(entry.getShownFields(header.getShownNames())); } result.setModel(model); result.setColumnSelectionAllowed(false); result.setSelectionMode(0); result.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { ((JTable) e.getSource()).getComponentAt(e.getPoint()); int row = ((JTable) e.getSource()).rowAtPoint(e.getPoint()); SoundEntry entry = ((ButtonTabComponent) tpnResults.getTabComponentAt(tpnResults.getSelectedIndex())).records.get(row); String file = entry.fields.get("FileName"); String title = entry.fields.get("Title"); if (file != null && !file.isEmpty()) { try { AudioSource src = new AudioSource(new URL(file), title); src.attachAudioStateListener(new AudioStateListener() { public void AudioStateReceived(AudioStateEvent event) { if (event.getAudioState() != AudioStateEvent.AudioState.CLOSED && event.getAudioState() != AudioStateEvent.AudioState.CLOSING) { llblStatus.setText(event.getAudioState() + ": " + ((AudioSource) event.getSource()).getTitle().toString()); } } }); audioPlayer.open(src); } catch (Exception j) { } } } }); JScrollPane scrollPane = new JScrollPane(result); tpnResults.add(display, scrollPane); index = tpnResults.indexOfComponent(scrollPane); btc.records = entries; } tpnResults.setTabComponentAt(index, btc); tpnResults.setSelectedIndex(index); } catch (SAXException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } }
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 void connected(String address, int port) { connected = true; try { if (localConnection) { byte key[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; si.setEncryptionKey(key); } else { saveData(address, port); MessageDigest mds = MessageDigest.getInstance("SHA"); mds.update(connectionPassword.getBytes("UTF-8")); si.setEncryptionKey(mds.digest()); } if (!si.login(username, password)) { si.disconnect(); connected = false; showErrorMessage(this, "Authentication Failure"); restore(); return; } SwingUtilities.invokeLater(new Runnable() { public void run() { connectionLabel.setText(""); progressLabel = new JLabel("Loading... Please wait."); progressLabel.setOpaque(true); progressLabel.setBackground(Color.white); replaceComponent(progressLabel); cancelButton.setEnabled(true); xx.remove(helpButton); } }); } catch (Exception e) { System.out.println("connected: Exception: " + e + "\r\n"); } ; }
Code Sample 2:
private ScrollingGraphicalViewer createGraphicalViewer(final Composite parent) { final ScrollingGraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); _root = new ScalableRootEditPart(); viewer.setRootEditPart(_root); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); viewer.setEditPartFactory(getEditPartFactory()); viewer.setContents(getEditorInput().getAdapter(ScannedMap.class)); return viewer; } |
11
| Code Sample 1:
private static void loadFromZip() { InputStream in = Resources.class.getResourceAsStream("data.zip"); if (in == null) { return; } ZipInputStream zipIn = new ZipInputStream(in); try { while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String entryName = entry.getName(); if (!entryName.startsWith("/")) { entryName = "/" + entryName; } ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(zipIn, out); zipIn.closeEntry(); FILES.put(entryName, out.toByteArray()); } zipIn.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
private synchronized Frame addFrame(INSERT_TYPE type, File source) throws IOException { if (source == null) throw new NullPointerException("Parameter 'source' is null"); if (!source.exists()) throw new IOException("File does not exist: " + source.getAbsolutePath()); if (source.length() <= 0) throw new IOException("File is empty: " + source.getAbsolutePath()); File newLocation = new File(Settings.getPropertyString(ConstantKeys.project_dir), formatFileName(frames_.size())); if (newLocation.compareTo(source) != 0) { switch(type) { case MOVE: source.renameTo(newLocation); break; case COPY: FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(newLocation).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); break; } } Frame f = new Frame(newLocation); f.createThumbNail(); frames_.add(f); return f; } |
00
| Code Sample 1:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
@Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; } |
11
| Code Sample 1:
public static void gunzip(File gzippedFile, File destinationFile) throws IOException { int buffer = 2048; FileInputStream in = new FileInputStream(gzippedFile); GZIPInputStream zipin = new GZIPInputStream(in); byte[] data = new byte[buffer]; FileOutputStream out = new FileOutputStream(destinationFile); int length; while ((length = zipin.read(data, 0, buffer)) != -1) out.write(data, 0, length); out.close(); zipin.close(); }
Code Sample 2:
private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } } |
00
| Code Sample 1:
@Override public void action(String msg, String uri, Gateway gateway) throws Exception { String city = "成都"; if (msg.indexOf("#") != -1) { city = msg.substring(msg.indexOf("#") + 1); } String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather?theCityCode={city}&theUserID="; url = url.replace("{city}", URLEncoder.encode(city, "UTF8")); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); if (conn.getResponseCode() == 200) { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(conn.getInputStream()); List strings = doc.getRootElement().getChildren(); String[] sugguestions = getText(strings.get(6)).split("\n"); StringBuffer buffer = new StringBuffer(); buffer.append("欢迎使用MapleSMS的天气服务!\n"); buffer.append("你查询的是 " + getText(strings.get(1)) + "的天气。\n"); buffer.append(getText(strings.get(4)) + "。\n"); buffer.append(getText(strings.get(5)) + "。\n"); buffer.append(sugguestions[0] + "\n"); buffer.append(sugguestions[1] + "\n"); buffer.append(sugguestions[7] + "\n"); buffer.append("感谢你使用MapleSMS的天气服务!祝你愉快!"); gateway.sendSMS(uri, buffer.toString()); } else { gateway.sendSMS(uri, "对不起,你输入的城市格式有误,请检查后再试~"); } }
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); } |
11
| Code Sample 1:
public static File unGzip(File infile, boolean deleteGzipfileOnSuccess) throws IOException { GZIPInputStream gin = new GZIPInputStream(new FileInputStream(infile)); File outFile = new File(infile.getParent(), infile.getName().replaceAll("\\.gz$", "")); FileOutputStream fos = new FileOutputStream(outFile); byte[] buf = new byte[100000]; int len; while ((len = gin.read(buf)) > 0) fos.write(buf, 0, len); gin.close(); fos.close(); if (deleteGzipfileOnSuccess) infile.delete(); return outFile; }
Code Sample 2:
public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); } |
00
| Code Sample 1:
public int fileUpload(File pFile, String uploadName, Hashtable pValue) throws Exception { int res = 0; MultipartEntity reqEntity = new MultipartEntity(); if (uploadName != null) { FileBody bin = new FileBody(pFile); reqEntity.addPart(uploadName, bin); } Enumeration<String> enm = pValue.keys(); String key; while (enm.hasMoreElements()) { key = enm.nextElement(); reqEntity.addPart(key, new StringBody("" + pValue.get(key))); } httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost); HttpEntity resEntity = response.getEntity(); res = response.getStatusLine().getStatusCode(); close(); return res; }
Code Sample 2:
@SuppressWarnings("unused") private String getMD5(String value) { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return ""; } md5.reset(); md5.update(value.getBytes()); byte[] messageDigest = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } String hashedPassword = hexString.toString(); return hashedPassword; } |
11
| Code Sample 1:
public void testAddingEntries() throws Exception { DiskCache c = new DiskCache(); { c.setRoot(rootFolder.getAbsolutePath()); c.setHtmlExtension("htm"); c.setPropertiesExtension("txt"); assertEquals("htm", c.getHtmlExtension()); assertEquals("txt", c.getPropertiesExtension()); assertEquals(rootFolder.getAbsolutePath(), c.getRoot()); } String key1 = "cat1/key1"; String key2 = "cat1/key2"; try { try { { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(300005L); i.setTranslationCount(10); i.setEncoding("ISO-8859-7"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = new ByteArrayInputStream(greekTextBytes); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } c.storeInCache(key1, i); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key2, null); CacheItem i = c.getOrCreateCacheEntry(key2); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(350000L); i.setTranslationCount(11); i.setEncoding("ISO-8859-1"); i.setHeader(new ResponseHeaderImpl("Test3", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test4", new String[] { "Value1" })); String englishText = "Hello this is another example"; { InputStream input = new ByteArrayInputStream(englishText.getBytes("ISO-8859-1")); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[29]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test3", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test4", h.getName()); assertEquals("[Value1]", Arrays.toString(h.getValues())); } } } c.storeInCache(key2, i); assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-1"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(englishText, w.toString()); } } { CacheItem i = c.getOrCreateCacheEntry(key1); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); } } finally { c.removeCacheEntry(key1, null); } } finally { c.removeCacheEntry(key2, null); } }
Code Sample 2:
public String merge(int width, int height) throws Exception { htErrors.clear(); sendGetImageRequests(width, height); Vector files = new Vector(); ConcurrentHTTPTransactionHandler c = new ConcurrentHTTPTransactionHandler(); c.setCache(cache); c.checkIfModified(false); for (int i = 0; i < vImageUrls.size(); i++) { if ((String) vImageUrls.get(i) != null) { c.register((String) vImageUrls.get(i)); } else { } } c.doTransactions(); vTransparency = new Vector(); for (int i = 0; i < vImageUrls.size(); i++) { if (vImageUrls.get(i) != null) { String path = c.getResponseFilePath((String) vImageUrls.get(i)); if (path != null) { String contentType = c.getHeaderValue((String) vImageUrls.get(i), "content-type"); if (contentType.startsWith("image")) { files.add(path); vTransparency.add(htTransparency.get(vRank.get(i))); } } } } if (files.size() > 1) { File output = TempFiles.getFile(); String path = output.getPath(); ImageMerger.mergeAndSave(files, vTransparency, path, ImageMerger.GIF); imageName = output.getName(); imagePath = output.getPath(); return (imageName); } else if (files.size() == 1) { File f = new File((String) files.get(0)); File out = TempFiles.getFile(); BufferedInputStream is = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(out)); byte buf[] = new byte[1024]; for (int nRead; (nRead = is.read(buf, 0, 1024)) > 0; os.write(buf, 0, nRead)) ; os.flush(); os.close(); is.close(); imageName = out.getName(); return imageName; } else return ""; } |
00
| Code Sample 1:
@Override public void fileUpload(UploadEvent uploadEvent) { FileOutputStream tmpOutStream = null; try { tmpUpload = File.createTempFile("projectImport", ".xml"); tmpOutStream = new FileOutputStream(tmpUpload); IOUtils.copy(uploadEvent.getInputStream(), tmpOutStream); panel.setGeneralMessage("Project file " + uploadEvent.getFileName() + " uploaded and ready for import."); } catch (Exception e) { panel.setGeneralMessage("Could not upload file: " + e); } finally { if (tmpOutStream != null) { IOUtils.closeQuietly(tmpOutStream); } } }
Code Sample 2:
private void bubbleSort(int[] mas) { boolean t = true; int temp = 0; while (t) { t = false; for (int i = 0; i < mas.length - 1; i++) { if (mas[i] > mas[i + 1]) { temp = mas[i]; mas[i] = mas[i + 1]; mas[i + 1] = temp; t = true; } } } } |
00
| Code Sample 1:
public static String sha1(String clearText, String seed) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update((seed + clearText).getBytes()); return convertToHex(md.digest()); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
Code Sample 2:
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(); } } |
11
| Code Sample 1:
public void copy(String pathFileIn, String pathFileOut) { try { File inputFile = new File(pathFileIn); File outputFile = new File(pathFileOut); FileReader in = new FileReader(inputFile); File outDir = new File(DirOut); if (!outDir.exists()) outDir.mkdirs(); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); this.printColumn(inputFile.getName(), outputFile.getPath()); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private 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(); } } |
11
| Code Sample 1:
public static void generate(final InputStream input, String format, Point dimension, IPath outputLocation) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = outputLocation.toFile(); ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); return; } } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
Code Sample 2:
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); try { boolean isMultipart = FileUpload.isMultipartContent(request); Store storeInstance = getStoreInstance(request); if (isMultipart) { Map fields = new HashMap(); Vector files = new Vector(); List items = diskFileUpload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fields.put(item.getFieldName(), item.getString()); } else { if (!StringUtils.isBlank(item.getName())) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); IOUtils.copy(item.getInputStream(), baos); MailPartObj part = new MailPartObj(); part.setAttachent(baos.toByteArray()); part.setContentType(item.getContentType()); part.setName(item.getName()); part.setSize(item.getSize()); files.addElement(part); } catch (Exception ex) { } finally { IOUtils.closeQuietly(baos); } } } } if (files.size() > 0) { storeInstance.send(files, 0, Charset.defaultCharset().displayName()); } } else { errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null")); request.setAttribute("exception", "The form is null"); request.setAttribute("newLocation", null); doTrace(request, DLog.ERROR, getClass(), "The form is null"); } } catch (Exception ex) { String errorMessage = ExceptionUtilities.parseMessage(ex); if (errorMessage == null) { errorMessage = "NullPointerException"; } errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage)); request.setAttribute("exception", errorMessage); doTrace(request, DLog.ERROR, getClass(), errorMessage); } finally { } if (errors.isEmpty()) { doTrace(request, DLog.INFO, getClass(), "OK"); return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD); } else { saveErrors(request, errors); return mapping.findForward(Constants.ACTION_FAIL_FORWARD); } } |
11
| Code Sample 1:
public static void copy(File source, File destination) throws IOException { InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); in.close(); out.close(); }
Code Sample 2:
public void save() { final JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileFilter() { public String getDescription() { return "PDF File"; } public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf"); } }); if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return; } File targetFile = fc.getSelectedFile(); if (!targetFile.getName().toLowerCase().endsWith(".pdf")) { targetFile = new File(targetFile.getParentFile(), targetFile.getName() + ".pdf"); } if (targetFile.exists()) { if (JOptionPane.showConfirmDialog(this, "Do you want to overwrite the file?") != JOptionPane.YES_OPTION) { return; } } try { final InputStream is = new FileInputStream(filename); try { final OutputStream os = new FileOutputStream(targetFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); } } finally { os.close(); } } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
public static String md5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException ex) { return password; } }
Code Sample 2:
private static String getUnsaltedHash(String algorithm, String input) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); messageDigest.reset(); messageDigest.update(input.getBytes(Main.DEFAULT_CHARSET)); byte[] digest = messageDigest.digest(); return String.format(Main.DEFAULT_LOCALE, "%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); } |
11
| 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:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
11
| Code Sample 1:
public static void zipFile(String file, String entry) throws IOException { FileInputStream in = new FileInputStream(file); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file + ".zip")); out.putNextEntry(new ZipEntry(entry)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.closeEntry(); out.close(); File fin = new File(file); fin.delete(); }
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.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } } |
11
| Code Sample 1:
public String getHash(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] toChapter1Digest = md.digest(); return Keystore.hexEncode(toChapter1Digest); } catch (Exception e) { logger.error("Error in creating DN hash: " + e.getMessage()); return null; } }
Code Sample 2:
private static String simpleCompute(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("utf-8"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } |
11
| Code Sample 1:
public static void main(String[] args) throws Exception { File rootDir = new File("C:\\dev\\workspace_fgd\\gouvqc_crggid\\WebContent\\WEB-INF\\upload"); File storeDir = new File(rootDir, "storeDir"); File workDir = new File(rootDir, "workDir"); LoggerFacade loggerFacade = new CommonsLoggingLogger(logger); final FileResourceManager frm = new SmbFileResourceManager(storeDir.getPath(), workDir.getPath(), true, loggerFacade); frm.start(); final String resourceId = "811375c8-7cae-4429-9a0e-9222f47dab45"; { if (!frm.resourceExists(resourceId)) { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); FileInputStream inputStream = new FileInputStream(resourceId); frm.createResource(txId, resourceId); OutputStream outputStream = frm.writeResource(txId, resourceId); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); frm.prepareTransaction(txId); frm.commitTransaction(txId); } } for (int i = 0; i < 30; i++) { final int index = i; new Thread() { @Override public void run() { try { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); InputStream inputStream = frm.readResource(resourceId); frm.prepareTransaction(txId); frm.commitTransaction(txId); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (début)"); } String contenu = TikaUtils.getParsedContent(inputStream, "file.pdf"); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (fin)"); } } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } catch (ResourceManagerException e) { throw new RuntimeException(e); } catch (TikaException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }.start(); } Thread.sleep(60000); frm.stop(FileResourceManager.SHUTDOWN_MODE_NORMAL); }
Code Sample 2:
public static void main(String args[]) { String midletClass = null; ; File appletInputFile = null; File deviceInputFile = null; File midletInputFile = null; File htmlOutputFile = null; File appletOutputFile = null; File deviceOutputFile = null; File midletOutputFile = null; List params = new ArrayList(); for (int i = 0; i < args.length; i++) { params.add(args[i]); } Iterator argsIterator = params.iterator(); while (argsIterator.hasNext()) { String arg = (String) argsIterator.next(); argsIterator.remove(); if ((arg.equals("--help")) || (arg.equals("-help"))) { System.out.println(usage()); System.exit(0); } else if (arg.equals("--midletClass")) { midletClass = (String) argsIterator.next(); argsIterator.remove(); } else if (arg.equals("--appletInput")) { appletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceInput")) { deviceInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletInput")) { midletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--htmlOutput")) { htmlOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--appletOutput")) { appletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceOutput")) { deviceOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletOutput")) { midletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } } if (midletClass == null || appletInputFile == null || deviceInputFile == null || midletInputFile == null || htmlOutputFile == null || appletOutputFile == null || deviceOutputFile == null || midletOutputFile == null) { System.out.println(usage()); System.exit(0); } try { DeviceImpl device = null; String descriptorLocation = null; JarFile jar = new JarFile(deviceInputFile); for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorLocation = entry; break; } } if (descriptorLocation != null) { EmulatorContext context = new EmulatorContext() { private DisplayComponent displayComponent = new NoUiDisplayComponent(); private InputMethod inputMethod = new J2SEInputMethod(); private DeviceDisplay deviceDisplay = new J2SEDeviceDisplay(this); private FontManager fontManager = new J2SEFontManager(); private DeviceComponent deviceComponent = new SwingDeviceComponent(true); public DisplayComponent getDisplayComponent() { return displayComponent; } public InputMethod getDeviceInputMethod() { return inputMethod; } public DeviceDisplay getDeviceDisplay() { return deviceDisplay; } public FontManager getDeviceFontManager() { return fontManager; } public InputStream getResourceAsStream(String name) { return MIDletBridge.getCurrentMIDlet().getClass().getResourceAsStream(name); } public DeviceComponent getDeviceComponent() { return deviceComponent; } }; URL[] urls = new URL[1]; urls[0] = deviceInputFile.toURI().toURL(); ClassLoader classLoader = new ExtensionsClassLoader(urls, urls.getClass().getClassLoader()); device = DeviceImpl.create(context, classLoader, descriptorLocation, J2SEDevice.class); } if (device == null) { System.out.println("Error parsing device package: " + descriptorLocation); System.exit(0); } createHtml(htmlOutputFile, device, midletClass, midletOutputFile, appletOutputFile, deviceOutputFile); createMidlet(midletInputFile.toURI().toURL(), midletOutputFile); IOUtils.copyFile(appletInputFile, appletOutputFile); IOUtils.copyFile(deviceInputFile, deviceOutputFile); } catch (IOException ex) { ex.printStackTrace(); } System.exit(0); } |
00
| Code Sample 1:
public static void redirect(String strRequest, PrintWriter sortie) throws Exception { String level = "info."; if (ConnectorServlet.debug) level = "debug."; Log log = LogFactory.getLog(level + "fr.brgm.exows.gml2gsml.GFI"); URL url2Request = new URL(strRequest); URLConnection conn = url2Request.openConnection(); DataInputStream buffin = new DataInputStream(new BufferedInputStream(conn.getInputStream())); String strLine = null; while ((strLine = buffin.readLine()) != null) { sortie.println(strLine); } buffin.close(); }
Code Sample 2:
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 ""; } |
11
| Code Sample 1:
public static String getTextFromUrl(final String url) throws IOException { final String lineSeparator = System.getProperty("line.separator"); InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { final StringBuilder result = new StringBuilder(); inputStreamReader = new InputStreamReader(new URL(url).openStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { result.append(line).append(lineSeparator); } return result.toString(); } finally { InputOutputUtil.close(bufferedReader, inputStreamReader); } }
Code Sample 2:
public URL grabCover(String artist, String title) { if (idf.jCheckBox3.isSelected()) { println("Searching cover for: " + artist); artist = artist.trim(); URL url = null; int searchnumber = 0; try { URL yahoo = new URL("http://www.gracenote.com/search/?query=" + artist.toLowerCase().replaceAll(" ", "+") + "&search_type=artist"); BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream())); println("" + yahoo); String inputLine; String line = ""; while ((inputLine = in.readLine()) != null) line += inputLine; boolean notfound = true; String cut = line; while (notfound) { String search = "<div class=\"album-name large\"><strong>Album:</strong> <a href=\""; if (line.indexOf(search) <= 0) { println("Artist was not found!"); in.close(); return null; } cut = cut.substring(cut.indexOf(search) + search.length()); String test = cut.substring(0, cut.indexOf("\"")); URL secondurl = new URL("http://www.gracenote.com" + test); println("" + secondurl); BufferedReader secin = new BufferedReader(new InputStreamReader(secondurl.openStream())); String secinputLine; String secline = ""; while ((secinputLine = secin.readLine()) != null) secline += secinputLine; if (!(secline.toUpperCase().indexOf(title.toUpperCase()) < 0 && idf.jCheckBox2.isSelected())) { String secsearch = "<div class=\"album-image\"><img src=\""; String seccut = secline.substring(secline.indexOf(secsearch) + secsearch.length()); seccut = seccut.substring(0, seccut.indexOf("\"")); url = new URL("http://www.gracenote.com" + seccut); if (url.toString().indexOf("covers/default") <= 0 && url.toString().indexOf("covers/") > 0) { notfound = false; } } secin.close(); } in.close(); println(url.toString()); } catch (Exception e) { println("error " + e + "\n"); e.printStackTrace(); } return url; } else { return null; } } |
11
| Code Sample 1:
public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); } |
00
| Code Sample 1:
public static String getProgramVersion() { String s = "0"; try { URL url; URLConnection urlConn; DataInputStream dis; url = new URL("http://www.dombosfest.org.yu/log/yamiversion.dat"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); dis = new DataInputStream(urlConn.getInputStream()); while ((dis.readUTF()) != null) { s = dis.readUTF(); } dis.close(); } catch (MalformedURLException mue) { System.out.println("mue:" + mue.getMessage()); } catch (IOException ioe) { System.out.println("ioe:" + ioe.getMessage()); } return s; }
Code Sample 2:
@Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + httpServletRequest.getQueryString()); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + baos.toString()); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); } |
11
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void copyWithClose(InputStream is, OutputStream os) throws IOException { try { IOUtils.copy(is, os); } catch (IOException ioe) { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } } |
11
| Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } |
11
| Code Sample 1:
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long time = System.currentTimeMillis(); String text = request.getParameter("text"); String parsedQueryString = request.getQueryString(); if (text == null) { String[] fonts = new File(ctx.getRealPath("/WEB-INF/fonts/")).list(); text = "accepted params: text,font,size,color,background,nocache,aa,break"; response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<p>"); out.println("Usage: " + request.getServletPath() + "?params[]<BR>"); out.println("Acceptable Params are: <UL>"); out.println("<LI><B>text</B><BR>"); out.println("The body of the image"); out.println("<LI><B>font</B><BR>"); out.println("Available Fonts (in folder '/WEB-INF/fonts/') <UL>"); for (int i = 0; i < fonts.length; i++) { if (!"CVS".equals(fonts[i])) { out.println("<LI>" + fonts[i]); } } out.println("</UL>"); out.println("<LI><B>size</B><BR>"); out.println("An integer, i.e. size=100"); out.println("<LI><B>color</B><BR>"); out.println("in rgb, i.e. color=255,0,0"); out.println("<LI><B>background</B><BR>"); out.println("in rgb, i.e. background=0,0,255"); out.println("transparent, i.e. background=''"); out.println("<LI><B>aa</B><BR>"); out.println("antialias (does not seem to work), aa=true"); out.println("<LI><B>nocache</B><BR>"); out.println("if nocache is set, we will write out the image file every hit. Otherwise, will write it the first time and then read the file"); out.println("<LI><B>break</B><BR>"); out.println("An integer greater than 0 (zero), i.e. break=20"); out.println("</UL>"); out.println("</UL>"); out.println("Example:<BR>"); out.println("<img border=1 src=\"" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100\"><BR>"); out.println("<img border=1 src='" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100'><BR>"); out.println("</body>"); out.println("</html>"); return; } String myFile = (request.getQueryString() == null) ? "empty" : PublicEncryptionFactory.digestString(parsedQueryString).replace('\\', '_').replace('/', '_'); myFile = Config.getStringProperty("PATH_TO_TITLE_IMAGES") + myFile + ".png"; File file = new File(ctx.getRealPath(myFile)); if (!file.exists() || (request.getParameter("nocache") != null)) { StringTokenizer st = null; Iterator i = hm.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); if (parsedQueryString.indexOf(key) > -1) { String val = (String) entry.getValue(); parsedQueryString = UtilMethods.replace(parsedQueryString, key, val); } } st = new StringTokenizer(parsedQueryString, "&"); while (st.hasMoreTokens()) { try { String x = st.nextToken(); String key = x.split("=")[0]; String val = x.split("=")[1]; if ("text".equals(key)) { text = val; } } catch (Exception e) { } } text = URLDecoder.decode(text, "UTF-8"); Logger.debug(this.getClass(), "building title image:" + file.getAbsolutePath()); file.createNewFile(); try { String font_file = "/WEB-INF/fonts/arial.ttf"; if (request.getParameter("font") != null) { font_file = "/WEB-INF/fonts/" + request.getParameter("font"); } font_file = ctx.getRealPath(font_file); float size = 20.0f; if (request.getParameter("size") != null) { size = Float.parseFloat(request.getParameter("size")); } Color background = Color.white; if (request.getParameter("background") != null) { if (request.getParameter("background").equals("transparent")) try { background = new Color(Color.TRANSLUCENT); } catch (Exception e) { } else try { st = new StringTokenizer(request.getParameter("background"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); background = new Color(x, y, z); } catch (Exception e) { } } Color color = Color.black; if (request.getParameter("color") != null) { try { st = new StringTokenizer(request.getParameter("color"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); color = new Color(x, y, z); } catch (Exception e) { Logger.info(this, e.getMessage()); } } int intBreak = 0; if (request.getParameter("break") != null) { try { intBreak = Integer.parseInt(request.getParameter("break")); } catch (Exception e) { } } java.util.ArrayList<String> lines = null; if (intBreak > 0) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); int start = 0; String line = null; int offSet; for (; ; ) { try { for (; isWhitespace(text.charAt(start)); ++start) ; if (isWhitespace(text.charAt(start + intBreak - 1))) { lines.add(text.substring(start, start + intBreak)); start += intBreak; } else { for (offSet = -1; !isWhitespace(text.charAt(start + intBreak + offSet)); ++offSet) ; lines.add(text.substring(start, start + intBreak + offSet)); start += intBreak + offSet; } } catch (Exception e) { if (text.length() > start) lines.add(leftTrim(text.substring(start))); break; } } } else { java.util.StringTokenizer tokens = new java.util.StringTokenizer(text, "|"); if (tokens.hasMoreTokens()) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); for (; tokens.hasMoreTokens(); ) lines.add(leftTrim(tokens.nextToken())); } } Font font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(font_file)); font = font.deriveFont(size); BufferedImage buffer = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = buffer.createGraphics(); if (request.getParameter("aa") != null) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } FontRenderContext fc = g2.getFontRenderContext(); Rectangle2D fontBounds = null; Rectangle2D textLayoutBounds = null; TextLayout tl = null; boolean useTextLayout = false; useTextLayout = Boolean.parseBoolean(request.getParameter("textLayout")); int width = 0; int height = 0; int offSet = 0; if (1 < lines.size()) { int heightMultiplier = 0; int maxWidth = 0; for (; heightMultiplier < lines.size(); ++heightMultiplier) { fontBounds = font.getStringBounds(lines.get(heightMultiplier), fc); tl = new TextLayout(lines.get(heightMultiplier), font, fc); textLayoutBounds = tl.getBounds(); if (maxWidth < Math.ceil(fontBounds.getWidth())) maxWidth = (int) Math.ceil(fontBounds.getWidth()); } width = maxWidth; int boundHeigh = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); height = boundHeigh * lines.size(); offSet = ((int) (boundHeigh * 0.2)) * (lines.size() - 1); } else { fontBounds = font.getStringBounds(text, fc); tl = new TextLayout(text, font, fc); textLayoutBounds = tl.getBounds(); width = (int) fontBounds.getWidth(); height = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); } buffer = new BufferedImage(width, height - offSet, BufferedImage.TYPE_INT_ARGB); g2 = buffer.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setFont(font); g2.setColor(background); if (!background.equals(new Color(Color.TRANSLUCENT))) g2.fillRect(0, 0, width, height); g2.setColor(color); if (1 < lines.size()) { for (int numLine = 0; numLine < lines.size(); ++numLine) { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(lines.get(numLine), 0, -y * (numLine + 1)); } } else { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(text, 0, -y); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); ImageIO.write(buffer, "png", out); out.close(); } catch (Exception ex) { Logger.info(this, ex.toString()); } } response.setContentType("image/png"); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); OutputStream os = response.getOutputStream(); byte[] buf = new byte[4096]; int i = 0; while ((i = bis.read(buf)) != -1) { os.write(buf, 0, i); } os.close(); bis.close(); Logger.debug(this.getClass(), "time to build title: " + (System.currentTimeMillis() - time) + "ms"); return; }
Code Sample 2:
private static void execute(String fileName) throws IOException, SQLException { InputStream input = DatabaseConstants.class.getResourceAsStream(fileName); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer); String sql = writer.toString(); Statement statement = connection.createStatement(); statement.execute(sql); } |
11
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException { if (!src.exists()) throw new IOException("File not found '" + src.getAbsolutePath() + "'"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } |
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:
private void saveFile(Folder folder, Object key, InputStream stream) throws FileManagerException { File file = new File(folder, key.toString()); LOGGER.debug("Writing file: " + file.getAbsolutePath()); Writer writer = null; Writer encodedWriter = null; try { encodedWriter = new OutputStreamWriter(new FileOutputStream(file), getEncodeCharset()); IOUtils.copy(stream, encodedWriter, getDecodeCharset()); LOGGER.info("saveFile(), decode charset: " + getDecodeCharset() + ", encode charset: " + getEncodeCharset()); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } finally { try { encodedWriter.close(); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } } } |
11
| Code Sample 1:
public static String getMD5Hash(String input) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(input.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { String byteStr = Integer.toHexString(result[i]); String swap = null; switch(byteStr.length()) { case 1: swap = "0" + Integer.toHexString(result[i]); break; case 2: swap = Integer.toHexString(result[i]); break; case 8: swap = (Integer.toHexString(result[i])).substring(6, 8); break; } hexString.append(swap); } return hexString.toString(); } catch (Exception ex) { System.out.println("Fehler beim Ermitteln eines Hashs (" + ex.getMessage() + ")"); } return null; }
Code Sample 2:
public void setPassword(String password) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); String encodedPassword = Base64.encode(digest); this.password = encodedPassword; } catch (NoSuchAlgorithmException e) { logger.log(Level.SEVERE, "Password creation failed", e); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "Password creation failed", e); throw new RuntimeException(e); } } |
11
| Code Sample 1:
public String hash(String senha) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(senha.getBytes()); byte[] hashMd5 = md.digest(); for (int i = 0; i < hashMd5.length; i++) result += Integer.toHexString((((hashMd5[i] >> 4) & 0xf) << 4) | (hashMd5[i] & 0xf)); } catch (NoSuchAlgorithmException ex) { Logger.getInstancia().log(TipoLog.ERRO, ex); } return result; }
Code Sample 2:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config = getServletConfig(); ServletContext context = config.getServletContext(); try { String driver = context.getInitParameter("driver"); Class.forName(driver); String dbURL = context.getInitParameter("db"); String username = context.getInitParameter("username"); String password = ""; connection = DriverManager.getConnection(dbURL, username, password); } catch (ClassNotFoundException e) { System.out.println("Database driver not found."); } catch (SQLException e) { System.out.println("Error opening the db connection: " + e.getMessage()); } String action = ""; String notice; String error = ""; HttpSession session = request.getSession(); session.setMaxInactiveInterval(300); if (request.getParameter("action") != null) { action = request.getParameter("action"); } else { notice = "Unknown action!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } if (action.equals("edit_events")) { String sql; String month_name = ""; int month; int year; Event event; if (request.getParameter("month") != null) { month = Integer.parseInt(request.getParameter("month")); String temp = request.getParameter("year_num"); year = Integer.parseInt(temp); int month_num = month - 1; event = new Event(year, month_num, 1); month_name = event.getMonthName(); year = event.getYearNumber(); if (month < 10) { sql = "SELECT * FROM event WHERE date LIKE '" + year + "-0" + month + "-%'"; } else { sql = "SELECT * FROM event WHERE date LIKE '" + year + "-" + month + "-%'"; } } else { event = new Event(); month_name = event.getMonthName(); month = event.getMonthNumber() + 1; year = event.getYearNumber(); sql = "SELECT * FROM event WHERE date LIKE '" + year + "-%" + month + "-%'"; } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); request.setAttribute("year", Integer.toString(year)); request.setAttribute("month", Integer.toString(month)); request.setAttribute("month_name", month_name); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_events.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving events from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_event")) { int id = Integer.parseInt(request.getParameter("id")); Event event = new Event(); event = event.getEvent(id); if (event != null) { request.setAttribute("event", event); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving event from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("save_event")) { String title = request.getParameter("title"); String description = request.getParameter("description"); String month = request.getParameter("month"); String day = request.getParameter("day"); String year = request.getParameter("year"); String start_time = ""; String end_time = ""; if (request.getParameter("all_day") == null) { String start_hour = request.getParameter("start_hour"); String start_minutes = request.getParameter("start_minutes"); String start_ampm = request.getParameter("start_ampm"); String end_hour = request.getParameter("end_hour"); String end_minutes = request.getParameter("end_minutes"); String end_ampm = request.getParameter("end_ampm"); if (Integer.parseInt(start_hour) < 10) { start_hour = "0" + start_hour; } if (Integer.parseInt(end_hour) < 10) { end_hour = "0" + end_hour; } start_time = start_hour + ":" + start_minutes + " " + start_ampm; end_time = end_hour + ":" + end_minutes + " " + end_ampm; } Event event = null; if (!start_time.equals("") && !end_time.equals("")) { event = new Event(title, description, month, day, year, start_time, end_time); } else { event = new Event(title, description, month, day, year); } if (event.saveEvent()) { notice = "Calendar event saved!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error saving calendar event."; request.setAttribute("notice", notice); request.setAttribute("event", event); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_event")) { String title = request.getParameter("title"); String description = request.getParameter("description"); String month = request.getParameter("month"); String day = request.getParameter("day"); String year = request.getParameter("year"); String start_time = ""; String end_time = ""; int id = Integer.parseInt(request.getParameter("id")); if (request.getParameter("all_day") == null) { String start_hour = request.getParameter("start_hour"); String start_minutes = request.getParameter("start_minutes"); String start_ampm = request.getParameter("start_ampm"); String end_hour = request.getParameter("end_hour"); String end_minutes = request.getParameter("end_minutes"); String end_ampm = request.getParameter("end_ampm"); if (Integer.parseInt(start_hour) < 10) { start_hour = "0" + start_hour; } if (Integer.parseInt(end_hour) < 10) { end_hour = "0" + end_hour; } start_time = start_hour + ":" + start_minutes + " " + start_ampm; end_time = end_hour + ":" + end_minutes + " " + end_ampm; } Event event = null; if (!start_time.equals("") && !end_time.equals("")) { event = new Event(title, description, month, day, year, start_time, end_time); } else { event = new Event(title, description, month, day, year); } if (event.updateEvent(id)) { notice = "Calendar event updated!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error updating calendar event."; request.setAttribute("notice", notice); request.setAttribute("event", event); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete_event")) { int id = Integer.parseInt(request.getParameter("id")); Event event = new Event(); if (event.deleteEvent(id)) { notice = "Calendar event successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_events"); dispatcher.forward(request, response); return; } else { notice = "Error deleting event from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_events"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_members")) { String sql = "SELECT * FROM person ORDER BY lname"; if (request.getParameter("member_type") != null) { String member_type = request.getParameter("member_type"); if (member_type.equals("all")) { sql = "SELECT * FROM person ORDER BY lname"; } else { sql = "SELECT * FROM person where member_type LIKE '" + member_type + "' ORDER BY lname"; } request.setAttribute("member_type", member_type); } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_members.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving members from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_person")) { int id = Integer.parseInt(request.getParameter("id")); String member_type = request.getParameter("member_type"); Person person = new Person(); person = person.getPerson(id); if (member_type.equals("student")) { Student student = person.getStudent(); request.setAttribute("student", student); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_student.jsp"); dispatcher.forward(request, response); return; } else if (member_type.equals("alumni")) { Alumni alumni = person.getAlumni(); request.setAttribute("alumni", alumni); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_alumni.jsp"); dispatcher.forward(request, response); return; } else if (member_type.equals("hospital")) { Hospital hospital = person.getHospital(id); request.setAttribute("hospital", hospital); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_hospital.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_alumni")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Alumni cur_alumni = person.getAlumni(); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String company_name = request.getParameter("company_name"); String position = request.getParameter("position"); int mentor = 0; if (request.getParameter("mentor") != null) { mentor = 1; } String graduation_date = request.getParameter("graduation_year") + "-" + request.getParameter("graduation_month") + "-01"; String password = ""; if (request.getParameter("password") != null) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_alumni.getPassword(); } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Alumni new_alumni = new Alumni(fname, lname, address1, address2, city, state, zip, email, password, is_admin, company_name, position, graduation_date, mentor); if (!new_alumni.getEmail().equals(cur_alumni.getEmail())) { if (new_alumni.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("alumni", new_alumni); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_alumni.updateAlumni(person_id)) { session.setAttribute("alumni", new_alumni); notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Member information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("update_hospital")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Hospital cur_hospital = person.getHospital(person_id); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String name = request.getParameter("name"); String phone = request.getParameter("phone"); String url = request.getParameter("url"); String password = ""; if (cur_hospital.getPassword() != null) { if (request.getParameter("password") != null && !request.getParameter("password").equals("")) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_hospital.getPassword(); } } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Hospital new_hospital = new Hospital(fname, lname, address1, address2, city, state, zip, email, password, is_admin, name, phone, url); if (!new_hospital.getEmail().equals(cur_hospital.getEmail())) { if (new_hospital.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("hospital", new_hospital); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_hospital.updateHospital(person_id)) { session.setAttribute("hospital", new_hospital); notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("update_student")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Student cur_student = person.getStudent(); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String start_date = request.getParameter("start_year") + "-" + request.getParameter("start_month") + "-01"; String graduation_date = ""; if (!request.getParameter("grad_year").equals("") && !request.getParameter("grad_month").equals("")) { graduation_date = request.getParameter("grad_year") + "-" + request.getParameter("grad_month") + "-01"; } String password = ""; if (request.getParameter("password") != null && !request.getParameter("password").equals("")) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_student.getPassword(); } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Student new_student = new Student(fname, lname, address1, address2, city, state, zip, email, password, is_admin, start_date, graduation_date); if (!new_student.getEmail().equals(cur_student.getEmail())) { if (new_student.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("student", new_student); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_student.updateStudent(person_id)) { notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("delete_person")) { int id = Integer.parseInt(request.getParameter("id")); String member_type = request.getParameter("member_type"); Person person = new Person(); person = person.getPerson(id); if (person.deletePerson(member_type)) { notice = person.getFname() + ' ' + person.getLname() + " successfully deleted from database."; request.setAttribute("notice", notice); person = null; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members&member_type=all"); dispatcher.forward(request, response); return; } } else if (action.equals("manage_pages")) { String sql = "SELECT * FROM pages WHERE parent_id=0 OR parent_id IN (SELECT id FROM pages WHERE title LIKE 'root')"; if (request.getParameter("id") != null) { int id = Integer.parseInt(request.getParameter("id")); sql = "SELECT * FROM pages WHERE parent_id=" + id; } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_pages.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("add_page")) { String sql = "SELECT id, title FROM pages WHERE parent_id=0 OR parent_id IN (SELECT id FROM pages WHERE title LIKE 'root')"; try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("save_page")) { String title = request.getParameter("title"); String content = request.getParameter("content"); Page page = null; if (request.getParameter("parent_id") != null) { int parent_id = Integer.parseInt(request.getParameter("parent_id")); page = new Page(title, content, parent_id); } else { page = new Page(title, content, 0); } if (page.savePage()) { notice = "Content page saved!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "There was an error saving the page."; request.setAttribute("page", page); request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_page")) { String sql = "SELECT * FROM pages WHERE parent_id=0"; int id = Integer.parseInt(request.getParameter("id")); Page page = new Page(); page = page.getPage(id); try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } if (page != null) { request.setAttribute("page", page); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving content page from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_page")) { int id = Integer.parseInt(request.getParameter("id")); String title = request.getParameter("title"); String content = request.getParameter("content"); int parent_id = 0; if (request.getParameter("parent_id") != null) { parent_id = Integer.parseInt(request.getParameter("parent_id")); } Page page = new Page(title, content, parent_id); if (page.updatePage(id)) { notice = "Content page was updated successfully."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error updating the content page."; request.setAttribute("notice", notice); request.setAttribute("page", page); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete_page")) { int id = Integer.parseInt(request.getParameter("id")); Page page = new Page(); if (page.deletePage(id)) { notice = "Content page (and sub pages) deleted successfully."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the content page(s)."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("list_residencies")) { Residency residency = new Residency(); dbResultSet = residency.getResidencies(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list_residencies.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("delete_residency")) { int job_id = Integer.parseInt(request.getParameter("id")); Residency residency = new Residency(); if (residency.deleteResidency(job_id)) { notice = "Residency has been successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_residency")) { int job_id = Integer.parseInt(request.getParameter("id")); Residency residency = new Residency(); dbResultSet = residency.getResidency(job_id); if (dbResultSet != null) { try { int hId = dbResultSet.getInt("hospital_id"); String hName = residency.getHospitalName(hId); request.setAttribute("hName", hName); dbResultSet.beforeFirst(); } catch (SQLException e) { error = "There was an error retreiving the residency."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_residency.jsp"); dispatcher.forward(request, response); return; } else { notice = "There was an error in locating the residency you selected."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("new_residency")) { Residency residency = new Residency(); dbResultSet = residency.getHospitals(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_residency.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("add_residency")) { Person person = (Person) session.getAttribute("person"); if (person.isAdmin()) { String hName = request.getParameter("hName"); String title = request.getParameter("title"); String description = request.getParameter("description"); String start_month = request.getParameter("startDateMonth"); String start_day = request.getParameter("startDateDay"); String start_year = request.getParameter("startDateYear"); String start_date = start_year + start_month + start_day; String end_month = request.getParameter("endDateMonth"); String end_day = request.getParameter("endDateDay"); String end_year = request.getParameter("endDateYear"); String end_date = end_year + end_month + end_day; String deadline_month = request.getParameter("deadlineDateMonth"); String deadline_day = request.getParameter("deadlineDateDay"); String deadline_year = request.getParameter("deadlineDateYear"); String deadline_date = deadline_year + deadline_month + deadline_day; int hId = Integer.parseInt(request.getParameter("hId")); Residency residency = new Residency(title, start_date, end_date, deadline_date, description, hId); if (residency.saveResidency()) { notice = "Residency has been successfully saved."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error saving the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("update_residency")) { Person person = (Person) session.getAttribute("person"); int job_id = Integer.parseInt(request.getParameter("job_id")); if (person.isAdmin()) { String hName = request.getParameter("hName"); String title = request.getParameter("title"); String description = request.getParameter("description"); String start_month = request.getParameter("startDateMonth"); String start_day = request.getParameter("startDateDay"); String start_year = request.getParameter("startDateYear"); String start_date = start_year + start_month + start_day; String end_month = request.getParameter("endDateMonth"); String end_day = request.getParameter("endDateDay"); String end_year = request.getParameter("endDateYear"); String end_date = end_year + end_month + end_day; String deadline_month = request.getParameter("deadlineDateMonth"); String deadline_day = request.getParameter("deadlineDateDay"); String deadline_year = request.getParameter("deadlineDateYear"); String deadline_date = deadline_year + deadline_month + deadline_day; int hId = Integer.parseInt(request.getParameter("hId")); Residency residency = new Residency(job_id, title, start_date, end_date, deadline_date, description); if (residency.updateResidency(job_id)) { notice = "Residency has been successfully saved."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error saving the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("add_hospital")) { Person person = (Person) session.getAttribute("person"); if (person.isAdmin()) { String name = request.getParameter("name"); String url = request.getParameter("url"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String phone = request.getParameter("phone"); String lname = request.getParameter("name"); Hospital hospital = new Hospital(lname, address1, address2, city, state, zip, name, phone, url); if (!hospital.saveHospitalAdmin()) { notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=new_residency"); dispatcher.forward(request, response); return; } else { notice = "Unknown request. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Get Admin News List")) { News news = new News(); if (news.getNewsList() != null) { dbResultSet = news.getNewsList(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news list."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Get News List")) { News news = new News(); if (news.getNewsList() != null) { dbResultSet = news.getNewsList(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_list.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news list."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/gsu_fhce/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("detail")) { String id = request.getParameter("id"); News news = new News(); if (news.getNewsDetail(id) != null) { dbResultSet = news.getNewsDetail(id); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_detail.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news detail."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete")) { int id = 0; id = Integer.parseInt(request.getParameter("id")); News news = new News(); if (news.deleteNews(id)) { notice = "News successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } } else if (action.equals("edit")) { int id = Integer.parseInt(request.getParameter("id")); News news = new News(); news = news.getNews(id); if (news != null) { request.setAttribute("news", news); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_update.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving news from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Update News")) { String title = request.getParameter("title"); String date = (request.getParameter("year")) + (request.getParameter("month")) + (request.getParameter("day")); String content = request.getParameter("content"); int id = Integer.parseInt(request.getParameter("newsid")); News news = new News(title, date, content); if (news.updateNews(id)) { notice = "News successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Could not update news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } } else if (action.equals("Add News")) { String id = ""; String title = request.getParameter("title"); String date = request.getParameter("year") + "-" + request.getParameter("month") + "-" + request.getParameter("day"); String content = request.getParameter("content"); News news = new News(title, date, content); if (news.addNews()) { notice = "News successfully added."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Could not add news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("manage_mship")) { Mentor mentor = new Mentor(); dbResultSet = mentor.getMentorships(); if (dbResultSet != null) { request.setAttribute("result", dbResultSet); } else { notice = "There are no current mentorships."; request.setAttribute("notice", notice); } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list_mentorships.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("delete_mship")) { int mentorship_id = Integer.parseInt(request.getParameter("id")); Mentor mentor = new Mentor(); if (mentor.delMentorship(mentorship_id)) { notice = "Mentorship successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the mentorship."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } } else if (action.equals("new_mship")) { Mentor mentor = new Mentor(); ResultSet alumnis = null; ResultSet students = null; alumnis = mentor.getAlumnis(); students = mentor.getStudents(); request.setAttribute("alumni_result", alumnis); request.setAttribute("student_result", students); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/create_mship.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("create_mship")) { int student_id = Integer.parseInt(request.getParameter("student_id")); int alumni_id = Integer.parseInt(request.getParameter("alumni_id")); Mentor mentor = new Mentor(); if (mentor.addMentorship(student_id, alumni_id)) { notice = "Mentorship successfully created."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } else { notice = "There was an error creating the mentorship."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/create_mship.jsp"); dispatcher.forward(request, response); return; } } } |
00
| Code Sample 1:
public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); }
Code Sample 2:
@Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; } |
00
| Code Sample 1:
private static InputSource getInputSourceFromURI(String uri, String username, String password) throws IOException, ProtocolException, UnsupportedEncodingException { URL wsdlurl = null; try { wsdlurl = new URL(uri); } catch (MalformedURLException e) { return new InputSource(uri); } if (username == null && wsdlurl.getUserInfo() == null) { return new InputSource(uri); } if (!wsdlurl.getProtocol().startsWith("http")) { return new InputSource(uri); } URLConnection connection = wsdlurl.openConnection(); if (!(connection instanceof HttpURLConnection)) { return new InputSource(uri); } HttpURLConnection uconn = (HttpURLConnection) connection; String userinfo = wsdlurl.getUserInfo(); uconn.setRequestMethod("GET"); uconn.setAllowUserInteraction(false); uconn.setDefaultUseCaches(false); uconn.setDoInput(true); uconn.setDoOutput(false); uconn.setInstanceFollowRedirects(true); uconn.setUseCaches(false); String auth = null; if (userinfo != null) { auth = userinfo; } else if (username != null) { auth = (password == null) ? username : username + ":" + password; } if (auth != null) { uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(httpAuthCharEncoding))); } uconn.connect(); return new InputSource(uconn.getInputStream()); }
Code Sample 2:
public void testPreparedStatementRollback1() throws Exception { Connection localCon = getConnection(); Statement stmt = localCon.createStatement(); stmt.execute("CREATE TABLE #psr1 (data BIT)"); localCon.setAutoCommit(false); PreparedStatement pstmt = localCon.prepareStatement("INSERT INTO #psr1 (data) VALUES (?)"); pstmt.setBoolean(1, true); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); localCon.rollback(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psr1"); assertFalse(rs.next()); rs.close(); stmt.close(); localCon.close(); try { localCon.commit(); fail("Expecting commit to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } try { localCon.rollback(); fail("Expecting rollback to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } } |
11
| Code Sample 1:
static final String md5(String text) throws RtmApiException { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RtmApiException("Md5 error: NoSuchAlgorithmException - " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RtmApiException("Md5 error: UnsupportedEncodingException - " + e.getMessage()); } }
Code Sample 2:
public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.substring(8, 24).toString().toUpperCase(); } |
00
| Code Sample 1:
private boolean connect() { try { this.ftpClient.connect(this.server, this.port); this.ftpClient.login(this.username, this.password); return true; } catch (IOException iOException) { return false; } }
Code Sample 2:
private void writeInputStreamToFile(InputStream stream, File file) { try { FileOutputStream fOut = new FileOutputStream(file); IOUtils.copy(stream, fOut); fOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); }
Code Sample 2:
@Override public void run() { HttpGet httpGet = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); DataModel model = DataModel.getInstance(); for (City city : citiesToBeUpdated) { String preferredUnitType = PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(R.string.settings_units_key), context.getString(R.string.settings_units_default_value)); String codePrefix = city.getCountryName().startsWith("United States") ? GET_PARAM_ZIP_PREFIX : GET_PARAM_CITY_CODE_PREFIX; String requestUri = new String(GET_URL + "?" + GET_PARAM_ACODE_PREFIX + "=" + GET_PARAM_ACODE + "&" + codePrefix + "=" + city.getId() + "&" + GET_PARAM_UNIT_PREFIX + "=" + preferredUnitType); httpGet = new HttpGet(requestUri); HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { processXML(response.getEntity().getContent()); for (ForecastedDay day : forecast) { int pos = day.getImageURL().lastIndexOf('/'); if (pos < 0 || pos + 1 == day.getImageURL().length()) throw new Exception("Invalid image URL"); final String imageFilename = day.getImageURL().substring(pos + 1); File downloadDir = context.getDir(ForecastedDay.DOWNLOAD_DIR, Context.MODE_PRIVATE); File[] imagesFilteredByName = downloadDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { if (filename.equals(imageFilename)) return true; else return false; } }); if (imagesFilteredByName.length == 0) { httpGet = new HttpGet(day.getImageURL()); response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedOutputStream bus = null; try { bus = new BufferedOutputStream(new FileOutputStream(downloadDir.getAbsolutePath() + "/" + imageFilename)); response.getEntity().writeTo(bus); } finally { bus.close(); } } } } city.setDays(forecast); city.setLastUpdated(Calendar.getInstance().getTime()); model.saveCity(city); } } } catch (Exception e) { httpGet.abort(); e.printStackTrace(); } finally { handler.sendEmptyMessage(1); } } |
00
| Code Sample 1:
public static void replaceEntry(File file, String entryName, InputStream stream) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ".zargo"); temporaryFile.deleteOnExit(); FileInputStream inputStream = new FileInputStream(file); ZipInputStream input = new ZipInputStream(inputStream); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); ZipEntry entry = input.getNextEntry(); while (entry != null) { ZipEntry zipEntry = new ZipEntry(entry); zipEntry.setCompressedSize(-1); output.putNextEntry(zipEntry); if (!entry.getName().equals(entryName)) { IOUtils.copy(input, output); } else { IOUtils.copy(stream, output); } input.closeEntry(); output.closeEntry(); entry = input.getNextEntry(); } input.close(); inputStream.close(); output.close(); System.gc(); boolean isSuccess = file.delete(); if (!isSuccess) { throw new PersistenceException(); } isSuccess = temporaryFile.renameTo(file); if (!isSuccess) { throw new PersistenceException(); } } catch (IOException e) { throw new PersistenceException(e); } }
Code Sample 2:
public void getDataFiles(String server, String username, String password, String folder, String destinationFolder) { try { FTPClient ftp = new FTPClient(); ftp.connect(server); ftp.login(username, password); System.out.println("Connected to " + server + "."); System.out.print(ftp.getReplyString()); ftp.enterLocalActiveMode(); ftp.changeWorkingDirectory(folder); System.out.println("Changed to " + folder); FTPFile[] files = ftp.listFiles(); System.out.println("Number of files in dir: " + files.length); for (int i = 0; i < files.length; i++) { getFiles(ftp, files[i], destinationFolder); } ftp.logout(); ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } } |
11
| Code Sample 1:
public static String MD5(String text) { byte[] md5hash = new byte[32]; try { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (Exception e) { e.printStackTrace(); } return convertToHex(md5hash); }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } |
11
| Code Sample 1:
private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); }
Code Sample 2:
public static void copyFile(File source, File dest) throws Exception { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { throw new Exception("Cannot copy file " + source.getAbsolutePath() + " to " + dest.getAbsolutePath(), e); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e) { throw new Exception("Cannot close streams.", e); } } } |
00
| Code Sample 1:
public Dbf(URL url) throws java.io.IOException, DbfFileException { if (DEBUG) System.out.println("---->uk.ac.leeds.ccg.dbffile.Dbf constructed. Will identify itself as " + DBC); URLConnection uc = url.openConnection(); InputStream in = uc.getInputStream(); EndianDataInputStream sfile = new EndianDataInputStream(in); init(sfile); }
Code Sample 2:
@Override public String getMD5(String host) { String res = ""; Double randNumber = Math.random() + System.currentTimeMillis(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(randNumber.toString().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 (Exception ex) { } return res; } |
00
| Code Sample 1:
public ProgramMessageSymbol addProgramMessageSymbol(int programID, String name, byte[] bytecode) throws AdaptationException { ProgramMessageSymbol programMessageSymbol = null; Connection connection = null; PreparedStatement preparedStatement = null; Statement statement = null; ResultSet resultSet = null; InputStream stream = new ByteArrayInputStream(bytecode); try { String query = "INSERT INTO ProgramMessageSymbols(programID, name, " + "bytecode) VALUES ( ?, ?, ? )"; connection = DriverManager.getConnection(CONN_STR); preparedStatement = connection.prepareStatement(query); preparedStatement.setInt(1, programID); preparedStatement.setString(2, name); preparedStatement.setBinaryStream(3, stream, bytecode.length); log.info("INSERT INTO ProgramMessageSymbols(programID, name, " + "bytecode) VALUES (" + programID + ", '" + name + "', " + "<bytecode>)"); preparedStatement.executeUpdate(); statement = connection.createStatement(); query = "SELECT * FROM ProgramMessageSymbols WHERE " + "programID = " + programID + " AND " + "name = '" + name + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to add program message symbol failed."; log.error(msg); ; throw new AdaptationException(msg); } programMessageSymbol = getProgramMessageSymbol(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in addProgramMessageSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { preparedStatement.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programMessageSymbol; }
Code Sample 2:
public void Copy() throws IOException { if (!FileDestination.exists()) { FileDestination.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(FileSource).getChannel(); destination = new FileOutputStream(FileDestination).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } |
00
| Code Sample 1:
private void makeConn(String filename1, String filename2) { String basename = "http://www.bestmm.com/"; String urlname = basename + filename1 + "/pic/" + filename2 + ".jpg"; URL url = null; try { url = new URL(urlname); } catch (MalformedURLException e) { System.err.println("URL Format Error!"); System.exit(1); } try { conn = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.err.println("Error IO"); System.exit(2); } }
Code Sample 2:
public void initGet() throws Exception { cl = new FTPClient(); cl.connect(getHostName()); Authentication auth = AuthManager.getAuth(getSite()); if (auth == null) auth = new FTPAuthentication(getSite()); while (!cl.login(auth.getUser(), auth.getPassword())) { ap.setSite(getSite()); auth = ap.promptAuthentication(); if (auth == null) throw new Exception("User Cancelled Auth Operation"); } cl.connect(getHostName()); cl.login(auth.getUser(), auth.getPassword()); cl.enterLocalPassiveMode(); cl.setFileType(FTP.BINARY_FILE_TYPE); cl.setRestartOffset(getPosition()); setInputStream(cl.retrieveFileStream(new URL(getURL()).getFile())); } |
11
| Code Sample 1:
public String hash(String text) { try { MessageDigest md = MessageDigest.getInstance(hashFunction); md.update(text.getBytes(charset)); byte[] raw = md.digest(); return new String(encodeHex(raw)); } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
protected static String hashPassword(String password, String salt) throws NoSuchAlgorithmException { String s = salt + password; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes()); byte bs[] = md.digest(); String s1 = BASE64Encoder.encode(bs); return new StringBuffer(salt).append(':').append(s1).toString(); } |
Subsets and Splits