label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
public void writeValue(Value v) throws IOException, SQLException { int type = v.getType(); writeInt(type); switch(type) { case Value.NULL: break; case Value.BYTES: case Value.JAVA_OBJECT: writeBytes(v.getBytesNoCopy()); break; case Value.UUID: { ValueUuid uuid = (ValueUuid) v; writeLong(uuid.getHigh()); writeLong(uuid.getLow()); break; } case Value.BOOLEAN: writeBoolean(v.getBoolean().booleanValue()); break; case Value.BYTE: writeByte(v.getByte()); break; case Value.TIME: writeLong(v.getTimeNoCopy().getTime()); break; case Value.DATE: writeLong(v.getDateNoCopy().getTime()); break; case Value.TIMESTAMP: { Timestamp ts = v.getTimestampNoCopy(); writeLong(ts.getTime()); writeInt(ts.getNanos()); break; } case Value.DECIMAL: writeString(v.getString()); break; case Value.DOUBLE: writeDouble(v.getDouble()); break; case Value.FLOAT: writeFloat(v.getFloat()); break; case Value.INT: writeInt(v.getInt()); break; case Value.LONG: writeLong(v.getLong()); break; case Value.SHORT: writeInt(v.getShort()); break; case Value.STRING: case Value.STRING_IGNORECASE: case Value.STRING_FIXED: writeString(v.getString()); break; case Value.BLOB: { long length = v.getPrecision(); if (SysProperties.CHECK && length < 0) { Message.throwInternalError("length: " + length); } writeLong(length); InputStream in = v.getInputStream(); long written = IOUtils.copyAndCloseInput(in, out); if (SysProperties.CHECK && written != length) { Message.throwInternalError("length:" + length + " written:" + written); } writeInt(LOB_MAGIC); break; } case Value.CLOB: { long length = v.getPrecision(); if (SysProperties.CHECK && length < 0) { Message.throwInternalError("length: " + length); } writeLong(length); Reader reader = v.getReader(); java.io.OutputStream out2 = new java.io.FilterOutputStream(out) { public void flush() { } }; Writer writer = new BufferedWriter(new OutputStreamWriter(out2, Constants.UTF8)); long written = IOUtils.copyAndCloseInput(reader, writer); if (SysProperties.CHECK && written != length) { Message.throwInternalError("length:" + length + " written:" + written); } writer.flush(); writeInt(LOB_MAGIC); break; } case Value.ARRAY: { Value[] list = ((ValueArray) v).getList(); writeInt(list.length); for (Value value : list) { writeValue(value); } break; } case Value.RESULT_SET: { ResultSet rs = ((ValueResultSet) v).getResultSet(); rs.beforeFirst(); ResultSetMetaData meta = rs.getMetaData(); int columnCount = meta.getColumnCount(); writeInt(columnCount); for (int i = 0; i < columnCount; i++) { writeString(meta.getColumnName(i + 1)); writeInt(meta.getColumnType(i + 1)); writeInt(meta.getPrecision(i + 1)); writeInt(meta.getScale(i + 1)); } while (rs.next()) { writeBoolean(true); for (int i = 0; i < columnCount; i++) { int t = DataType.convertSQLTypeToValueType(meta.getColumnType(i + 1)); Value val = DataType.readValue(session, rs, i + 1, t); writeValue(val); } } writeBoolean(false); rs.beforeFirst(); break; } default: Message.throwInternalError("type=" + type); } }
Code Sample 2:
private void removeSessionId(InputStream inputStream, Output output) throws IOException { String jsessionid = RewriteUtils.getSessionId(target); boolean textContentType = ResourceUtils.isTextContentType(httpClientResponse.getHeader(HttpHeaders.CONTENT_TYPE), target.getDriver().getConfiguration().getParsableContentTypes()); if (jsessionid == null || !textContentType) { IOUtils.copy(inputStream, output.getOutputStream()); } else { String charset = httpClientResponse.getContentCharset(); if (charset == null) { charset = "ISO-8859-1"; } String content = IOUtils.toString(inputStream, charset); content = removeSessionId(jsessionid, content); if (output.getHeader(HttpHeaders.CONTENT_LENGTH) != null) { output.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(content.length())); } OutputStream outputStream = output.getOutputStream(); IOUtils.write(content, outputStream, charset); } inputStream.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:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/zip"); response.setHeader("Content-Disposition", "inline; filename=c:/server1.zip"); try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("server.zip"); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; java.util.Properties props = new java.util.Properties(); props.load(new java.io.FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + "/SystemFiles/ENV_VAR.txt")); String jbossHomePath = props.getProperty("JBOSS_HOME"); jbossHomePath = jbossHomePath.replaceAll("deploy", "log"); FileInputStream fis = new FileInputStream(new File(jbossHomePath + "/server.log")); origin = new BufferedInputStream(fis, BUFFER); ZipEntry entry = new ZipEntry(jbossHomePath + "/server.log"); zipOut.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } origin.close(); zipOut.closeEntry(); java.io.FileInputStream fis1 = new java.io.FileInputStream(new java.io.File("server.zip")); java.nio.channels.FileChannel fc1 = fis1.getChannel(); int length1 = (int) fc1.size(); byte buffer[] = new byte[length1]; System.out.println("size of zip file = " + length1); fis1.read(buffer); OutputStream out1 = response.getOutputStream(); out1.write(buffer); fis1.close(); out1.close(); } catch (Exception e) { e.printStackTrace(); } }
|
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:
public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); }
|
00
|
Code Sample 1:
@Test public void test_lookupType_TooShortName() throws Exception { URL url = new URL(baseUrl + "/lookupType/A"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); }
Code Sample 2:
public SCFFile(URL url) throws IOException { URLConnection connection = url.openConnection(); byte[] content = new byte[connection.getContentLength()]; DataInputStream dis = new DataInputStream(connection.getInputStream()); dis.readFully(content); dis.close(); dis = new DataInputStream(new ByteArrayInputStream(content)); header = new SCFHeader(dis); if (!header.magicNumber.equals(".scf")) throw new RuntimeException(url + " is not an SCF file"); A = new int[header.samples]; C = new int[header.samples]; G = new int[header.samples]; T = new int[header.samples]; max = Integer.MIN_VALUE; dis.reset(); dis.skipBytes(header.samplesOffset); if (header.sampleSize == 1) { if (header.version < 3.00) { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedByte(); if (A[i] > max) max = A[i]; C[i] = dis.readUnsignedByte(); if (C[i] > max) max = C[i]; G[i] = dis.readUnsignedByte(); if (G[i] > max) max = G[i]; T[i] = dis.readUnsignedByte(); if (T[i] > max) max = T[i]; } } else { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedByte(); if (A[i] > max) max = A[i]; } for (int i = 0; i < header.samples; ++i) { C[i] = dis.readUnsignedByte(); if (C[i] > max) max = C[i]; } for (int i = 0; i < header.samples; ++i) { G[i] = dis.readUnsignedByte(); if (G[i] > max) max = G[i]; } for (int i = 0; i < header.samples; ++i) { T[i] = dis.readUnsignedByte(); if (T[i] > max) max = T[i]; } } } else if (header.sampleSize == 2) { if (header.version < 3.00) { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedShort(); if (A[i] > max) max = A[i]; C[i] = dis.readUnsignedShort(); if (C[i] > max) max = C[i]; G[i] = dis.readUnsignedShort(); if (G[i] > max) max = G[i]; T[i] = dis.readUnsignedShort(); if (T[i] > max) max = T[i]; } } else { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedShort(); if (A[i] > max) max = A[i]; } for (int i = 0; i < header.samples; ++i) { C[i] = dis.readUnsignedShort(); if (C[i] > max) max = C[i]; } for (int i = 0; i < header.samples; ++i) { G[i] = dis.readUnsignedShort(); if (G[i] > max) max = G[i]; } for (int i = 0; i < header.samples; ++i) { T[i] = dis.readUnsignedShort(); if (T[i] > max) max = T[i]; } } } centers = new int[header.bases]; byte[] buf = new byte[header.bases]; dis.reset(); dis.skipBytes(header.basesOffset); if (header.version < 3.00) { for (int i = 0; i < header.bases; ++i) { centers[i] = dis.readInt(); dis.skipBytes(4); buf[i] = dis.readByte(); dis.skipBytes(3); } } else { for (int i = 0; i < header.bases; ++i) centers[i] = dis.readInt(); dis.skipBytes(4 * header.bases); dis.readFully(buf); } sequence = new String(buf); dis.close(); }
|
11
|
Code Sample 1:
@SuppressWarnings("static-access") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { filename = URLDecoder.decode(filename, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { is = request.getInputStream(); File newFile = new File(realPath + filename); if (!newFile.exists()) { fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true,detailMsg}"); } else { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false,detailMsg:'文件已经存在!请重命名后上传!'}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + filename + " has existed!"); } } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
Code Sample 2:
public File createFileFromClasspathResource(String resourceUrl) throws IOException { File fichierTest = File.createTempFile("xmlFieldTestFile", ""); FileOutputStream fos = new FileOutputStream(fichierTest); InputStream is = XmlFieldDomSelectorTest.class.getResourceAsStream(resourceUrl); IOUtils.copy(is, fos); is.close(); fos.close(); return fichierTest; }
|
00
|
Code Sample 1:
@Override public void copyFile2File(final File src, final File dest, final boolean force) throws C4JException { if (dest.exists()) if (force && !dest.delete()) throw new C4JException(format("Copying ‘%s’ to ‘%s’ failed; cannot overwrite existing file.", src.getPath(), dest.getPath())); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dest).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (src.canExecute()) dest.setExecutable(true, false); } catch (final IOException e) { throw new C4JException(format("Could not copy ‘%s’ to ‘%s’.", src.getPath(), dest.getPath()), e); } finally { if (inChannel != null) try { try { inChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close input stream for ‘%s’.", src.getPath()), e); } } finally { if (outChannel != null) try { outChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close output stream for ‘%s’.", dest.getPath()), e); } } } }
Code Sample 2:
public synchronized String decrypt(String plaintext) throws Exception { MessageDigest md = null; String strhash = new String((new BASE64Decoder()).decodeBuffer(plaintext)); System.out.println("strhash1122 " + strhash); try { md = MessageDigest.getInstance("MD5"); } catch (Exception e) { e.printStackTrace(); } byte raw[] = md.digest(); try { md.update(new String(raw).getBytes("UTF-8")); } catch (Exception e) { e.printStackTrace(); } System.out.println("plain text " + strhash); String strcode = new String(raw); System.out.println("strcode.." + strcode); return strcode; }
|
11
|
Code Sample 1:
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); }
Code Sample 2:
public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text.getBytes(ENCODING)); } catch (NoSuchAlgorithmException nsae) { Logger.error(Encryptor.class, nsae.getMessage(), nsae); } catch (UnsupportedEncodingException uee) { Logger.error(Encryptor.class, uee.getMessage(), uee); } byte raw[] = mDigest.digest(); return (new BASE64Encoder()).encode(raw); }
|
00
|
Code Sample 1:
void updateSource(Class<?> type) throws Exception { final String path = type.getName().replaceAll("\\.", "/") + ".java"; new Thread(new Runnable() { @Override public void run() { try { URL url = Thread.currentThread().getContextClassLoader().getResource(path); InputStream fis = url.openStream(); InputStreamReader r = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(r); String line; StringBuilder sb = new StringBuilder(); while (null != (line = br.readLine())) { sb.append(line); sb.append("\r\n"); } br.close(); r.close(); fis.close(); final String text = sb.toString(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MainPanel.this.source.setText(text); MainPanel.this.source.setCaretPosition(0); } }); } catch (Exception ex) { } } }).start(); }
Code Sample 2:
public DataRecord addRecord(InputStream input) throws DataStoreException { File temporary = null; try { temporary = newTemporaryFile(); DataIdentifier tempId = new DataIdentifier(temporary.getName()); usesIdentifier(tempId); long length = 0; MessageDigest digest = MessageDigest.getInstance(DIGEST); OutputStream output = new DigestOutputStream(new FileOutputStream(temporary), digest); try { length = IOUtils.copyLarge(input, output); } finally { output.close(); } DataIdentifier identifier = new DataIdentifier(digest.digest()); File file; synchronized (this) { usesIdentifier(identifier); file = getFile(identifier); System.out.println("new file name: " + file.getName()); File parent = file.getParentFile(); System.out.println("parent file: " + file.getParentFile().getName()); if (!parent.isDirectory()) { parent.mkdirs(); } if (!file.exists()) { temporary.renameTo(file); if (!file.exists()) { throw new IOException("Can not rename " + temporary.getAbsolutePath() + " to " + file.getAbsolutePath() + " (media read only?)"); } } else { long now = System.currentTimeMillis(); if (file.lastModified() < now) { file.setLastModified(now); } } if (!file.isFile()) { throw new IOException("Not a file: " + file); } if (file.length() != length) { throw new IOException(DIGEST + " collision: " + file); } } inUse.remove(tempId); return new FileDataRecord(identifier, file); } catch (NoSuchAlgorithmException e) { throw new DataStoreException(DIGEST + " not available", e); } catch (IOException e) { throw new DataStoreException("Could not add record", e); } finally { if (temporary != null) { temporary.delete(); } } }
|
11
|
Code Sample 1:
public static void copy(File source, File dest) throws IOException { if (dest.isDirectory()) { dest = new File(dest + File.separator + source.getName()); } FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
@Override public void run() { try { if (LOG.isDebugEnabled()) { LOG.debug("Backupthread started"); } if (_file.exists()) { _file.delete(); } final ZipOutputStream zOut = new ZipOutputStream(new FileOutputStream(_file)); zOut.setLevel(9); final File xmlFile = File.createTempFile("mp3db", ".xml"); final OutputStream ost = new FileOutputStream(xmlFile); final XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(ost, "UTF-8"); writer.writeStartDocument("UTF-8", "1.0"); writer.writeCharacters("\n"); writer.writeStartElement("mp3db"); writer.writeAttribute("version", Integer.toString(Main.ENGINEVERSION)); final MediafileDAO mfDAO = new MediafileDAO(); final AlbumDAO aDAO = new AlbumDAO(); final CdDAO cdDAO = new CdDAO(); final CoveritemDAO ciDAO = new CoveritemDAO(); int itemCount = 0; try { itemCount += mfDAO.getCount(); itemCount += aDAO.getCount(); itemCount += cdDAO.getCount(); itemCount += ciDAO.getCount(); fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, itemCount)); } catch (final Exception e) { LOG.error("Error getting size", e); fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, -1)); } int cdCounter = 0; int mediafileCounter = 0; int albumCounter = 0; int coveritemCounter = 0; int counter = 0; final List<CdIf> data = cdDAO.getCdsOrderById(); if (data.size() > 0) { final Map<Integer, Integer> albums = new HashMap<Integer, Integer>(); final Iterator<CdIf> it = data.iterator(); while (it.hasNext() && !_break) { final CdIf cd = it.next(); final Integer cdId = Integer.valueOf(cdCounter++); writer.writeStartElement(TypeConstants.XML_CD); exportCd(writer, cd, cdId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); final List<MediafileIf> files = cd.getMediafiles(); final Iterator<MediafileIf> mfit = files.iterator(); MediafileIf mf; while (mfit.hasNext() && !_break) { mf = mfit.next(); final Integer mfId = Integer.valueOf(mediafileCounter++); writer.writeStartElement(TypeConstants.XML_MEDIAFILE); exportMediafile(writer, mf, mfId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); final AlbumIf a = mf.getAlbum(); if (a != null) { Integer inte; if (albums.containsKey(a.getAid())) { inte = albums.get(a.getAid()); writeLink(writer, TypeConstants.XML_ALBUM, inte); } else { inte = Integer.valueOf(albumCounter++); writer.writeStartElement(TypeConstants.XML_ALBUM); exportAlbum(writer, a, inte); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); albums.put(a.getAid(), inte); if (a.hasCoveritems() && !_break) { final List<CoveritemIf> covers = a.getCoveritems(); final Iterator<CoveritemIf> coit = covers.iterator(); while (coit.hasNext() && !_break) { final Integer coveritemId = Integer.valueOf(coveritemCounter++); exportCoveritem(writer, zOut, coit.next(), coveritemId); fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter)); } } writer.writeEndElement(); } GenericDAO.getEntityManager().close(); } writer.writeEndElement(); } writer.writeEndElement(); writer.flush(); it.remove(); GenericDAO.getEntityManager().close(); } } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); ost.flush(); ost.close(); if (_break) { zOut.close(); _file.delete(); } else { zOut.putNextEntry(new ZipEntry("mp3.xml")); final InputStream xmlIn = FileUtils.openInputStream(xmlFile); IOUtils.copy(xmlIn, zOut); xmlIn.close(); zOut.close(); } xmlFile.delete(); fireStatusEvent(new StatusEvent(this, StatusEventType.FINISH)); } catch (final Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Error backup database", e); } fireStatusEvent(new StatusEvent(this, e, "")); _messenger.fireMessageEvent(new MessageEvent(this, "ERROR", MessageEventTypeEnum.ERROR, GuiStrings.getInstance().getString("error.backup"), e)); } }
|
11
|
Code Sample 1:
public static void compressFile(File orig) throws IOException { File file = new File(INPUT + orig.toString()); File target = new File(OUTPUT + orig.toString().replaceAll(".xml", ".xml.gz")); System.out.println(" Compressing \"" + file.getName() + "\" into \"" + target + "\""); long l = file.length(); FileInputStream fileinputstream = new FileInputStream(file); GZIPOutputStream gzipoutputstream = new GZIPOutputStream(new FileOutputStream(target)); byte abyte0[] = new byte[1024]; int i; while ((i = fileinputstream.read(abyte0)) != -1) gzipoutputstream.write(abyte0, 0, i); fileinputstream.close(); gzipoutputstream.close(); long l1 = target.length(); System.out.println(" Initial size: " + l + "; Compressed size: " + l1 + "."); System.out.println(" Done."); System.out.println(); }
Code Sample 2:
protected void createValueListAnnotation(IProgressMonitor monitor, IPackageFragment pack, Map model) throws CoreException { IProject pj = pack.getJavaProject().getProject(); QualifiedName qn = new QualifiedName(JstActivator.PLUGIN_ID, JstActivator.PACKAGE_INFO_LOCATION); String location = pj.getPersistentProperty(qn); if (location != null) { IFolder javaFolder = pj.getFolder(new Path(NexOpenFacetInstallDataModelProvider.WEB_SRC_MAIN_JAVA)); IFolder packageInfo = javaFolder.getFolder(location); if (!packageInfo.exists()) { Logger.log(Logger.INFO, "package-info package [" + location + "] does not exists."); Logger.log(Logger.INFO, "ValueList annotation will not be added by this wizard. " + "You must add manually in your package-info class if exist " + "or create a new one at location " + location); return; } IFile pkginfo = packageInfo.getFile("package-info.java"); if (!pkginfo.exists()) { Logger.log(Logger.INFO, "package-info class at location [" + location + "] does not exists."); return; } InputStream in = pkginfo.getContents(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(in, baos); String content = new String(baos.toByteArray()); VelocityEngine engine = VelocityEngineHolder.getEngine(); model.put("adapterType", getAdapterType()); model.put("packageInfo", location.replace('/', '.')); model.put("defaultNumberPerPage", "5"); model.put("defaultSortDirection", "asc"); if (isFacadeAdapter()) { model.put("facadeType", "true"); } if (content.indexOf("@ValueLists({})") > -1) { appendValueList(monitor, model, pkginfo, content, engine, true); return; } else if (content.indexOf("@ValueLists") > -1) { appendValueList(monitor, model, pkginfo, content, engine, false); return; } String vl = VelocityEngineUtils.mergeTemplateIntoString(engine, "ValueList.vm", model); ByteArrayInputStream bais = new ByteArrayInputStream(vl.getBytes()); try { pkginfo.setContents(bais, true, false, monitor); } finally { bais.close(); } return; } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O exception", e); throw new CoreException(status); } catch (VelocityException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "Velocity exception", e); throw new CoreException(status); } finally { try { baos.close(); in.close(); } catch (IOException e) { } } } Logger.log(Logger.INFO, "package-info location property does not exists."); }
|
11
|
Code Sample 1:
public void createBankSignature() { byte b; try { _bankMessageDigest = MessageDigest.getInstance("MD5"); _bankSig = Signature.getInstance("MD5/RSA/PKCS#1"); _bankSig.initSign((PrivateKey) _bankPrivateKey); _bankMessageDigest.update(getBankString().getBytes()); _bankMessageDigestBytes = _bankMessageDigest.digest(); _bankSig.update(_bankMessageDigestBytes); _bankSignatureBytes = _bankSig.sign(); } catch (Exception e) { } ; }
Code Sample 2:
public String crypt(String suppliedPassword) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(suppliedPassword.getBytes()); String encriptedPassword = null; try { encriptedPassword = new String(Base64.encode(md.digest()), "ASCII"); } catch (UnsupportedEncodingException e) { } return encriptedPassword; }
|
00
|
Code Sample 1:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); try { URL url = new URL("http://placekitten.com/g/500/250"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setConnectTimeout(3000); conn.setReadTimeout(5000); Bitmap kitten = BitmapFactory.decodeStream(conn.getInputStream()); conn.disconnect(); Bitmap frame = BitmapFactory.decodeResource(getResources(), R.drawable.frame500); Bitmap output = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888); output.eraseColor(Color.BLACK); Canvas canvas = new Canvas(output); canvas.drawBitmap(kitten, 125, 125, new Paint()); canvas.drawBitmap(frame, 0, 0, new Paint()); Paint textPaint = new Paint(); textPaint.setColor(Color.WHITE); textPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD)); textPaint.setTextAlign(Align.CENTER); textPaint.setAntiAlias(true); textPaint.setTextSize(36); canvas.drawText("Cute", output.getWidth() / 2, (output.getHeight() / 2) + 140, textPaint); textPaint.setTextSize(24); canvas.drawText("Some of us just haz it.", output.getWidth() / 2, (output.getHeight() / 2) + 180, textPaint); ImageView imageView = (ImageView) this.findViewById(R.id.imageView); imageView.setImageBitmap(output); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
private void sendActionPerformed(java.awt.event.ActionEvent evt) { if (name.getText().length() < 3) { JOptionPane.showMessageDialog(comment, "Too short name (at least 3)"); return; } if (comment.getText().length() < 10) { JOptionPane.showMessageDialog(comment, "Too short comment (at least 10)"); return; } Thread t = new Thread(new Runnable() { public void run() { try { String data = URLEncoder.encode("send_id", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8"); data += "&" + URLEncoder.encode("author", "UTF-8") + "=" + URLEncoder.encode(name.getText(), "UTF-8"); data += "&" + URLEncoder.encode("location", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("user.language"), "UTF-8"); data += "&" + URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(email.getText(), "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(comment.getText(), "UTF-8"); data += "&" + URLEncoder.encode("rate", "UTF-8") + "=" + URLEncoder.encode(rate.getSelectedItem().toString(), "UTF-8"); System.out.println(data); URL url = new URL("http://javablock.sourceforge.net/book/index.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String address = rd.readLine(); JPanel panel = new JPanel(); panel.add(new JLabel("Comment added")); panel.add(new JTextArea("visit: http://javablock.sourceforge.net/")); JOptionPane.showMessageDialog(null, new JLabel("Comment sended correctly!")); wr.close(); rd.close(); hide(); } catch (IOException ex) { Logger.getLogger(guestBook.class.getName()).log(Level.SEVERE, null, ex); } } }); t.start(); }
|
00
|
Code Sample 1:
public static String sendGetData(URL url, Hashtable<String, String> data) throws IOException { StringBuilder outStringBuilder = new StringBuilder(); if (data != null) { for (Entry<String, String> entry : data.entrySet()) { outStringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8")); outStringBuilder.append("="); outStringBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8")); outStringBuilder.append("&"); } } URL innerURL = new URL(url.toString() + "?" + outStringBuilder.toString()); System.out.println("URL: " + innerURL); URLConnection urlConnection = innerURL.openConnection(); urlConnection.connect(); StringBuilder inStringBuilder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); Scanner inputScanner = new Scanner(urlConnection.getInputStream()); while (inputScanner.hasNext()) { inStringBuilder.append(inputScanner.next() + " "); } inputScanner.close(); reader.close(); return inStringBuilder.toString(); }
Code Sample 2:
private static void zip(ZipArchiveOutputStream zos, File efile, String base) throws IOException { if (efile.isDirectory()) { File[] lf = efile.listFiles(); base = base + File.separator + efile.getName(); for (File file : lf) { zip(zos, file, base); } } else { ZipArchiveEntry entry = new ZipArchiveEntry(efile, base + File.separator + efile.getName()); zos.setEncoding("utf-8"); zos.putArchiveEntry(entry); InputStream is = new FileInputStream(efile); IOUtils.copy(is, zos); is.close(); zos.closeArchiveEntry(); } }
|
00
|
Code Sample 1:
public static String encrypt(String value) { MessageDigest messageDigest; byte[] raw = null; try { messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(((String) value).getBytes("UTF-8")); raw = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return (new BASE64Encoder()).encode(raw); }
Code Sample 2:
protected BufferedImage handleBNException() { if (params.uri.startsWith("http://purl.pt/")) try { URLConnection connection = new URL(params.uri).openConnection(); if (params.uri.endsWith("/")) params.uri = params.uri.substring(0, params.uri.length() - 1); int index = params.uri.lastIndexOf("/"); params.uri = "http://purl.pt/homepage/" + params.uri.substring(index + 1) + "/" + params.uri.substring(index + 1); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String url = null; while ((url = reader.readLine()) != null) { index = url.indexOf(params.uri); if (index != -1) { url = url.substring(index); url = url.substring(0, url.indexOf("\"")); break; } } if (url != null) { connection = new URL(url).openConnection(); return processNewUri(connection); } } catch (Exception e) { } return null; }
|
00
|
Code Sample 1:
public void initialize(AtomPropsMenu menu) { propertiesMenu = menu; if (shieldings == null) { try { URL url = this.getClass().getClassLoader().getResource(RF); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); SharcReader sr1 = new SharcReader(br); shieldings = new Hashtable(); while (sr1.hasNext()) { SharcShielding ss1 = sr1.next(); shieldings.put(ss1.getMethod(), ss1); } String[] shieldingNames = new String[shieldings.size()]; int i = 0; Enumeration k = shieldings.keys(); while (k.hasMoreElements()) { shieldingNames[i] = (String) k.nextElement(); i++; } dialog = new SelectSharcReference(null, shieldingNames, true); } catch (Exception ex) { shieldings = null; } } }
Code Sample 2:
public static void exportDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = input + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); HashMap<Integer, String> languageIDs = new HashMap<Integer, String>(); HashMap<Integer, String> typeIDs = new HashMap<Integer, String>(); long tiempoInicio = System.currentTimeMillis(); Element dataBaseXML = new Element("database"); Element languages = new Element("languages"); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select * from language order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); languageIDs.put(id, name); Element language = new Element("language"); language.setText(name); languages.addContent(language); } dataBaseXML.addContent(languages); rs = stat.executeQuery("select * from type order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); typeIDs.put(id, name); } rs = stat.executeQuery("select distinct name from main order by name"); while (rs.next()) { String name = rs.getString("name"); Element image = new Element("image"); image.setAttribute("id", name); Statement stat2 = G.conn.createStatement(); ResultSet rs2 = stat2.executeQuery("select distinct idL from main where name = \"" + name + "\" order by idL"); while (rs2.next()) { int idL = rs2.getInt("idL"); Element language = new Element("language"); language.setAttribute("id", languageIDs.get(idL)); Statement stat3 = G.conn.createStatement(); ResultSet rs3 = stat3.executeQuery("select * from main where name = \"" + name + "\" and idL = " + idL + " order by idT"); while (rs3.next()) { int idT = rs3.getInt("idT"); String word = rs3.getString("word"); Element wordE = new Element("word"); wordE.setAttribute("type", typeIDs.get(idT)); wordE.setText(word); language.addContent(wordE); String pathSrc = input + File.separator + name.substring(0, 1).toUpperCase() + File.separator + name; String pathDst = output + File.separator + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } rs3.close(); stat3.close(); image.addContent(language); } rs2.close(); stat2.close(); dataBaseXML.addContent(image); } rs.close(); stat.close(); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); FileOutputStream f = new FileOutputStream(output + File.separator + G.imagesName); out.output(dataBaseXML, f); f.flush(); f.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
private void findFile() throws SchedulerException { java.io.InputStream f = null; String furl = null; File file = new File(getFileName()); if (!file.exists()) { URL url = classLoadHelper.getResource(getFileName()); if (url != null) { try { furl = URLDecoder.decode(url.getPath(), "UTF-8"); file = new File(furl); f = url.openStream(); } catch (java.io.UnsupportedEncodingException uee) { } catch (IOException ignor) { } } } else { try { f = new java.io.FileInputStream(file); } catch (FileNotFoundException e) { } } if (f == null && isFailOnFileNotFound()) { throw new SchedulerException("File named '" + getFileName() + "' does not exist. f == null && isFailOnFileNotFound()"); } else if (f == null) { getLog().warn("File named '" + getFileName() + "' does not exist. f == null"); } else { fileFound = true; try { if (furl != null) this.filePath = furl; else this.filePath = file.getAbsolutePath(); f.close(); } catch (IOException ioe) { getLog().warn("Error closing jobs file " + getFileName(), ioe); } } }
Code Sample 2:
public InputStream getResourceAsStream(String name) { InputStream is = parent.getResourceAsStream(name); if (is == null) { URL url = findResource(name); if (url != null) { try { is = url.openStream(); } catch (IOException e) { is = null; } } } return is; }
|
11
|
Code Sample 1:
static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
Code Sample 2:
public void copyImage(String from, String to) { File inputFile = new File(from); File outputFile = new File(to); try { if (inputFile.canRead()) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buf = new byte[65536]; int c; while ((c = in.read(buf)) > 0) out.write(buf, 0, c); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public void testTransactions0010() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0010 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("insert into #t0010 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0010"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); rowsToAdd = 6; for (int j = 1; j <= 2; j++) { count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i + ((j - 1) * rowsToAdd)); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); } rs = stmt.executeQuery("select s, i from #t0010"); count = 0; while (rs.next()) { count++; int i = rs.getInt(2); if (i > rowsToAdd) { i -= rowsToAdd; } assertEquals(rs.getString(1).trim().length(), i); } assertEquals(count, (2 * rowsToAdd)); stmt.close(); pstmt.close(); con.setAutoCommit(true); }
Code Sample 2:
public void sendRequest(String method) { try { url = new URL(urlStr); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod(method); httpURLConnection.setDoOutput(true); httpURLConnection.getOutputStream().flush(); httpURLConnection.getOutputStream().close(); System.out.println(httpURLConnection.getResponseMessage()); } catch (Exception e) { e.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } }
|
11
|
Code Sample 1:
public static void copy(File src, File dest) throws IOException { log.info("Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath()); if (!src.exists()) throw new IOException("File not found: " + src.getAbsolutePath()); if (!src.canRead()) throw new IOException("Source not readable: " + src.getAbsolutePath()); if (src.isDirectory()) { if (!dest.exists()) if (!dest.mkdirs()) throw new IOException("Could not create direcotry: " + dest.getAbsolutePath()); String children[] = src.list(); for (String child : children) { File src1 = new File(src, child); File dst1 = new File(dest, child); copy(src1, dst1); } } else { FileInputStream fin = null; FileOutputStream fout = null; byte[] buffer = new byte[4096]; int bytesRead; fin = new FileInputStream(src); fout = new FileOutputStream(dest); while ((bytesRead = fin.read(buffer)) >= 0) fout.write(buffer, 0, bytesRead); if (fin != null) { fin.close(); } if (fout != null) { fout.close(); } } }
Code Sample 2:
private void copyFile(File source, File destination) throws IOException { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); fileOutputStream = new FileOutputStream(destination); int bufferLength = 1024; byte[] buffer = new byte[bufferLength]; int readCount = 0; while ((readCount = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, readCount); } } finally { if (fileInputStream != null) { fileInputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } }
|
00
|
Code Sample 1:
public RecordIterator get(URL url) { RecordIterator recordIter = null; if (!SUPPORTED_PROTOCOLS.contains(url.getProtocol().toLowerCase())) { return null; } try { URL robotsUrl = new URL(url, ROBOTS_TXT); recordIter = new RecordIterator(urlInputStreamFactory.openStream(robotsUrl)); } catch (IOException e) { LOG.info("Failed to fetch " + url, e); } return recordIter; }
Code Sample 2:
protected String updateTwitter() { if (updatingTwitter) return null; updatingTwitter = true; String highestId = null; final Cursor cursor = query(TWITTER_TABLE, new String[] { KEY_TWEET_ID }, null, null, null); if (cursor.getCount() > 0) { cursor.moveToFirst(); highestId = cursor.getString(cursor.getColumnIndex(KEY_TWEET_ID)); } cursor.close(); final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); nameValuePairs.add(new BasicNameValuePair("screen_name", TWITTER_ACCOUNT)); nameValuePairs.add(new BasicNameValuePair("count", "" + MAX_TWEETS)); if (highestId != null) nameValuePairs.add(new BasicNameValuePair("since_id", highestId)); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final HttpParams params = new BasicHttpParams(); final SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry); final HttpClient httpclient = new DefaultHttpClient(mgr, params); final HttpGet request = new HttpGet(); final String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); String data = ""; try { final URI uri = new URI(TWITTER_URL + "?" + paramString); request.setURI(uri); final HttpResponse response = httpclient.execute(request); final BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) data += inputLine; in.close(); } catch (final URISyntaxException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final ClientProtocolException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final IOException e) { e.printStackTrace(); updatingTwitter = false; return "failed"; } try { final JSONArray tweets = new JSONArray(data); if (tweets == null) { updatingTwitter = false; return "failed"; } if (tweets.length() == 0) { updatingTwitter = false; return "none"; } final SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH); final SimpleDateFormat parser = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH); for (int i = 0; i < tweets.length(); i++) { final JSONObject tweet = tweets.getJSONObject(i); final ContentValues values = new ContentValues(); Log.v(TAG, "Datum van tweet: " + tweet.getString(KEY_TWEET_DATE)); values.put(KEY_TWEET_DATE, formatter.format(parser.parse(tweet.getString(KEY_TWEET_DATE)))); values.put(KEY_TWEET_TEXT, tweet.getString(KEY_TWEET_TEXT)); values.put(KEY_TWEET_ID, tweet.getString(KEY_TWEET_ID)); insert(TWITTER_TABLE, values); } } catch (final JSONException e) { Log.v(TAG, "JSON decodering is mislukt."); e.printStackTrace(); updatingTwitter = false; return "failed"; } catch (final ParseException e) { Log.v(TAG, "Datum decodering is mislukt."); e.printStackTrace(); updatingTwitter = false; return "failed"; } purgeTweets(); updatingTwitter = false; return "success"; }
|
11
|
Code Sample 1:
public static void createModelZip(String filename, String tempdir) throws EDITSException { try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); } catch (Exception e) { throw new EDITSException("Can not create a model in file " + filename + " from folder " + tempdir); } }
Code Sample 2:
public static void copyFile(File from, File to) throws IOException { ensureFile(to); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
private static void copyFile(String src, String dst) throws InvocationTargetException { try { FileChannel srcChannel; srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (FileNotFoundException e) { throw new InvocationTargetException(e, Messages.ALFWizardCreationAction_errorSourceFilesNotFound); } catch (IOException e) { throw new InvocationTargetException(e, Messages.ALFWizardCreationAction_errorCopyingFiles); } }
|
00
|
Code Sample 1:
public void write(OutputStream out, String className, InputStream classDefStream) throws IOException { ByteArrayOutputStream a = new ByteArrayOutputStream(); IOUtils.copy(classDefStream, a); a.close(); DataOutputStream da = new DataOutputStream(out); da.writeUTF(className); da.writeUTF(new String(base64.cipher(a.toByteArray()))); }
Code Sample 2:
protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } state = CONNECTED; logger.info("Successfully logged in"); version = determineVersion(); writer.setTargetVersion(version); logger.info("Determined Asterisk version: " + version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); }
|
11
|
Code Sample 1:
@Action(value = "ajaxFileUploads", results = { }) public void ajaxFileUploads() throws IOException { String extName = ""; String newFilename = ""; String nowTimeStr = ""; String realpath = ""; if (Validate.StrNotNull(this.getImgdirpath())) { realpath = "Uploads/" + this.getImgdirpath() + "/"; } else { realpath = this.isexistdir(); } SimpleDateFormat sDateFormat; Random r = new Random(); String savePath = ServletActionContext.getServletContext().getRealPath(""); savePath = savePath + realpath; HttpServletResponse response = ServletActionContext.getResponse(); int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000; sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); nowTimeStr = sDateFormat.format(new Date()); String filename = request.getHeader("X-File-Name"); if (filename.lastIndexOf(".") >= 0) { extName = filename.substring(filename.lastIndexOf(".")); } newFilename = nowTimeStr + rannum + extName; PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log.debug(ImgTAction.class.getName() + "has thrown an exception:" + ex.getMessage()); } try { is = request.getInputStream(); fos = new FileOutputStream(new File(savePath + newFilename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success:'" + realpath + newFilename + "'}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { this.setImgdirpath(null); fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
Code Sample 2:
@Override protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String filename = ServletRequestUtils.getRequiredStringParameter(request, "id"); final File file = new File(path, filename + ".html"); logger.debug("Getting static content from: " + file.getPath()); final InputStream is = getServletContext().getResourceAsStream(file.getPath()); OutputStream out = null; if (is != null) { try { out = response.getOutputStream(); IOUtils.copy(is, out); } catch (IOException ioex) { logger.error(ioex); } finally { is.close(); if (out != null) { out.close(); } } } return null; }
|
11
|
Code Sample 1:
@Override public String toString() { if (byteArrayOutputStream == null) return "<Unparsed binary data: Content-Type=" + getHeader("Content-Type") + " >"; String charsetName = getCharsetName(); if (charsetName == null) charsetName = "ISO-8859-1"; try { if (unzip) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); ByteArrayOutputStream unzippedResult = new ByteArrayOutputStream(); IOUtils.copy(gzipInputStream, unzippedResult); return unzippedResult.toString(charsetName); } else { return byteArrayOutputStream.toString(charsetName); } } catch (UnsupportedEncodingException e) { throw new OutputException(e); } catch (IOException e) { throw new OutputException(e); } }
Code Sample 2:
private static boolean copyFile(File srcFile, File tagFile) throws IOException { if (srcFile == null || tagFile == null) { return false; } int length = 2097152; FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(tagFile); FileChannel inC = in.getChannel(); FileChannel outC = out.getChannel(); int i = 0; while (true) { if (inC.position() == inC.size()) { inC.close(); outC.close(); break; } if ((inC.size() - inC.position()) < 20971520) length = (int) (inC.size() - inC.position()); else length = 20971520; inC.transferTo(inC.position(), length, outC); inC.position(inC.position() + length); i++; } return true; }
|
00
|
Code Sample 1:
public void run() { URLConnection con = null; try { con = url.openConnection(); if ("HTTPS".equalsIgnoreCase(url.getProtocol())) { HttpsURLConnection scon = (HttpsURLConnection) con; try { scon.setSSLSocketFactory(SSLUtil.getSSLSocketFactory(clientCertAlias)); HostnameVerifier hv = SSLUtil.getHostnameVerifier(hostCertLevel); if (hv != null) { scon.setHostnameVerifier(hv); } } catch (GeneralSecurityException e) { Debug.logError(e, module); } catch (GenericConfigException e) { Debug.logError(e, module); } } } catch (IOException e) { Debug.logError(e, module); } synchronized (URLConnector.this) { if (timedOut && con != null) { close(con); } else { connection = con; URLConnector.this.notify(); } } }
Code Sample 2:
public void run() { OutputStream out = null; InputStream in = null; boolean success = false; String absoluteFileName = ""; try { String fileName = getFileName(softwareLocation); File downloadFolder = new File(Properties.downloadFolder); if (downloadFolder.exists()) { if (downloadFolder.isDirectory()) { fileName = downloadFolder.getPath() + File.separator + fileName; } } else { downloadFolder.mkdir(); fileName = downloadFolder.getPath() + File.separator + fileName; } File softwareFile = new File(fileName); absoluteFileName = softwareFile.getAbsolutePath(); if (softwareFile.exists() && softwareFile.length() == softwareSize) { XohmLogger.debugPrintln("Software file already exists. Exiting..."); listener.downloadComplete(true, softwareName, absoluteFileName); return; } else { try { File[] oldFiles = downloadFolder.listFiles(); for (int i = 0; i < oldFiles.length; i++) { oldFiles[i].delete(); } } catch (Exception ex) { } } File softwareTempFile = File.createTempFile("XOHMCM", null); URL url = new URL(softwareLocation); out = new BufferedOutputStream(new FileOutputStream(softwareTempFile)); URLConnection connection = url.openConnection(); in = connection.getInputStream(); listener.downloadStarted(softwareName); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; listener.downloadProgressNotification(softwareName, numWritten, softwareSize); } out.flush(); out.close(); in.close(); if (copyFile(softwareTempFile, softwareFile)) { XohmLogger.debugPrintln("Download complete: " + absoluteFileName + "\t" + numWritten); success = true; softwareTempFile.delete(); } } catch (Exception ex) { XohmLogger.warningPrintln("Software Update download failed - " + ex.getMessage(), null, null); ex.printStackTrace(); } listener.downloadComplete(success, softwareName, absoluteFileName); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); try { FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { destinationChannel.close(); } } finally { sourceChannel.close(); } }
|
11
|
Code Sample 1:
public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } }
Code Sample 2:
public static void uncompress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new GZIPInputStream(new FileInputStream(srcFile)); output = new BufferedOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
|
00
|
Code Sample 1:
public static void main(final String... args) { int returnCode = 0; if (args.length == 0) { System.err.println("Usage: JWGet url..."); returnCode++; } final byte[] buf = new byte[8192]; for (final String arg : args) { try { final URL url = new URL(arg); OutputStream out = null; InputStream in = null; try { final URLConnection con = url.openConnection(); in = con.getInputStream(); final String location = con.getHeaderField("Content-Location"); final String outputFilename = new File((location != null ? new URL(url, location) : url).getFile()).getName(); System.err.println(outputFilename); out = new FileOutputStream(outputFilename); for (int bytesRead; (bytesRead = in.read(buf)) != -1; out.write(buf, 0, bytesRead)) ; } catch (final IOException e) { System.err.println(e); returnCode++; } finally { try { in.close(); } catch (final Exception ignore) { } try { out.close(); } catch (final Exception ignore) { } } } catch (final MalformedURLException e) { System.err.println(e); returnCode++; } } System.exit(returnCode); }
Code Sample 2:
private Element getXmlFromGeoNetwork(String urlIn, Session userSession) throws FailedActionException { Element results = null; try { URL url = new URL(urlIn); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); String cookie = (String) userSession.getAttribute("usercookie.object"); if (cookie != null) conn.setRequestProperty("Cookie", cookie); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { results = Xml.loadStream(in); } finally { in.close(); } } catch (Exception e) { throw new FailedActionException(FailedActionReason.SYSTEM_ERROR); } return results; }
|
00
|
Code Sample 1:
public InputSource resolveEntity(String pPublicId, String pSystemId) throws SAXException, IOException { try { URL url = new URL(pSystemId); String fileName = (String) urlMap.get(url); if (fileName != null) { FileInputStream istream = new FileInputStream(new File(schemaDir, fileName)); InputSource isource = new InputSource(istream); isource.setSystemId(url.toString()); return isource; } String file = url.getFile(); if (file == null) { file = ""; } else { int offset = file.lastIndexOf('/'); if (offset >= 0) { file = file.substring(offset + 1); } } if ("".equals(file)) { file = "schema.xsd"; } int offset = file.lastIndexOf('.'); String prefix; String suffix; String numAsStr = ""; if (offset > 0 && offset < file.length()) { prefix = file.substring(0, offset); suffix = file.substring(offset); } else { prefix = file; suffix = ".xsd"; } File f; for (int num = 1; ; ++num) { f = new File(schemaDir, prefix + numAsStr + suffix); if (f.exists()) { numAsStr = "_" + num; } else { break; } } InputStream istream = url.openStream(); schemaDir.mkdirs(); FileOutputStream fos = new FileOutputStream(f); try { byte[] buffer = new byte[1024]; for (; ; ) { int res = istream.read(buffer); if (res == -1) { break; } else if (res > 0) { fos.write(buffer, 0, res); } } istream.close(); fos.close(); fos = null; } finally { if (fos != null) { try { f.delete(); } catch (Throwable ignore) { } } } urlMap.put(url, f.getName()); InputSource isource = new InputSource(new FileInputStream(f)); isource.setSystemId(url.toString()); return isource; } catch (Exception e) { JaxMeServlet.this.log("Failed to resolve URL " + pSystemId, e); } return null; }
Code Sample 2:
@Override public int deleteStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); int result = statement.executeUpdate(sql.toString()); if (result == 0) log.warn(sql + " result row count is 0"); getConnection().commit(); return result; } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); throw new RuntimeException(); } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
|
11
|
Code Sample 1:
public static void decryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.DECRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }
Code Sample 2:
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(); } }
|
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) { FTPClient client = new FTPClient(); FileInputStream fis = null; try { client.connect("192.168.1.10"); client.login("a", "123456"); String filename = "D:\\DHTH5CLT\\HK3\\Ung dung phan tan\\FTP_JAVA\\FTP_DETAI\\FTP\\src\\DemoFTP\\filename\\5s.txt"; fis = new FileInputStream(filename); client.storeFile(filename, fis); client.logout(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
|
00
|
Code Sample 1:
public ContourGenerator(URL url, float modelMean, float modelStddev) throws IOException { this.modelMean = modelMean; this.modelStddev = modelStddev; List termsList = new ArrayList(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); line = reader.readLine(); while (line != null) { if (!line.startsWith("***")) { parseAndAdd(termsList, line); } line = reader.readLine(); } terms = (F0ModelTerm[]) termsList.toArray(terms); reader.close(); }
Code Sample 2:
protected BufferedImage handleNLIBException() { if (params.uri.startsWith("http://digar.nlib.ee/otsing/") || params.uri.startsWith("http://digar.nlib.ee/show")) try { String url = "http://digar.nlib.ee/gmap/nd" + params.uri.substring(params.uri.indexOf(":") + 1, params.uri.lastIndexOf("&")) + "-tiles/z0x0y0.jpeg"; URLConnection connection = new URL(url).openConnection(); return processNewUri(connection); } catch (Exception e) { try { if (params.uri.startsWith("http://digar.nlib.ee/show")) params.uri = "http://digar.nlib.ee/otsing/?pid=" + params.uri.substring(params.uri.lastIndexOf("/") + 1) + "&show"; URLConnection connection = new URL(params.uri).openConnection(); String url = params.uri; if (url.endsWith("&show")) url = url.substring(0, url.length() - 5); int index = url.lastIndexOf("?"); url = "stream" + url.substring(index); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String aux = null; while ((aux = reader.readLine()) != null) { index = aux.indexOf(url); if (index != -1) { url = "http://digar.nlib.ee/otsing/" + aux.substring(index); index = url.indexOf('>'); if (index == -1) index = url.indexOf("\""); url = url.substring(0, index); break; } } connection = new URL(url).openConnection(); return processNewUri(connection); } catch (Exception e2) { } } return null; }
|
11
|
Code Sample 1:
public boolean excuteBackup(String backupOrginlDrctry, String targetFileNm, String archiveFormat) throws JobExecutionException { File targetFile = new File(targetFileNm); File srcFile = new File(backupOrginlDrctry); if (!srcFile.exists()) { log.error("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 존재하지 않습니다."); throw new JobExecutionException("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 존재하지 않습니다."); } if (srcFile.isFile()) { log.error("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 파일입니다. 디렉토리명을 지정해야 합니다. "); throw new JobExecutionException("백업원본디렉토리[" + srcFile.getAbsolutePath() + "]가 파일입니다. 디렉토리명을 지정해야 합니다. "); } boolean result = false; FileInputStream finput = null; FileOutputStream fosOutput = null; ArchiveOutputStream aosOutput = null; ArchiveEntry entry = null; try { log.debug("charter set : " + Charset.defaultCharset().name()); fosOutput = new FileOutputStream(targetFile); aosOutput = new ArchiveStreamFactory().createArchiveOutputStream(archiveFormat, fosOutput); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { ((TarArchiveOutputStream) aosOutput).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); } File[] fileArr = srcFile.listFiles(); ArrayList list = EgovFileTool.getSubFilesByAll(fileArr); for (int i = 0; i < list.size(); i++) { File sfile = new File((String) list.get(i)); finput = new FileInputStream(sfile); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { entry = new TarArchiveEntry(sfile, new String(sfile.getAbsolutePath().getBytes(Charset.defaultCharset().name()), "8859_1")); ((TarArchiveEntry) entry).setSize(sfile.length()); } else { entry = new ZipArchiveEntry(sfile.getAbsolutePath()); ((ZipArchiveEntry) entry).setSize(sfile.length()); } aosOutput.putArchiveEntry(entry); IOUtils.copy(finput, aosOutput); aosOutput.closeArchiveEntry(); finput.close(); result = true; } aosOutput.close(); } catch (Exception e) { log.error("백업화일생성중 에러가 발생했습니다. 에러 : " + e.getMessage()); log.debug(e); result = false; throw new JobExecutionException("백업화일생성중 에러가 발생했습니다.", e); } finally { try { if (finput != null) finput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (aosOutput != null) aosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (fosOutput != null) fosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (result == false) targetFile.delete(); } catch (Exception e2) { log.error("IGNORE:", e2); } } return result; }
Code Sample 2:
public static void decompress(File apps,File f) throws IOException{ String filename=f.getName(); filename=filename.substring(0,filename.length()-PACK_FILE_SUFFIX.length()); File dir=new File(apps,filename); if(!dir.exists()){ dir.mkdirs(); } if(dir.isDirectory()){ JarFile jar=new JarFile(f); Enumeration<JarEntry> files=jar.entries(); while(files.hasMoreElements()){ JarEntry je=files.nextElement(); if(je.isDirectory()){ File item=new File(dir,je.getName()); item.mkdirs(); }else{ File item=new File(dir,je.getName()); item.getParentFile().mkdirs(); InputStream input=jar.getInputStream(je); FileOutputStream out=new FileOutputStream(item); IOUtils.copy(input, out); input.close(); out.close(); } //System.out.println(je.isDirectory() + je.getName()); } } }
|
11
|
Code Sample 1:
public Object send(URL url, Object params) throws Exception { params = processRequest(params); String response = ""; BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); response += in.readLine(); while (response != null) response += in.readLine(); in.close(); return processResponse(response); }
Code Sample 2:
private void readVersion() { URL url = ClassLoader.getSystemResource("version"); if (url == null) { return; } BufferedReader reader = null; String line = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { if (line.startsWith("Version=")) { version = (line.split("="))[1]; } if (line.startsWith("Revision=")) { revision = (line.split("="))[1]; } if (line.startsWith("Date=")) { String sSec = (line.split("="))[1]; Long lSec = Long.valueOf(sSec); compileDate = new Date(lSec); } } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return; }
|
00
|
Code Sample 1:
protected BufferedImage handleICCException() { if (params.uri.startsWith("http://vacani.icc.cat") || params.uri.startsWith("http://louisdl.louislibraries.org")) try { params.uri = params.uri.replace("cdm4/item_viewer.php", "cgi-bin/getimage.exe") + "&DMSCALE=3"; params.uri = params.uri.replace("/u?", "cgi-bin/getimage.exe?CISOROOT=").replace(",", "&CISOPTR=") + "&DMSCALE=3"; URL url = new URL(params.uri); URLConnection connection = url.openConnection(); return processNewUri(connection); } catch (Exception e) { } return null; }
Code Sample 2:
public static String[] getURLListFromResource(String resourceName, String regExFilter, boolean firstNoEmptyMatched) { String[] urlArray; Vector<String> urlVector = new Vector<String>(); try { ClassLoader classLoader = MqatMain.class.getClassLoader(); URLClassLoader urlClassLoader = (URLClassLoader) classLoader; Enumeration e = urlClassLoader.findResources(resourceName); for (; e.hasMoreElements(); ) { URL url = (URL) e.nextElement(); if ("file".equals(url.getProtocol())) { File file = new File(url.getPath()); File[] fileList = file.listFiles(); if (fileList != null) { for (int i = 0; i < fileList.length; i++) { String urlStr = fileList[i].toURL().toString(); if (urlStr.matches(regExFilter)) { urlVector.add(urlStr); } } } } else if ("jar".equals(url.getProtocol())) { JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); JarFile jarFile = jarConnection.getJarFile(); Enumeration jarEntries = jarFile.entries(); for (; jarEntries.hasMoreElements(); ) { JarEntry jarEntry = (JarEntry) jarEntries.nextElement(); if (!jarEntry.isDirectory()) { String urlStr = url.toString().substring(0, url.toString().lastIndexOf('!') + 1); urlStr += "/" + jarEntry; if (urlStr.matches(regExFilter)) { urlVector.add(urlStr); } } } } if (!urlVector.isEmpty() && firstNoEmptyMatched) { break; } } } catch (Exception ex) { ExceptionHandler.handle(ex, ExceptionHandler.NO_VISUAL); } urlArray = urlVector.toArray(new String[urlVector.size()]); return urlArray; }
|
11
|
Code Sample 1:
private static void createCompoundData(String dir, String type) { try { Set s = new HashSet(); File nouns = new File(dir + "index." + type); FileInputStream fis = new FileInputStream(nouns); InputStreamReader reader = new InputStreamReader(fis); StringBuffer sb = new StringBuffer(); int chr = reader.read(); while (chr >= 0) { if (chr == '\n' || chr == '\r') { String line = sb.toString(); if (line.length() > 0) { String[] spaceSplit = PerlHelp.split(line); for (int i = 0; i < spaceSplit.length; i++) { if (spaceSplit[i].indexOf('_') >= 0) { s.add(spaceSplit[i].replace('_', ' ')); } } } sb.setLength(0); } else { sb.append((char) chr); } chr = reader.read(); } System.out.println(type + " size=" + s.size()); File output = new File(dir + "compound." + type + "s.gz"); FileOutputStream fos = new FileOutputStream(output); GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos)); PrintWriter writer = new PrintWriter(gzos); writer.println("# This file was extracted from WordNet data, the following copyright notice"); writer.println("# from WordNet is attached."); writer.println("#"); writer.println("# This software and database is being provided to you, the LICENSEE, by "); writer.println("# Princeton University under the following license. By obtaining, using "); writer.println("# and/or copying this software and database, you agree that you have "); writer.println("# read, understood, and will comply with these terms and conditions.: "); writer.println("# "); writer.println("# Permission to use, copy, modify and distribute this software and "); writer.println("# database and its documentation for any purpose and without fee or "); writer.println("# royalty is hereby granted, provided that you agree to comply with "); writer.println("# the following copyright notice and statements, including the disclaimer, "); writer.println("# and that the same appear on ALL copies of the software, database and "); writer.println("# documentation, including modifications that you make for internal "); writer.println("# use or for distribution. "); writer.println("# "); writer.println("# WordNet 1.7 Copyright 2001 by Princeton University. All rights reserved. "); writer.println("# "); writer.println("# THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR "); writer.println("# IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- "); writer.println("# ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE "); writer.println("# OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT "); writer.println("# INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR "); writer.println("# OTHER RIGHTS. "); writer.println("# "); writer.println("# The name of Princeton University or Princeton may not be used in"); writer.println("# advertising or publicity pertaining to distribution of the software"); writer.println("# and/or database. Title to copyright in this software, database and"); writer.println("# any associated documentation shall at all times remain with"); writer.println("# Princeton University and LICENSEE agrees to preserve same. "); for (Iterator i = s.iterator(); i.hasNext(); ) { String mwe = (String) i.next(); writer.println(mwe); } writer.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private static void reconfigureDebug() { useFile = false; logValue = 0; String methodString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.method']/@value"); String levelString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.level']/@value"); String quietString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.quiet']/@value"); String fileString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.file']/@value"); String filemodeString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.filemode']/@value"); String calltraceString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.calltrace']/@value"); String rotateTimeoutString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatetimeout']/@value"); String rotateDestString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedest']/@value"); String rotateCompressString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatecompress']/@value"); String rotateDaysString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedays']/@value"); String rotateArchiveString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatearchive']/@value"); String rotateDeleteString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedelete']/@value"); String dirName = "."; if (rotateTimeoutString != null) { rotateTimeout = Integer.parseInt(rotateTimeoutString); } if (rotateDestString != null) { rotateDest = rotateDestString; } if (rotateCompressString != null && rotateCompressString.equalsIgnoreCase("true")) { rotateCompress = true; } if (rotateDaysString != null) { rotateDays = Integer.parseInt(rotateDaysString); } if (rotateArchiveString != null) { rotateArchive = rotateArchiveString; } if (rotateDeleteString != null && rotateDeleteString.equalsIgnoreCase("true")) { rotateDelete = true; } if (fileString != null && fileString.indexOf("/") != -1) { dirName = fileString.substring(0, fileString.lastIndexOf("/")); (new File(dirName)).mkdirs(); } if (methodString != null) { logMethod = methodString; } else { logMethod = "file"; } if (levelString != null) { logValue = Integer.parseInt(levelString); } else { logValue = 0; } if (calltraceString != null && calltraceString.equalsIgnoreCase("true")) { calltrace = true; } else { calltrace = false; } if (logMethod == null) { logMethod = "file"; } if (quietString != null) { if (quietString.equalsIgnoreCase("true")) { beQuiet = true; } } if (logMethod != null) { if (logMethod.equalsIgnoreCase("file")) { if (fileString != null) { logFile = fileString; } else { logFile = "log.txt"; } useFile = true; } } else { System.err.println("*** A debugging method (debug.method) is required in properties file!"); System.err.println("*** Please refer to configuration documentation."); System.exit(-1); } timesRepeated = 0; lastMessage = null; if (useFile) { logfile = new File(logFile); try { if (filemodeString != null && filemodeString.equalsIgnoreCase("append")) { ps = new PrintStream(new FileOutputStream(logfile, true)); } else { ps = new PrintStream(new FileOutputStream(logfile)); } isFile = true; Calendar calendar = new GregorianCalendar(); Date date = calendar.getTime(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); ps.println(); ps.println("--- Log file opened " + format1.format(date) + " ---"); } catch (FileNotFoundException e) { System.out.println("Debug: Unable to instantiate debugger: " + e.getMessage()); System.exit(-1); } catch (Exception e) { System.out.println("Debug: Unable to instantiate debugger - internal error: " + e.getMessage()); System.exit(-1); } } if (!registeredSchedule) { registeredSchedule = true; if (Server.getScheduler() != null) { Server.getScheduler().register("Log File Rotator for '" + logFile + "'", new SchedulerInterface() { public int getScheduleRate() { if (rotateTimeout != 0) { return rotateTimeout / 10; } return 0; } public void handle() { FileChannel srcChannel, destChannel; String destOutFile = logFile + "." + System.currentTimeMillis(); String destOutFileCompressed = logFile + "." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(logFile); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate log file '" + logFile + "': " + e); } } else { try { srcChannel = new FileInputStream(logFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to read log file '" + logFile + "': " + e.getMessage()); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate log file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFile + "'"); } if (rotateDelete && isFile) { try { ps.close(); } catch (Exception e) { } isFile = false; ps = null; (new File(logFile)).delete(); reconfigureDebug(); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(logFile + ".") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } } public String identString() { return "Debug Rotator for logs"; } }); } } }
|
00
|
Code Sample 1:
public void putMedia(Media m) { if (m == null) { return; } if (_conn == null) { log.error("DatabaseDatastore not connected!"); return; } if (log.isTraceEnabled()) { log.trace("Writing Media " + m.toString() + " to database"); } try { try { long trackid = getLocalID(m, _conn); if (m.isBaseDirty()) { if (log.isTraceEnabled()) { log.trace("Need to update base " + m.getID() + " to database"); } Integer artist = getArtistID(m, _conn); Integer author = getAuthorID(m, _conn); Integer artistAlias = getArtistAliasID(m, _conn); PreparedStatement s = _conn.prepareStatement("update media_track set track_name=?,track_artist_id=?,track_author_id=?,track_artist_alias_id=?,track_audit_timestamp=CURRENT_TIMESTAMP where track_id = ?"); s.setString(1, m.getName()); if (artist != null) { s.setLong(2, artist); } else { s.setNull(2, Types.BIGINT); } if (author != null) { s.setLong(3, author); } else { s.setNull(3, Types.BIGINT); } if (artistAlias != null) { s.setLong(4, artistAlias); } else { s.setNull(4, Types.BIGINT); } s.setLong(5, trackid); s.executeUpdate(); s.close(); } if (m.isUserDirty()) { if (log.isTraceEnabled()) { log.trace("Need to update user " + m.getID() + " to database"); } PreparedStatement s = _conn.prepareStatement("update media_track_rating set rating=?, play_count=? where track_id=? and user_id=?"); s.setFloat(1, m.getRating()); s.setLong(2, m.getPlayCount()); s.setLong(3, trackid); s.setLong(4, userid); if (s.executeUpdate() != 1) { s.close(); } s.close(); } if (m.isContentDirty()) { updateLocation(m, _conn); } _conn.commit(); m.resetDirty(); if (log.isTraceEnabled()) { log.trace("Committed " + m.getID() + " to database"); } } catch (Exception e) { log.error(e.toString(), e); _conn.rollback(); } } catch (Exception e) { log.error(e.toString(), e); } }
Code Sample 2:
private String getCurrentUniprotAccession(String accession) throws Exception { URL url = new URL(String.format(UNIPROT_ENTRY_QUERY_STRING, accession)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); connection.setRequestMethod("HEAD"); connection.connect(); if (connection.getResponseCode() != 200) { logger.debug("{} seems to be no UniProt accession", accession); throw new Exception("Missing UniProt entry for " + accession); } String effectiveUrl = connection.getURL().toString(); String confirmedAccession = effectiveUrl.substring(effectiveUrl.lastIndexOf('/') + 1); logger.debug("getCurrentUniprotAccession: {} -> {}", new Object[] { accession, confirmedAccession }); return confirmedAccession; }
|
00
|
Code Sample 1:
void bsort(int a[], int lo, int hi) throws Exception { for (int j = hi; j > lo; j--) { for (int i = lo; i < j; i++) { if (a[i] > a[i + 1]) { int T = a[i]; a[i] = a[i + 1]; a[i + 1] = T; pause(); } } } }
Code Sample 2:
public void doFTP() throws BuildException { FTPClient ftp = null; try { task.log("Opening FTP connection to " + task.getServer(), Project.MSG_VERBOSE); ftp = new FTPClient(); if (task.isConfigurationSet()) { ftp = FTPConfigurator.configure(ftp, task); } ftp.setRemoteVerificationEnabled(task.getEnableRemoteVerification()); ftp.connect(task.getServer(), task.getPort()); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("FTP connection failed: " + ftp.getReplyString()); } task.log("connected", Project.MSG_VERBOSE); task.log("logging in to FTP server", Project.MSG_VERBOSE); if ((task.getAccount() != null && !ftp.login(task.getUserid(), task.getPassword(), task.getAccount())) || (task.getAccount() == null && !ftp.login(task.getUserid(), task.getPassword()))) { throw new BuildException("Could not login to FTP server"); } task.log("login succeeded", Project.MSG_VERBOSE); if (task.isBinary()) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } else { ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } if (task.isPassive()) { task.log("entering passive mode", Project.MSG_VERBOSE); ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString()); } } if (task.getInitialSiteCommand() != null) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, task.getInitialSiteCommand()); } }, "initial site command: " + task.getInitialSiteCommand()); } if (task.getUmask() != null) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, "umask " + task.getUmask()); } }, "umask " + task.getUmask()); } if (task.getAction() == FTPTask.MK_DIR) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { makeRemoteDir(lftp, task.getRemotedir()); } }, task.getRemotedir()); } else if (task.getAction() == FTPTask.SITE_CMD) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, task.getSiteCommand()); } }, "Site Command: " + task.getSiteCommand()); } else { if (task.getRemotedir() != null) { task.log("changing the remote directory", Project.MSG_VERBOSE); ftp.changeWorkingDirectory(task.getRemotedir()); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString()); } } if (task.isNewer() && task.isTimeDiffAuto()) { task.setTimeDiffMillis(getTimeDiff(ftp)); } task.log(FTPTask.ACTION_STRS[task.getAction()] + " " + FTPTask.ACTION_TARGET_STRS[task.getAction()]); transferFiles(ftp); } } catch (IOException ex) { throw new BuildException("error during FTP transfer: " + ex, ex); } finally { if (ftp != null && ftp.isConnected()) { try { task.log("disconnecting", Project.MSG_VERBOSE); ftp.logout(); ftp.disconnect(); } catch (IOException ex) { } } } }
|
00
|
Code Sample 1:
private CachedQuery loadQuery(String path) throws CacheException, IOException, XQueryException { final URL url; final long lastModified; final InputStream is; try { url = getServletContext().getResource(path); assert (url != null); lastModified = url.openConnection().getLastModified(); is = url.openStream(); } catch (IOException e) { log(PrintUtils.prettyPrintStackTrace(e, -1)); throw e; } _lock.readLock().lock(); CachedQuery cached = _caches.get(path); if (cached == null || cached.loadTimeStamp < lastModified) { if (cached == null) { cached = new CachedQuery(); } XQueryParser parser = new XQueryParser(is); StaticContext staticEnv = parser.getStaticContext(); try { URI baseUri = url.toURI(); staticEnv.setBaseURI(baseUri); } catch (URISyntaxException e) { log(PrintUtils.prettyPrintStackTrace(e, -1)); } final XQueryModule module; try { module = parser.parse(); } catch (XQueryException e) { log(PrintUtils.prettyPrintStackTrace(e, -1)); _lock.readLock().unlock(); throw e; } _lock.readLock().unlock(); _lock.writeLock().lock(); cached.queryObject = module; cached.staticEnv = staticEnv; cached.loadTimeStamp = System.currentTimeMillis(); _caches.put(path, cached); _lock.writeLock().unlock(); _lock.readLock().lock(); try { module.staticAnalysis(staticEnv); } catch (XQueryException e) { log(PrintUtils.prettyPrintStackTrace(e, -1)); _lock.readLock().unlock(); throw e; } } _lock.readLock().unlock(); return cached; }
Code Sample 2:
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(); }
|
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:
protected void saveSelectedFiles() { if (dataList.getSelectedRowCount() == 0) { return; } if (dataList.getSelectedRowCount() == 1) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(dataList.getSelectedRow())); AttachFile entry = (AttachFile) obj; JFileChooser fc = new JFileChooser(); fc.setSelectedFile(new File(fc.getCurrentDirectory(), entry.getCurrentPath().getName())); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File current = entry.getCurrentPath(); File dest = fc.getSelectedFile(); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return; } else { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { for (Integer idx : dataList.getSelectedRows()) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(idx)); AttachFile entry = (AttachFile) obj; File current = entry.getCurrentPath(); File dest = new File(fc.getSelectedFile(), entry.getName()); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } return; } }
|
00
|
Code Sample 1:
public static void loginBayFiles() throws Exception { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); System.out.println("Trying to log in to bayfiles.com"); HttpPost httppost = new HttpPost("http://bayfiles.com/ajax_login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("action", "login")); formparams.add(new BasicNameValuePair("username", "")); formparams.add(new BasicNameValuePair("password", "")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); System.out.println("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("SESSID")) { sessioncookie = "SESSID=" + escookie.getValue(); System.out.println(sessioncookie); login = true; System.out.println("BayFiles.com Login success :)"); } } if (!login) { System.out.println("BayFiles.com Login failed :("); } }
Code Sample 2:
String openUrlAsString(String address, int maxLines) { StringBuffer sb; try { URL url = new URL(address); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); sb = new StringBuffer(); int count = 0; String line; while ((line = br.readLine()) != null && count++ < maxLines) sb.append(line + "\n"); in.close(); } catch (IOException e) { sb = null; } return sb != null ? new String(sb) : null; }
|
00
|
Code Sample 1:
private void fetchAvailable(ProgressObserver po) { if (po == null) throw new IllegalArgumentException("the progress observer can't be null"); if (availables == null) availables = new ArrayList<Dictionary>(); else availables.clear(); if (installed == null) initInstalled(); File home = SpellCheckPlugin.getHomeDir(jEdit.getActiveView()); File target = new File(home, "available.lst"); try { boolean skipDownload = false; if (target.exists()) { long modifiedDate = target.lastModified(); Calendar c = Calendar.getInstance(); c.setTimeInMillis(modifiedDate); Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.HOUR, -1); skipDownload = yesterday.before(c); } String enc = null; if (!skipDownload) { URL available_url = new URL(jEdit.getProperty(OOO_DICTS_PROP) + "available.lst"); URLConnection connect = available_url.openConnection(); connect.connect(); InputStream is = connect.getInputStream(); po.setMaximum(connect.getContentLength()); OutputStream os = new FileOutputStream(target); boolean copied = IOUtilities.copyStream(po, is, os, true); if (!copied) { Log.log(Log.ERROR, HunspellDictsManager.class, "Unable to download " + available_url.toString()); GUIUtilities.error(null, "spell-check-hunspell-error-fetch", new String[] { "Unable to download file " + available_url.toString() }); availables = null; if (target.exists()) target.delete(); return; } IOUtilities.closeQuietly(os); enc = connect.getContentEncoding(); } FileInputStream fis = new FileInputStream(target); Reader r; if (enc != null) { try { r = new InputStreamReader(fis, enc); } catch (UnsupportedEncodingException uee) { r = new InputStreamReader(fis, "UTF-8"); } } else { r = new InputStreamReader(fis, "UTF-8"); } BufferedReader br = new BufferedReader(r); for (String line = br.readLine(); line != null; line = br.readLine()) { Dictionary d = parseLine(line); if (d != null) { int ind = installed.indexOf(d); if (ind == -1) { d.installed = false; availables.add(d); } else { Dictionary id = installed.get(ind); if (!skipDownload) { Date lmd = fetchLastModifiedDate(id.archiveName); if (lmd != null) { id.lastModified = lmd; } } } } } IOUtilities.closeQuietly(fis); } catch (IOException ioe) { if (ioe instanceof UnknownHostException) { GUIUtilities.error(null, "spell-check-hunspell-error-unknownhost", new String[] { ioe.getMessage() }); } else { GUIUtilities.error(null, "spell-check-hunspell-error-fetch", new String[] { ioe.getMessage() }); } ioe.printStackTrace(); if (target.exists()) target.delete(); } }
Code Sample 2:
public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } }
|
11
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
public static String digest(String ha1, String ha2, String nonce) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(ha1, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(nonce, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(ha2, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
|
00
|
Code Sample 1:
private void checkResourceAvailable() throws XQException { HttpUriRequest head = new HttpHead(remoteURL); try { HttpResponse response = httpClient.execute(head); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw new XQException("Could not connect to the remote resource, response code: " + response.getStatusLine().getStatusCode() + " reason: " + response.getStatusLine().getReasonPhrase()); } catch (ClientProtocolException cpe) { throw new XQException(cpe.getMessage()); } catch (IOException ioe) { throw new XQException(ioe.getMessage()); } }
Code Sample 2:
protected ProductionTabsProperties(final PlayerID playerId, final List<Rule> mRules, final String mapDir) { m_rules = mRules; final ResourceLoader loader = ResourceLoader.getMapResourceLoader(mapDir); String propertyFile = PROPERTY_FILE + "." + playerId.getName() + ".properties"; URL url = loader.getResource(propertyFile); if (url == null) { propertyFile = PROPERTY_FILE + ".properties"; url = loader.getResource(propertyFile); if (url == null) { } else { try { m_properties.load(url.openStream()); } catch (final IOException e) { System.out.println("Error reading " + propertyFile + e); } } } }
|
11
|
Code Sample 1:
public static boolean copyFile(File from, File to, byte[] buf) { if (buf == null) buf = new byte[BUFFER_SIZE]; FileInputStream from_s = null; FileOutputStream to_s = null; try { from_s = new FileInputStream(from); to_s = new FileOutputStream(to); for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf)) to_s.write(buf, 0, bytesRead); from_s.close(); from_s = null; to_s.getFD().sync(); to_s.close(); to_s = null; } catch (IOException ioe) { return false; } finally { if (from_s != null) { try { from_s.close(); } catch (IOException ioe) { } } if (to_s != null) { try { to_s.close(); } catch (IOException ioe) { } } } return true; }
Code Sample 2:
public static void extractZip(Resource zip, FileObject outputDirectory) { ZipInputStream zis = null; try { zis = new ZipInputStream(zip.getResourceURL().openStream()); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String[] pathElements = entry.getName().split("/"); FileObject extractDir = outputDirectory; for (int i = 0; i < pathElements.length - 1; i++) { String pathElementName = pathElements[i]; FileObject pathElementFile = extractDir.resolveFile(pathElementName); if (!pathElementFile.exists()) { pathElementFile.createFolder(); } extractDir = pathElementFile; } String fileName = entry.getName(); if (fileName.endsWith("/")) { fileName = fileName.substring(0, fileName.length() - 1); } if (fileName.contains("/")) { fileName = fileName.substring(fileName.lastIndexOf('/') + 1); } if (entry.isDirectory()) { extractDir.resolveFile(fileName).createFolder(); } else { FileObject file = extractDir.resolveFile(fileName); file.createFile(); int size = (int) entry.getSize(); byte[] unpackBuffer = new byte[size]; zis.read(unpackBuffer, 0, size); InputStream in = null; OutputStream out = null; try { in = new ByteArrayInputStream(unpackBuffer); out = file.getContent().getOutputStream(); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } } catch (IOException e2) { throw new RuntimeException(e2); } finally { IOUtils.closeQuietly(zis); } }
|
11
|
Code Sample 1:
public static String digestMd5(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("文字列がNull、または空です。"); } MessageDigest md5; byte[] enclyptedHash; try { md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); enclyptedHash = md5.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ""; } return bytesToHexString(enclyptedHash); }
Code Sample 2:
public static String toMD5Sum(String arg0) { String ret; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(arg0.getBytes()); ret = toHexString(md.digest()); } catch (Exception e) { ret = arg0; } return ret; }
|
00
|
Code Sample 1:
private static String encryptSHA1URL(String x) throws Exception { java.security.MessageDigest d = null; d = java.security.MessageDigest.getInstance("SHA-1"); d.reset(); d.update(x.getBytes()); String passwd = ""; passwd = URLEncoder.encode(new String(d.digest()), "ISO-8859-1"); return passwd; }
Code Sample 2:
public void doFilter(final ServletRequest arg0, final ServletResponse arg1, final FilterChain arg2) throws IOException, ServletException { if (!this.init) { final HttpServletResponse response = Dynamic._.Cast(arg1); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Mainfilter not initialized."); return; } if (this.mainFilter != null) { try { URL url = this.context.getResource("/WEB-INF/classes/log4j.properties"); URLConnection uc = url.openConnection(); if (uc.getLastModified() != lastLoadLog4j) { lastLoadLog4j = uc.getLastModified(); try { uc.getInputStream().close(); } catch (Exception ignore) { } PropertyConfigurator.configure(url); } else { try { uc.getInputStream().close(); } catch (Exception ignore) { } } } catch (final Exception e) { } this.mainFilter.doFilter(arg0, arg1); } else { final HttpServletResponse response = Dynamic._.Cast(arg1); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Mainfilter bad setup."); } }
|
00
|
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 Node external_open_url(Node startAt) throws Exception { if (inUse) { throw new InterpreterException(StdErrors.extend(StdErrors.Already_used, "File already open")); } inUse = true; startAt.isGoodArgsLength(false, 2); ExtURL url = new ExtURL(startAt.getSubNode(1, Node.TYPE_STRING).getString()); String protocol = url.getProtocol(); String mode = null; Node props = null; Node datas = null; byte[] buffer = null; String old_c = null; String old_r = null; int max_i = startAt.size() - 1; if (startAt.elementAt(max_i).getSymbolicValue_undestructive().isVList()) { props = startAt.getSubNode(max_i--, Node.TYPE_LIST); } int i_ = 2; if (i_ <= max_i) { mode = startAt.getSubNode(i_++, Node.TYPE_STRING).getString().toUpperCase().trim(); if (protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https")) { if (!(mode.equals("GET") || mode.equals("POST") || mode.equals("PUT"))) { throw new InterpreterException(128010, "Unsupported request methode"); } } else if (protocol.equalsIgnoreCase("ftp") || protocol.equalsIgnoreCase("file")) { if (!(mode.equalsIgnoreCase("r") || mode.equalsIgnoreCase("w"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else if (protocol.equalsIgnoreCase("jar") || protocol.equalsIgnoreCase("stdin")) { if (!(mode.equalsIgnoreCase("r"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else if (protocol.equalsIgnoreCase("tcp") || protocol.equalsIgnoreCase("ssl+tcp")) { if (!(mode.equalsIgnoreCase("rw"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else if (protocol.equalsIgnoreCase("stdout") || protocol.equalsIgnoreCase("stderr")) { if (!(mode.equalsIgnoreCase("w"))) { throw new InterpreterException(128015, "Unsupported access methode"); } } else { throw new InterpreterException(128011, "Unsupported protocol"); } } if (i_ <= max_i) { if (!protocol.equalsIgnoreCase("http") && !protocol.equalsIgnoreCase("https")) { throw new InterpreterException(128016, "Unsupported request datas"); } datas = startAt.getSubNode(i_++, Node.TYPE_STRING | Node.TYPE_OBJECT); if (datas.isVObject()) { Object obj = datas.getVObjectExternalInstance(); if (External_Buffer.class.isInstance(obj)) { Buffer bbuffer = ((External_Buffer) obj).getBuffer(); buffer = bbuffer.read_bytes(); } else { throw new InterpreterException(StdErrors.extend(StdErrors.Invalid_parameter, "Object (" + obj.getClass().getName() + ") required " + External_Buffer.class.getName())); } } else { buffer = datas.getString().getBytes(); } } if (datas != null && mode != null && mode.equals("GET")) { throw new InterpreterException(128012, "GET request with data body"); } if (props != null && (!protocol.equalsIgnoreCase("http") && !protocol.equalsIgnoreCase("https"))) { throw new InterpreterException(128013, "Cannot handle header properties in request"); } try { if (protocol.equalsIgnoreCase("file") && mode != null && mode.equalsIgnoreCase("w")) { File f = new File(url.toURI()); outputStream = new FileOutputStream(f); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } else if (protocol.equalsIgnoreCase("tcp")) { tcpHost = url.getHost(); tcpPort = url.getPort(); if (tcpPort < 0 || tcpPort > 65535) { throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "" + tcpPort)); } socket = new Socket(tcpHost, tcpPort); if (readTimeOut > 0) { socket.setSoTimeout(readTimeOut); } inputStream = socket.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); outputStream = socket.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } else if (protocol.equalsIgnoreCase("ssl+tcp")) { tcpHost = url.getHost(); tcpPort = url.getPort(); if (tcpPort < 0 || tcpPort > 65535) { throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "" + tcpPort)); } SocketFactory socketFactory = SSLSocketFactory.getDefault(); socket = socketFactory.createSocket(tcpHost, tcpPort); if (readTimeOut > 0) { socket.setSoTimeout(readTimeOut); } inputStream = socket.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); outputStream = socket.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } else if (protocol.equalsIgnoreCase("stdout")) { setBufOut(System.out); } else if (protocol.equalsIgnoreCase("stderr")) { setBufOut(System.err); } else if (protocol.equalsIgnoreCase("stdin")) { setBufIn(System.in); } else { urlConnection = url.openConnection(); if (connectTimeOut > 0) { urlConnection.setConnectTimeout(connectTimeOut); } if (readTimeOut > 0) { urlConnection.setReadTimeout(readTimeOut); } urlConnection.setUseCaches(false); urlConnection.setDoInput(true); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpCon = (HttpURLConnection) urlConnection; if (props != null) { for (int i = 0; i < props.size(); i++) { Node pnode = props.getSubNode(i, Node.TYPE_DICO); String header_s = Node.getPairKey(pnode); String value_s = Node.node2VString(Node.getPairValue(pnode)).getString(); Interpreter.Log(" HTTP-Header: " + header_s + " : " + value_s); httpCon.setRequestProperty(header_s, value_s); } } if (mode != null && (mode.equals("POST") || mode.equals("PUT"))) { if (mode.equals("PUT")) { Interpreter.Log(" HTTP PUT: " + url.toString()); } else { Interpreter.Log(" HTTP POST: " + url.toString()); } urlConnection.setDoOutput(true); httpCon.setRequestMethod(mode); outputStream = urlConnection.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); output.write(buffer); output.flush(); } inputStream = urlConnection.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); } else { if (mode == null || (mode != null && mode.equalsIgnoreCase("r"))) { Interpreter.Log(" " + protocol + " read : " + url.toString()); inputStream = urlConnection.getInputStream(); inputBuffer = new BufferedInputStream(inputStream); input = new DataInputStream(inputBuffer); } else { Interpreter.Log(" " + protocol + " write : " + url.toString()); outputStream = urlConnection.getOutputStream(); outputBuffer = new BufferedOutputStream(outputStream); output = new DataOutputStream(outputBuffer); } } } } catch (Exception e) { throw e; } bytePos = 0; putHook(); return null; }
|
00
|
Code Sample 1:
public In(URL url) { try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(is, charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println("Could not open " + url); } }
Code Sample 2:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/zip"); response.setHeader("Content-Disposition", "inline; filename=c:/server1.zip"); try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("server.zip"); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; java.util.Properties props = new java.util.Properties(); props.load(new java.io.FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + "/SystemFiles/ENV_VAR.txt")); String jbossHomePath = props.getProperty("JBOSS_HOME"); jbossHomePath = jbossHomePath.replaceAll("deploy", "log"); FileInputStream fis = new FileInputStream(new File(jbossHomePath + "/server.log")); origin = new BufferedInputStream(fis, BUFFER); ZipEntry entry = new ZipEntry(jbossHomePath + "/server.log"); zipOut.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } origin.close(); zipOut.closeEntry(); java.io.FileInputStream fis1 = new java.io.FileInputStream(new java.io.File("server.zip")); java.nio.channels.FileChannel fc1 = fis1.getChannel(); int length1 = (int) fc1.size(); byte buffer[] = new byte[length1]; System.out.println("size of zip file = " + length1); fis1.read(buffer); OutputStream out1 = response.getOutputStream(); out1.write(buffer); fis1.close(); out1.close(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void main(String[] args) { File container = new File(ArchiveFeature.class.getProtectionDomain().getCodeSource().getLocation().toURI()); if (container == null) { throw new RuntimeException("this use-case isn't being invoked from the executable jar"); } JarFile jarFile = new JarFile(container); String artifactName = PROJECT_DIST_ARCHIVE + ".tar.gz"; File artifactFile = new File(".", artifactName); ZipEntry artifactEntry = jarFile.getEntry(artifactName); InputStream source = jarFile.getInputStream(artifactEntry); try { FileOutputStream dest = new FileOutputStream(artifactFile); try { IOUtils.copy(source, dest); } finally { IOUtils.closeQuietly(dest); } } finally { IOUtils.closeQuietly(source); } Project project = new Project(); project.setName("project"); project.init(); Target target = new Target(); target.setName("target"); project.addTarget(target); project.addBuildListener(new Log4jListener()); Untar untar = new Untar(); untar.setTaskName("untar"); untar.setSrc(artifactFile); untar.setDest(new File(".")); Untar.UntarCompressionMethod method = new Untar.UntarCompressionMethod(); method.setValue("gzip"); untar.setCompression(method); untar.setProject(project); untar.setOwningTarget(target); target.addTask(untar); untar.execute(); }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public void onClick(View v) { String uriAPI = "http://www.sina.com"; HttpPost httpRequest = new HttpPost(uriAPI); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("str", "post string")); try { httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == 200) { String strResult = EntityUtils.toString(httpResponse.getEntity()); mTextView1.setText(strResult); } else { mTextView1.setText("Error Response: " + httpResponse.getStatusLine().toString()); } } catch (ClientProtocolException e) { mTextView1.setText(e.getMessage().toString()); e.printStackTrace(); } catch (IOException e) { mTextView1.setText(e.getMessage().toString()); e.printStackTrace(); } catch (Exception e) { mTextView1.setText(e.getMessage().toString()); e.printStackTrace(); } }
Code Sample 2:
private static void copyFile(File sourceFile, File destFile) { try { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } catch (Exception e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
Code Sample 2:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
|
00
|
Code Sample 1:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(CONTENT_TYPE); URL url; URLConnection urlConn; DataOutputStream cgiInput; url = new URL("http://localhost:8080/ListeOnLine/Target"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); cgiInput = new DataOutputStream(urlConn.getOutputStream()); String content = "param1=" + URLEncoder.encode("first parameter") + "¶m2=" + URLEncoder.encode("the second one..."); cgiInput.writeBytes(content); cgiInput.flush(); cgiInput.close(); BufferedReader cgiOutput = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); PrintWriter servletOutput = response.getWriter(); servletOutput.print("<html><body><h1>This is the Source Servlet</h1><p />"); String line = null; while (null != (line = cgiOutput.readLine())) { servletOutput.println(line); } cgiOutput.close(); servletOutput.print("</body></html>"); servletOutput.close(); }
Code Sample 2:
public void handleEvent(Event event) { if (fileDialog == null) { fileDialog = new FileDialog(getShell(), SWT.OPEN); fileDialog.setText("Open device profile file..."); fileDialog.setFilterNames(new String[] { "Device profile (*.jar)" }); fileDialog.setFilterExtensions(new String[] { "*.jar" }); } fileDialog.open(); if (fileDialog.getFileName() != null) { File file; String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); try { file = new File(fileDialog.getFilterPath(), fileDialog.getFileName()); JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } jar.close(); urls[0] = file.toURL(); } catch (IOException ex) { Message.error("Error reading file: " + fileDialog.getFileName() + ", " + Message.getCauseMessage(ex), ex); return; } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileDialog.getFileName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { JarEntry entry = (JarEntry) it.next(); try { devices.put(entry.getName(), DeviceImpl.create(emulatorContext, classLoader, entry.getName(), SwtDevice.class)); } catch (IOException ex) { Message.error("Error parsing device profile, " + Message.getCauseMessage(ex), ex); return; } } for (int i = 0; i < deviceModel.size(); i++) { DeviceEntry entry = (DeviceEntry) deviceModel.elementAt(i); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), file.getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(file, deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } deviceModel.addElement(entry); for (int i = 0; i < deviceModel.size(); i++) { if (deviceModel.elementAt(i) == entry) { lsDevices.add(entry.getName()); lsDevices.select(i); } } Config.addDeviceEntry(entry); } lsDevicesListener.widgetSelected(null); } catch (IOException ex) { Message.error("Error adding device profile, " + Message.getCauseMessage(ex), ex); return; } } }
|
11
|
Code Sample 1:
public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } }
Code Sample 2:
public static void extractZip(Resource zip, FileObject outputDirectory) { ZipInputStream zis = null; try { zis = new ZipInputStream(zip.getResourceURL().openStream()); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String[] pathElements = entry.getName().split("/"); FileObject extractDir = outputDirectory; for (int i = 0; i < pathElements.length - 1; i++) { String pathElementName = pathElements[i]; FileObject pathElementFile = extractDir.resolveFile(pathElementName); if (!pathElementFile.exists()) { pathElementFile.createFolder(); } extractDir = pathElementFile; } String fileName = entry.getName(); if (fileName.endsWith("/")) { fileName = fileName.substring(0, fileName.length() - 1); } if (fileName.contains("/")) { fileName = fileName.substring(fileName.lastIndexOf('/') + 1); } if (entry.isDirectory()) { extractDir.resolveFile(fileName).createFolder(); } else { FileObject file = extractDir.resolveFile(fileName); file.createFile(); int size = (int) entry.getSize(); byte[] unpackBuffer = new byte[size]; zis.read(unpackBuffer, 0, size); InputStream in = null; OutputStream out = null; try { in = new ByteArrayInputStream(unpackBuffer); out = file.getContent().getOutputStream(); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } } catch (IOException e2) { throw new RuntimeException(e2); } finally { IOUtils.closeQuietly(zis); } }
|
11
|
Code Sample 1:
private void chooseGame(DefaultHttpClient httpclient) throws IOException, ClientProtocolException { HttpGet httpget = new HttpGet(Constants.STRATEGICDOMINATION_URL + "/gameboard.cgi?gameid=" + 1687); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("cg form get: " + response.getStatusLine()); if (entity != null) { InputStream inStream = entity.getContent(); IOUtils.copy(inStream, System.out); } System.out.println("cg set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } }
Code Sample 2:
public static void writeEntry(File file, File input) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ARGOUML_EXT); temporaryFile.deleteOnExit(); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); FileInputStream inputStream = new FileInputStream(input); ZipEntry entry = new ZipEntry(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + XMI_EXT); output.putNextEntry(new ZipEntry(entry)); IOUtils.copy(inputStream, output); output.closeEntry(); inputStream.close(); entry = new ZipEntry(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + ".argo"); output.putNextEntry(new ZipEntry(entry)); output.write(ArgoWriter.getArgoContent(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + XMI_EXT).getBytes()); output.closeEntry(); output.close(); temporaryFile.renameTo(file); } catch (IOException ioe) { throw new PersistenceException(ioe); } }
|
11
|
Code Sample 1:
public void render(Map map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE); File file = (File) map.get("targetFile"); IOUtils.copy(new FileInputStream(file), baos); httpServletResponse.setContentType(getContentType()); httpServletResponse.setContentLength(baos.size()); httpServletResponse.addHeader("Content-disposition", "attachment; filename=" + file.getName()); ServletOutputStream out = httpServletResponse.getOutputStream(); baos.writeTo(out); out.flush(); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public static String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
Code Sample 2:
protected static int[] sort(int[] arr) { for (int i = arr.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; }
|
00
|
Code Sample 1:
public void copyDependancyFiles() { for (String[] depStrings : getDependancyFiles()) { String source = depStrings[0]; String target = depStrings[1]; try { File sourceFile = PluginManager.getFile(source); IOUtils.copyEverything(sourceFile, new File(WEB_ROOT + target)); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Code Sample 2:
public boolean authenticate(String plaintext) throws NoSuchAlgorithmException { String[] passwordParts = this.password.split("\\$"); md = MessageDigest.getInstance("SHA-1"); md.update(passwordParts[1].getBytes()); isAuthenticated = toHex(md.digest(plaintext.getBytes())).equalsIgnoreCase(passwordParts[2]); return isAuthenticated; }
|
00
|
Code Sample 1:
private void getDirectories() throws IOException { if (user == null || ukey == null) { System.out.println("user and or ukey null"); } if (directories != null) { if (directories.length != 0) { System.out.println("directories already present"); return; } } HttpPost requestdirectories = new HttpPost(GET_DIRECTORIES_KEY_URL + "?ukey=" + ukey.getValue() + "&user=" + user.getValue()); HttpResponse dirResponse = getHttpClient().execute(requestdirectories); String ds = EntityUtils.toString(dirResponse.getEntity()); dirResponse.getEntity().consumeContent(); getDirectories(ds); }
Code Sample 2:
public void run() { LogPrinter.log(Level.FINEST, "Started Download at : {0, date, long}", new Date()); if (!PipeConnected) { throw new IllegalStateException("You should connect the pipe before with getInputStream()"); } InputStream ins = null; if (IsAlreadyDownloaded) { LogPrinter.log(Level.FINEST, "The file already Exists open and foward the byte"); try { ContentLength = (int) TheAskedFile.length(); ContentType = URLConnection.getFileNameMap().getContentTypeFor(TheAskedFile.getName()); ins = new FileInputStream(TheAskedFile); byte[] buffer = new byte[BUFFER_SIZE]; int read = ins.read(buffer); while (read >= 0) { Pipe.write(buffer, 0, read); read = ins.read(buffer); } } catch (IOException e) { e.printStackTrace(); } finally { if (ins != null) { try { ins.close(); } catch (IOException e) { } } } } else { LogPrinter.log(Level.FINEST, "the file does not exist locally so we try to download the thing"); File theDir = TheAskedFile.getParentFile(); if (!theDir.exists()) { theDir.mkdirs(); } for (URL url : ListFastest) { FileOutputStream fout = null; boolean OnError = false; long timestart = System.currentTimeMillis(); long bytecount = 0; try { URL newUrl = new URL(url.toString() + RequestedFile); LogPrinter.log(Level.FINEST, "the download URL = {0}", newUrl); URLConnection conn = newUrl.openConnection(); ContentType = conn.getContentType(); ContentLength = conn.getContentLength(); ins = conn.getInputStream(); fout = new FileOutputStream(TheAskedFile); byte[] buffer = new byte[BUFFER_SIZE]; int read = ins.read(buffer); while (read >= 0) { fout.write(buffer, 0, read); Pipe.write(buffer, 0, read); read = ins.read(buffer); bytecount += read; } Pipe.flush(); } catch (IOException e) { OnError = true; } finally { if (ins != null) { try { ins.close(); } catch (IOException e) { } } if (fout != null) { try { fout.close(); } catch (IOException e) { } } } long timeend = System.currentTimeMillis(); if (OnError) { continue; } else { long timetook = timeend - timestart; BigDecimal speed = new BigDecimal(bytecount).multiply(new BigDecimal(1000)).divide(new BigDecimal(timetook), MathContext.DECIMAL32); for (ReportCalculatedStatistique report : Listener) { report.reportUrlStat(url, speed, timetook); } break; } } } LogPrinter.log(Level.FINEST, "download finished at {0,date,long}", new Date()); if (Pipe != null) { try { Pipe.close(); } catch (IOException e) { e.printStackTrace(); } } }
|
00
|
Code Sample 1:
public void removeJarFiles() throws IOException { HashSet<GridNode> nodes = (HashSet) batchTask.returnNodeCollection(); Iterator<GridNode> ic = nodes.iterator(); InetAddress addLocal = InetAddress.getLocalHost(); String hostnameLocal = addLocal.getHostName(); while (ic.hasNext()) { GridNode node = ic.next(); String address = node.getPhysicalAddress(); InetAddress addr = InetAddress.getByName(address); byte[] rawAddr = addr.getAddress(); Map<String, String> attributes = node.getAttributes(); InetAddress hostname = InetAddress.getByAddress(rawAddr); if (hostname.getHostName().equals(hostnameLocal)) continue; String gridPath = attributes.get("GRIDGAIN_HOME"); FTPClient ftp = new FTPClient(); try { String[] usernamePass = inputNodes.get(hostname.getHostName()); ftp.connect(hostname); ftp.login(usernamePass[0], usernamePass[1]); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); continue; } ftp.login(usernamePass[0], usernamePass[1]); String directory = gridPath + "/libs/ext/"; ftp.changeWorkingDirectory(directory); FTPFile[] fs = ftp.listFiles(); for (FTPFile f : fs) { if (f.isDirectory()) continue; System.out.println(f.getName()); ftp.deleteFile(f.getName()); } ftp.sendCommand("rm *"); ftp.logout(); ftp.disconnect(); } catch (Exception e) { MessageCenter.getMessageCenter(BatchMainSetup.class).error("Problems with the FTP connection." + "A file has not been succesfully transfered", e); e.printStackTrace(); } } }
Code Sample 2:
@Override public void run() { Shell currentShell = Display.getCurrent().getActiveShell(); if (DMManager.getInstance().getOntology() == null) return; DataRecordSet data = DMManager.getInstance().getOntology().getDataView().dataset(); InputDialog input = new InputDialog(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.tablename"), data.getRelationName(), null); input.open(); String tablename = input.getValue(); if (tablename == null) return; super.getProfile().connect(); IManagedConnection mc = super.getProfile().getManagedConnection("java.sql.Connection"); java.sql.Connection sql = (java.sql.Connection) mc.getConnection().getRawConnection(); try { sql.setAutoCommit(false); DatabaseMetaData dbmd = sql.getMetaData(); ResultSet tables = dbmd.getTables(null, null, tablename, new String[] { "TABLE" }); if (tables.next()) { if (!MessageDialog.openConfirm(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.overwriteTable"))) return; Statement statement = sql.createStatement(); statement.executeUpdate("DROP TABLE " + tablename); statement.close(); } String createTableQuery = null; for (int i = 0; i < data.getNumAttributes(); i++) { if (DMManager.getInstance().getOntology().isIDAttribute(data.getAttribute(i))) continue; if (createTableQuery == null) createTableQuery = ""; else createTableQuery += ","; createTableQuery += getColumnDefinition(data.getAttribute(i)); } Statement statement = sql.createStatement(); statement.executeUpdate("CREATE TABLE " + tablename + "(" + createTableQuery + ")"); statement.close(); exportRecordSet(data, sql, tablename); sql.commit(); sql.setAutoCommit(true); MessageDialog.openInformation(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.successful")); } catch (SQLException e) { try { sql.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } MessageDialog.openError(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.failed")); e.printStackTrace(); } }
|
11
|
Code Sample 1:
protected void createValueListAnnotation(IProgressMonitor monitor, IPackageFragment pack, Map model) throws CoreException { IProject pj = pack.getJavaProject().getProject(); QualifiedName qn = new QualifiedName(JstActivator.PLUGIN_ID, JstActivator.PACKAGE_INFO_LOCATION); String location = pj.getPersistentProperty(qn); if (location != null) { IFolder javaFolder = pj.getFolder(new Path(NexOpenFacetInstallDataModelProvider.WEB_SRC_MAIN_JAVA)); IFolder packageInfo = javaFolder.getFolder(location); if (!packageInfo.exists()) { Logger.log(Logger.INFO, "package-info package [" + location + "] does not exists."); Logger.log(Logger.INFO, "ValueList annotation will not be added by this wizard. " + "You must add manually in your package-info class if exist " + "or create a new one at location " + location); return; } IFile pkginfo = packageInfo.getFile("package-info.java"); if (!pkginfo.exists()) { Logger.log(Logger.INFO, "package-info class at location [" + location + "] does not exists."); return; } InputStream in = pkginfo.getContents(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(in, baos); String content = new String(baos.toByteArray()); VelocityEngine engine = VelocityEngineHolder.getEngine(); model.put("adapterType", getAdapterType()); model.put("packageInfo", location.replace('/', '.')); model.put("defaultNumberPerPage", "5"); model.put("defaultSortDirection", "asc"); if (isFacadeAdapter()) { model.put("facadeType", "true"); } if (content.indexOf("@ValueLists({})") > -1) { appendValueList(monitor, model, pkginfo, content, engine, true); return; } else if (content.indexOf("@ValueLists") > -1) { appendValueList(monitor, model, pkginfo, content, engine, false); return; } String vl = VelocityEngineUtils.mergeTemplateIntoString(engine, "ValueList.vm", model); ByteArrayInputStream bais = new ByteArrayInputStream(vl.getBytes()); try { pkginfo.setContents(bais, true, false, monitor); } finally { bais.close(); } return; } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O exception", e); throw new CoreException(status); } catch (VelocityException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "Velocity exception", e); throw new CoreException(status); } finally { try { baos.close(); in.close(); } catch (IOException e) { } } } Logger.log(Logger.INFO, "package-info location property does not exists."); }
Code Sample 2:
public static File enregistrerFichier(String fileName, File file, String path, String fileMime) throws Exception { if (file != null) { try { HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(); String pathFile = session.getServletContext().getRealPath(path) + File.separator + fileName; File outfile = new File(pathFile); String[] nomPhotoTab = fileName.split("\\."); String extension = nomPhotoTab[nomPhotoTab.length - 1]; StringBuffer pathResBuff = new StringBuffer(nomPhotoTab[0]); for (int i = 1; i < nomPhotoTab.length - 1; i++) { pathResBuff.append(".").append(nomPhotoTab[i]); } String pathRes = pathResBuff.toString(); String nomPhoto = fileName; for (int i = 0; !outfile.createNewFile(); i++) { nomPhoto = pathRes + "_" + +i + "." + extension; pathFile = session.getServletContext().getRealPath(path) + File.separator + nomPhoto; outfile = new File(pathFile); } logger.debug(" enregistrerFichier - Enregistrement du fichier : " + pathFile); FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(outfile).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return outfile; } catch (IOException e) { logger.error("Erreur lors de l'enregistrement de l'image ", e); throw new Exception("Erreur lors de l'enregistrement de l'image "); } } return null; }
|
11
|
Code Sample 1:
public void run() { LOG.debug(this); String[] parts = createCmdArray(getCommand()); Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec(parts); if (isBlocking()) { process.waitFor(); StringWriter out = new StringWriter(); IOUtils.copy(process.getInputStream(), out); String stdout = out.toString().replaceFirst("\\s+$", ""); if (StringUtils.isNotBlank(stdout)) { LOG.info("Process stdout:\n" + stdout); } StringWriter err = new StringWriter(); IOUtils.copy(process.getErrorStream(), err); String stderr = err.toString().replaceFirst("\\s+$", ""); if (StringUtils.isNotBlank(stderr)) { LOG.error("Process stderr:\n" + stderr); } } } catch (IOException ioe) { LOG.error(String.format("Could not exec [%s]", getCommand()), ioe); } catch (InterruptedException ie) { LOG.error(String.format("Interrupted [%s]", getCommand()), ie); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
private void pushResource(String peerId, String communityId, String resourceFilePath, List<String> attachmentFilePaths) throws IOException { String urlString = "http://" + peerId + "/upload"; HttpURLConnection uploadConnection = null; DataOutputStream connOutput = null; FileInputStream fileInput = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "232404jkg4220957934FW"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try { File resourceFile = new File(resourceFilePath); if (!resourceFile.exists()) { LOG.error("JTellaAdapter: Resource file could not be found for push: " + resourceFilePath); return; } List<File> attachments = new ArrayList<File>(); for (String attachmentPath : attachmentFilePaths) { File attachFile = new File(attachmentPath); if (!attachFile.exists()) { LOG.error("JTellaAdapter: Attachment file could not be found for push: " + attachmentPath); return; } attachments.add(attachFile); } LOG.debug("JTellaAdapter: Initiating push to: " + urlString); URL url = new URL(urlString); uploadConnection = (HttpURLConnection) url.openConnection(); uploadConnection.setDoInput(true); uploadConnection.setDoOutput(true); uploadConnection.setUseCaches(false); uploadConnection.setRequestMethod("POST"); uploadConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); uploadConnection.setRequestProperty("Connection", "Keep-Alive"); uploadConnection.setRequestProperty("User-Agent", "UP2P"); uploadConnection.setRequestProperty("Accept", "[star]/[star]"); connOutput = new DataOutputStream(uploadConnection.getOutputStream()); connOutput.writeBytes(twoHyphens + boundary + lineEnd); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:community\"" + lineEnd + lineEnd); connOutput.writeBytes(communityId + lineEnd); connOutput.writeBytes(twoHyphens + boundary + lineEnd); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:pushupload\"" + lineEnd + lineEnd + "true" + lineEnd); connOutput.writeBytes(twoHyphens + boundary + lineEnd); boolean fileWriteComplete = false; boolean resourceFileWritten = false; File nextFile = null; while (!fileWriteComplete) { if (!resourceFileWritten) { nextFile = resourceFile; } else { nextFile = attachments.remove(0); } LOG.debug("JTellaAdapter: PUSHing file: " + nextFile.getAbsolutePath()); connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:filename\";" + " filename=\"" + nextFile.getName() + "\"" + lineEnd); connOutput.writeBytes(lineEnd); fileInput = new FileInputStream(nextFile); bytesAvailable = fileInput.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInput.read(buffer, 0, bufferSize); while (bytesRead > 0) { connOutput.write(buffer, 0, bufferSize); bytesAvailable = fileInput.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInput.read(buffer, 0, bufferSize); } connOutput.writeBytes(lineEnd); if (attachments.isEmpty()) { connOutput.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); } else { connOutput.writeBytes(twoHyphens + boundary + lineEnd); } resourceFileWritten = true; if (attachments.isEmpty()) { fileWriteComplete = true; } } BufferedReader inStream = new BufferedReader(new InputStreamReader(uploadConnection.getInputStream())); while (inStream.readLine() != null) ; inStream.close(); LOG.debug("JTellaAdapter: Push upload was succesful."); } catch (MalformedURLException ex) { LOG.error("JTellaAdapter: pushResource Malformed URL: " + ex); throw new IOException("pushResource failed for URL: " + urlString); } catch (IOException ioe) { LOG.error("JTellaAdapter: pushResource IOException: " + ioe); throw new IOException("pushResource failed for URL: " + urlString); } finally { try { if (fileInput != null) { fileInput.close(); } if (connOutput != null) { connOutput.flush(); } if (connOutput != null) { connOutput.close(); } if (uploadConnection != null) { uploadConnection.disconnect(); } } catch (IOException e) { LOG.error("JTellaAdapter: pushResource failed to close connection streams."); } } }
Code Sample 2:
protected RemoteInputStream getUrlResource(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setConnectTimeout(url_loading_time_out); conn.setReadTimeout(url_loading_time_out); conn.setRequestProperty("connection", "Keep-Alive"); conn.connect(); long last_modify_time = conn.getLastModified(); IOCacheService cache_service = CIO.getAppBridge().getIO().getCache(); if (cache_service != null) { RemoteInputStream cache = cache_service.findCache(url, last_modify_time); if (cache != null) { return cache; } } return new URLConnectionInputStream(url, conn); }
|
00
|
Code Sample 1:
public void sendMessage(Message m) throws IOException { URL url = new URL(strURL); urlcon = (HttpURLConnection) url.openConnection(); urlcon.setUseCaches(false); urlcon.setDefaultUseCaches(false); urlcon.setDoOutput(true); urlcon.setDoInput(true); urlcon.setRequestProperty("Content-type", "application/octet-stream"); urlcon.setAllowUserInteraction(false); HttpURLConnection.setDefaultAllowUserInteraction(false); urlcon.setRequestMethod("POST"); ObjectOutputStream oos = new ObjectOutputStream(urlcon.getOutputStream()); oos.writeObject(m); oos.flush(); oos.close(); }
Code Sample 2:
private void parseXmlFile() throws IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); if (file != null) { dom = db.parse(file); } else { dom = db.parse(url.openStream()); } } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException se) { se.printStackTrace(); } }
|
00
|
Code Sample 1:
public void encryptFile(String originalFile, String encryptedFile, String password) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(originalFile); out = new CipherOutputStream(new FileOutputStream(encryptedFile), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
Code Sample 2:
public void update(String target, String cfgVersion) throws MalformedURLException, FileNotFoundException, IOException { Debug.log("Config Updater", "Checking for newer configuration..."); URL url = new URL(target); String[] urlSplit = target.split("/"); this.fileName = urlSplit[urlSplit.length - 1]; BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(Main.getHomeDir() + "tmp-" + this.fileName)); URLConnection urlConnection = url.openConnection(); InputStream in = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int numRead; int fileSize = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); fileSize += numRead; } Debug.log("Config Updater", "Read latest configuration: " + fileSize + " bytes"); in.close(); out.close(); XMLController xmlC = new XMLController(); String newFileVersion = xmlC.readCfgVersion(Main.getHomeDir() + "tmp-" + this.fileName); if (new File(Main.getHomeDir() + this.fileName).exists()) { Debug.log("Config Updater", "Local configfile '" + Main.getHomeDir() + this.fileName + "' exists (version " + cfgVersion + ")"); if (Double.parseDouble(newFileVersion) > Double.parseDouble(cfgVersion)) { Debug.log("Config Updater", "Removing old config and replacing it with version " + newFileVersion); new File(Main.getHomeDir() + this.fileName).delete(); new File(Main.getHomeDir() + "tmp-" + this.fileName).renameTo(new File(Main.getHomeDir() + this.fileName)); this.result = "ConfigFile upgraded to version " + newFileVersion; } else { new File(Main.getHomeDir() + "tmp-" + this.fileName).delete(); Debug.log("Config Updater", "I already have the latest version " + cfgVersion); } } else { Debug.log("Config Updater", "Local config doesn't exist. Loading the new one, version " + newFileVersion); new File(Main.getHomeDir() + "tmp-" + this.fileName).renameTo(new File(Main.getHomeDir() + this.fileName)); this.result = "ConfigFile upgraded to version " + newFileVersion; } Debug.log("Config Updater", "Update of configuration done"); }
|
00
|
Code Sample 1:
private void resourceDirectoryCopy(String resource, IProject project, String target, IProgressMonitor monitor) throws URISyntaxException, IOException, CoreException { if (!target.endsWith("/")) { target += "/"; } String res = resource; if (!res.endsWith("/")) ; { res += "/"; } Enumeration<URL> it = bundle.findEntries(resource, "*", false); while (it.hasMoreElements()) { URL url = it.nextElement(); File f = new File(FileLocator.toFileURL(url).toURI()); String fName = f.getName(); boolean skip = false; for (String skiper : skipList) { if (fName.equals(skiper)) { skip = true; break; } } if (skip) { continue; } String targetName = target + fName; if (f.isDirectory()) { IFolder folder = project.getFolder(targetName); if (!folder.exists()) { folder.create(true, true, monitor); } resourceDirectoryCopy(res + f.getName(), project, targetName, monitor); } else if (f.isFile()) { IFile targetFile = project.getFile(targetName); InputStream is = null; try { is = url.openStream(); if (targetFile.exists()) { targetFile.setContents(is, true, false, monitor); } else { targetFile.create(is, true, monitor); } } catch (Exception e) { throw new IOException(e); } finally { if (is != null) { is.close(); } } } } }
Code Sample 2:
public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: MD5AttachHandler::invoke"); try { Message msg = msgContext.getRequestMessage(); SOAPConstants soapConstants = msgContext.getSOAPConstants(); org.apache.axis.message.SOAPEnvelope env = (org.apache.axis.message.SOAPEnvelope) msg.getSOAPEnvelope(); org.apache.axis.message.SOAPBodyElement sbe = env.getFirstBody(); org.w3c.dom.Element sbElement = sbe.getAsDOM(); org.w3c.dom.Node n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; org.w3c.dom.Element paramElement = (org.w3c.dom.Element) n; String href = paramElement.getAttribute(soapConstants.getAttrHref()); org.apache.axis.Part ap = msg.getAttachmentsImpl().getAttachmentByReference(href); javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils.getActivationDataHandler(ap); org.w3c.dom.Node timeNode = paramElement.getFirstChild(); long startTime = -1; if (timeNode != null && timeNode instanceof org.w3c.dom.Text) { String startTimeStr = ((org.w3c.dom.Text) timeNode).getData(); startTime = Long.parseLong(startTimeStr); } long receivedTime = System.currentTimeMillis(); long elapsedTime = -1; if (startTime > 0) elapsedTime = receivedTime - startTime; String elapsedTimeStr = elapsedTime + ""; java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); java.io.InputStream attachmentStream = dh.getInputStream(); int bread = 0; byte[] buf = new byte[64 * 1024]; do { bread = attachmentStream.read(buf); if (bread > 0) { md.update(buf, 0, bread); } } while (bread > -1); attachmentStream.close(); buf = null; String contentType = dh.getContentType(); if (contentType != null && contentType.length() != 0) { md.update(contentType.getBytes("US-ASCII")); } sbe = env.getFirstBody(); sbElement = sbe.getAsDOM(); n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; paramElement = (org.w3c.dom.Element) n; String MD5String = org.apache.axis.encoding.Base64.encode(md.digest()); String senddata = " elapsedTime=" + elapsedTimeStr + " MD5=" + MD5String; paramElement.appendChild(paramElement.getOwnerDocument().createTextNode(senddata)); sbe = new org.apache.axis.message.SOAPBodyElement(sbElement); env.clearBody(); env.addBodyElement(sbe); msg = new Message(env); msgContext.setResponseMessage(msg); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); throw AxisFault.makeFault(e); } log.debug("Exit: MD5AttachHandler::invoke"); }
|
00
|
Code Sample 1:
protected String getTextResponse(String address, boolean ignoreResponseCode) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); BufferedReader in = null; try { con.connect(); if (!ignoreResponseCode) { assertEquals(HttpURLConnection.HTTP_OK, con.getResponseCode()); } in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder builder = new StringBuilder(); String inputLine = null; while ((inputLine = in.readLine()) != null) { builder.append(inputLine); } return builder.toString(); } finally { if (in != null) { in.close(); } con.disconnect(); } }
Code Sample 2:
public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
|
11
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
public static String getETag(final String uri, final long lastModified) { try { final MessageDigest dg = MessageDigest.getInstance("MD5"); dg.update(uri.getBytes("utf-8")); dg.update(new byte[] { (byte) ((lastModified >> 24) & 0xFF), (byte) ((lastModified >> 16) & 0xFF), (byte) ((lastModified >> 8) & 0xFF), (byte) (lastModified & 0xFF) }); return CBASE64Codec.encode(dg.digest()); } catch (final Exception ignore) { return uri + lastModified; } }
|
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 Parameters getParameters(HttpExchange http) throws IOException { ParametersImpl params = new ParametersImpl(); String query = null; if (http.getRequestMethod().equalsIgnoreCase("GET")) { query = http.getRequestURI().getRawQuery(); } else if (http.getRequestMethod().equalsIgnoreCase("POST")) { InputStream in = new MaxInputStream(http.getRequestBody()); if (in != null) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOUtils.copyTo(in, bytes); query = new String(bytes.toByteArray()); in.close(); } } else { throw new IOException("Method not supported " + http.getRequestMethod()); } if (query != null) { for (String s : query.split("[&]")) { s = s.replace('+', ' '); int eq = s.indexOf('='); if (eq > 0) { params.add(URLDecoder.decode(s.substring(0, eq), "UTF-8"), URLDecoder.decode(s.substring(eq + 1), "UTF-8")); } } } return params; }
|
00
|
Code Sample 1:
public String get(String s, String encoding) throws Exception { if (!s.startsWith("http")) return ""; StringBuilder sb = new StringBuilder(); try { String result = null; URL url = new URL(s); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(false); if (encoding == null) encoding = "UTF-8"; BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding)); String inputLine; String contentType = connection.getContentType(); if (contentType.startsWith("text") || contentType.startsWith("application/xml")) { while ((inputLine = in.readLine()) != null) { sb.append(inputLine); sb.append("\n"); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw e; } return sb.toString(); }
Code Sample 2:
public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwdInDb = hexStringToByte(passwordInDb); byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); if (Arrays.equals(digest, digestInDb)) { return true; } else { return false; } }
|
11
|
Code Sample 1:
public static byte[] SHA1(String... strings) { try { MessageDigest digest = MessageDigest.getInstance("SHA1"); digest.reset(); for (String string : strings) { digest.update(string.getBytes("UTF-8")); } return digest.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.toString(), e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.toString(), e); } }
Code Sample 2:
private String calculateMD5(String value) { String finalString; try { MessageDigest md5Alg = MessageDigest.getInstance("MD5"); md5Alg.reset(); md5Alg.update(value.getBytes()); byte messageDigest[] = md5Alg.digest(); StringBuilder hexString = new StringBuilder(256); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } finalString = hexString.toString(); } catch (NoSuchAlgorithmException exc) { throw new RuntimeException("Hashing error happened:", exc); } return finalString; }
|
11
|
Code Sample 1:
private void zip(FileHolder fileHolder, int zipCompressionLevel) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File zipDestFile = new File(fileHolder.destFiles[0]); try { ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipDestFile)); for (int i = 0; i < fileHolder.selectedFileList.size(); i++) { File selectedFile = fileHolder.selectedFileList.get(i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); ZipEntry entry = new ZipEntry(selectedFile.getName()); outStream.setLevel(zipCompressionLevel); outStream.putNextEntry(entry); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.closeEntry(); this.inStream.close(); } outStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error zipping: " + zipDestFile); logger.logError(errEntry); } return; }
Code Sample 2:
public static void copyFromTo(String src, String des) { staticprintln("Copying:\"" + src + "\"\nto:\"" + des + "\""); try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(des).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } }
|
00
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static InputStream download_file(String sessionid, String key) { String urlString = "https://s2.cloud.cm/rpc/raw?c=Storage&m=download_file&key=" + key; try { URL url = new URL(urlString); Log.d("current running function name:", "download_file"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie", "PHPSESSID=" + sessionid); conn.setRequestMethod("POST"); conn.setDoInput(true); InputStream is = conn.getInputStream(); Log.d("size of the picture file", "" + is.available()); return is; } catch (Exception e) { e.printStackTrace(); } return null; }
|
11
|
Code Sample 1:
public void write(HttpServletRequest req, HttpServletResponse res, Object bean) throws IntrospectionException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException { res.setContentType(contentType); final Object r; if (HttpRpcServer.HttpRpcOutput.class.isAssignableFrom(bean.getClass())) { HttpRpcServer.HttpRpcOutput output = (HttpRpcServer.HttpRpcOutput) bean; r = output.getResult(); } else r = bean; if (r != null) { if (File.class.isAssignableFrom(r.getClass())) { File file = (File) r; InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } else if (InputStream.class.isAssignableFrom(r.getClass())) { InputStream in = null; try { in = (InputStream) r; IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } else if (XFile.class.isAssignableFrom(r.getClass())) { XFile file = (XFile) r; InputStream in = null; try { in = new XFileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) in.close(); } } res.getOutputStream().flush(); } }
Code Sample 2:
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(); }
|
11
|
Code Sample 1:
private static void downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } }
Code Sample 2:
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version_" + datastream + ".xml\""); } String xmlContent = URLDecoder.decode(req.getParameterValues(Constants.PARAM_CONTENT)[0], "UTF-8"); InputStream is = new ByteArrayInputStream(xmlContent.getBytes("UTF-8")); ServletOutputStream os = resp.getOutputStream(); IOUtils.copyStreams(is, os); os.flush(); }
|
11
|
Code Sample 1:
public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } }
Code Sample 2:
private void copyFile(File file, File targetFile) { try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] tmp = new byte[8192]; int read = -1; while ((read = bis.read(tmp)) > 0) { bos.write(tmp, 0, read); } bis.close(); bos.close(); } catch (Exception e) { if (!targetFile.delete()) { System.err.println("Ups, created copy cant be deleted (" + targetFile.getAbsolutePath() + ")"); } } }
|
00
|
Code Sample 1:
private boolean doDelete(String identifier) throws IOException, MalformedURLException { URL url = new URL(baseurl.toString() + "/" + identifier); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); huc.setRequestMethod("DELETE"); huc.connect(); if (huc.getResponseCode() == 200) { return true; } else return false; }
Code Sample 2:
public void testReceiveMessageWithHttpPost() throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://192.167.131.126/hotel/sms/create.htm"); String receipt = "2#12345:source:079456345:200:xxx:1234567809:userfred:"; String message = "11796 book owner2 password 238 12.09.2008 3 testname surname"; HttpParams params = new BasicHttpParams(); params.setParameter("TextMessage", message); httpPost.setParams(params); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); }
|
11
|
Code Sample 1:
private void init(URL url) { frame = new JInternalFrame(name); frame.addInternalFrameListener(this); listModel.add(listModel.size(), this); area = new JTextArea(); area.setMargin(new Insets(5, 5, 5, 5)); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String in; while ((in = reader.readLine()) != null) { area.append(in); area.append("\n"); } reader.close(); } catch (Exception e) { e.printStackTrace(); return; } th = area.getTransferHandler(); area.setFont(new Font("monospaced", Font.PLAIN, 12)); area.setCaretPosition(0); area.setDragEnabled(true); area.setDropMode(DropMode.INSERT); frame.getContentPane().add(new JScrollPane(area)); dp.add(frame); frame.show(); if (DEMO) { frame.setSize(300, 200); } else { frame.setSize(400, 300); } frame.setResizable(true); frame.setClosable(true); frame.setIconifiable(true); frame.setMaximizable(true); frame.setLocation(left, top); incr(); SwingUtilities.invokeLater(new Runnable() { public void run() { select(); } }); nullItem.addActionListener(this); setNullTH(); }
Code Sample 2:
public static void main(String[] args) throws IOException { System.out.println("start"); URL url = new URL("https://spreadsheets.google.com/feeds/list/" + "0AnoMCh3_x82sdERLR3FvVDBIWXpjT1JlcENmOFdERVE/" + "od7/public/basic"); InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { String[] mass = line.split("<entry>"); for (String m : mass) { System.out.println(m); } } }
|
00
|
Code Sample 1:
void readData(URL url) throws IOException { int i = 0, j = 0, k = 0; double xvalue, yvalue; double xindex, yindex; InputStream is = url.openStream(); is.mark(0); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); int columnsize = 0; double temp_prev = 0; double temp_new = 0; int first = 0; s = br.readLine(); StringTokenizer st = new StringTokenizer(s); columnsize = Integer.parseInt(st.nextToken()); data = new double[columnsize][100][100]; isize = 0; jsize = 0; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); for (k = 0; k < columnsize; k++) { temp_new = Double.parseDouble(st.nextToken()); if (first == 0) { temp_prev = temp_new; first = 1; } if (k == 0) { if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } } data[k][i][j] = temp_new; } j++; } isize = i + 1; jsize = j; }
Code Sample 2:
public void copyToZip(ZipOutputStream zout, String entryName) throws IOException { close(); ZipEntry entry = new ZipEntry(entryName); zout.putNextEntry(entry); if (!isEmpty() && this.tmpFile.exists()) { InputStream in = new FileInputStream(this.tmpFile); IOUtils.copyTo(in, zout); in.close(); } zout.flush(); zout.closeEntry(); delete(); }
|
00
|
Code Sample 1:
public void lookupAllFactories() throws IOException { Enumeration setOfFactories = null; ClassLoader classLoader = null; InputStream inputStream = null; classLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } return cl; } }); if (classLoader == null) { return; } try { setOfFactories = classLoader.getResources("META-INF/services/javax.print.StreamPrintServiceFactory"); } catch (IOException e) { e.printStackTrace(); throw new IOException("IOException during resource finding"); } try { while (setOfFactories.hasMoreElements()) { URL url = (URL) setOfFactories.nextElement(); inputStream = url.openStream(); getFactoryClasses(inputStream); } } catch (IOException e1) { e1.printStackTrace(); throw new IOException("IOException during resource reading"); } }
Code Sample 2:
protected void configure() { Enumeration<URL> resources = null; try { resources = classLoader.getResources(resourceName); } catch (IOException e) { binder().addError(e.getMessage(), e); return; } int resourceCount = 0; while (resources.hasMoreElements()) { URL url = resources.nextElement(); log.debug(url + " ..."); try { InputStream stream = url.openStream(); Properties props = new Properties(); props.load(stream); resourceCount++; addComponentsFromProperties(props, classLoader); } catch (IOException e) { binder().addError(e.getMessage(), e); } } log.info("Added components from " + resourceCount + " resources."); }
|
00
|
Code Sample 1:
public static final String encryptMD5(String decrypted) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(decrypted.getBytes()); byte hash[] = md5.digest(); md5.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } }
Code Sample 2:
public void actionPerformed(ActionEvent event) { System.out.println("STARTING on" + getQueryField().getText()); try { URL url = new URL(getQueryField().getText()); getResponseField().setText("opening URL"); DataInputStream inputStream = new DataInputStream(url.openStream()); getResponseField().setText("collating response"); String line = inputStream.readLine(); String totalString = ""; while (line != null) { totalString += line + "\n"; line = inputStream.readLine(); } System.out.println("FINISHING"); getResponseField().setText(totalString); System.out.println("FINISHED"); } catch (Exception exception) { getResponseField().setText(exception.getMessage() + "\n"); } }
|
11
|
Code Sample 1:
public BufferedImage extract() throws DjatokaException { boolean useRegion = false; int left = 0; int top = 0; int width = 50; int height = 50; boolean useleftDouble = false; Double leftDouble = 0.0; boolean usetopDouble = false; Double topDouble = 0.0; boolean usewidthDouble = false; Double widthDouble = 0.0; boolean useheightDouble = false; Double heightDouble = 0.0; if (params.getRegion() != null) { StringTokenizer st = new StringTokenizer(params.getRegion(), "{},"); String token; if ((token = st.nextToken()).contains(".")) { topDouble = Double.parseDouble(token); usetopDouble = true; } else top = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { leftDouble = Double.parseDouble(token); useleftDouble = true; } else left = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { heightDouble = Double.parseDouble(token); useheightDouble = true; } else height = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { widthDouble = Double.parseDouble(token); usewidthDouble = true; } else width = Integer.parseInt(token); useRegion = true; } try { if (is != null) { File f = File.createTempFile("tmp", ".jp2"); f.deleteOnExit(); FileOutputStream fos = new FileOutputStream(f); sourceFile = f.getAbsolutePath(); IOUtils.copyStream(is, fos); is.close(); fos.close(); } } catch (IOException e) { throw new DjatokaException(e); } try { Jp2_source inputSource = new Jp2_source(); Kdu_compressed_source input = null; Jp2_family_src jp2_family_in = new Jp2_family_src(); Jp2_locator loc = new Jp2_locator(); jp2_family_in.Open(sourceFile, true); inputSource.Open(jp2_family_in, loc); inputSource.Read_header(); input = inputSource; Kdu_codestream codestream = new Kdu_codestream(); codestream.Create(input); Kdu_channel_mapping channels = new Kdu_channel_mapping(); if (inputSource.Exists()) channels.Configure(inputSource, false); else channels.Configure(codestream); int ref_component = channels.Get_source_component(0); Kdu_coords ref_expansion = getReferenceExpansion(ref_component, channels, codestream); Kdu_dims image_dims = new Kdu_dims(); codestream.Get_dims(ref_component, image_dims); Kdu_coords imageSize = image_dims.Access_size(); Kdu_coords imagePosition = image_dims.Access_pos(); if (useleftDouble) left = imagePosition.Get_x() + (int) Math.round(leftDouble * imageSize.Get_x()); if (usetopDouble) top = imagePosition.Get_y() + (int) Math.round(topDouble * imageSize.Get_y()); if (useheightDouble) height = (int) Math.round(heightDouble * imageSize.Get_y()); if (usewidthDouble) width = (int) Math.round(widthDouble * imageSize.Get_x()); if (useRegion) { imageSize.Set_x(width); imageSize.Set_y(height); imagePosition.Set_x(left); imagePosition.Set_y(top); } int reduce = 1 << params.getLevelReductionFactor(); imageSize.Set_x(imageSize.Get_x() * ref_expansion.Get_x()); imageSize.Set_y(imageSize.Get_y() * ref_expansion.Get_y()); imagePosition.Set_x(imagePosition.Get_x() * ref_expansion.Get_x() / reduce - ((ref_expansion.Get_x() / reduce - 1) / 2)); imagePosition.Set_y(imagePosition.Get_y() * ref_expansion.Get_y() / reduce - ((ref_expansion.Get_y() / reduce - 1) / 2)); Kdu_dims view_dims = new Kdu_dims(); view_dims.Assign(image_dims); view_dims.Access_size().Set_x(imageSize.Get_x()); view_dims.Access_size().Set_y(imageSize.Get_y()); int region_buf_size = imageSize.Get_x() * imageSize.Get_y(); int[] region_buf = new int[region_buf_size]; Kdu_region_decompressor decompressor = new Kdu_region_decompressor(); decompressor.Start(codestream, channels, -1, params.getLevelReductionFactor(), 16384, image_dims, ref_expansion, new Kdu_coords(1, 1), false, Kdu_global.KDU_WANT_OUTPUT_COMPONENTS); Kdu_dims new_region = new Kdu_dims(); Kdu_dims incomplete_region = new Kdu_dims(); Kdu_coords viewSize = view_dims.Access_size(); incomplete_region.Assign(image_dims); int[] imgBuffer = new int[viewSize.Get_x() * viewSize.Get_y()]; int[] kduBuffer = null; while (decompressor.Process(region_buf, image_dims.Access_pos(), 0, 0, region_buf_size, incomplete_region, new_region)) { Kdu_coords newOffset = new_region.Access_pos(); Kdu_coords newSize = new_region.Access_size(); newOffset.Subtract(view_dims.Access_pos()); kduBuffer = region_buf; int imgBuffereIdx = newOffset.Get_x() + newOffset.Get_y() * viewSize.Get_x(); int kduBufferIdx = 0; int xDiff = viewSize.Get_x() - newSize.Get_x(); for (int j = 0; j < newSize.Get_y(); j++, imgBuffereIdx += xDiff) { for (int i = 0; i < newSize.Get_x(); i++) { imgBuffer[imgBuffereIdx++] = kduBuffer[kduBufferIdx++]; } } } BufferedImage image = new BufferedImage(imageSize.Get_x(), imageSize.Get_y(), BufferedImage.TYPE_INT_RGB); image.setRGB(0, 0, viewSize.Get_x(), viewSize.Get_y(), imgBuffer, 0, viewSize.Get_x()); if (params.getRotationDegree() > 0) { image = ImageProcessingUtils.rotate(image, params.getRotationDegree()); } decompressor.Native_destroy(); channels.Native_destroy(); if (codestream.Exists()) codestream.Destroy(); inputSource.Native_destroy(); input.Native_destroy(); jp2_family_in.Native_destroy(); return image; } catch (KduException e) { e.printStackTrace(); throw new DjatokaException(e); } catch (Exception e) { e.printStackTrace(); throw new DjatokaException(e); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } }
Code Sample 2:
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { Session session = HibernateUtil.getInstance().getSession(); response.setBufferSize(65536); ServletOutputStream outStream = response.getOutputStream(); File file = null; FileData fileData = null; try { String fileParameter = request.getParameter("file"); String disposition = request.getParameter("disposition"); if (fileParameter == null || fileParameter.equals("")) { String pi = request.getPathInfo(); int lastSlashIndex = pi.lastIndexOf("/") + 1; fileParameter = pi.substring(lastSlashIndex, pi.indexOf("_", pi.lastIndexOf("/"))); } if (fileParameter == null || fileParameter.equals("")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.flushBuffer(); Logger.log("file parameter not specified"); return; } if (disposition == null || disposition.equals("")) { String pi = request.getPathInfo(); String filename = pi.substring(pi.lastIndexOf("/") + 1); int underscoreIndex = filename.indexOf("_") + 1; disposition = filename.substring(underscoreIndex, filename.indexOf("_", underscoreIndex)); } file = (File) session.load(File.class, new Long(fileParameter)); Logger.log("Content requested=" + file.getName() + ":" + fileParameter + " Referral: " + request.getParameter("referer")); long ifModifiedSince = request.getDateHeader("If-Modified-Since"); long fileDate = file.getLastModifiedDate() - (file.getLastModifiedDate() % 1000); if (fileDate <= ifModifiedSince) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } response.setContentType(file.getContentType()); response.setHeader("Content-Description", file.getName()); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); response.flushBuffer(); Logger.log("Conditional GET: " + file.getName()); return; } User authUser = baseService.getAuthenticatedUser(session, request, response); if (!SecurityHelper.doesUserHavePermission(session, authUser, file, Permission.PERM.READ)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.flushBuffer(); Logger.log("Forbidden content requested: " + fileParameter); return; } String contentType = file.getContentType(); response.setContentType(contentType); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } String name = file.getName(); response.setHeader("Content-Description", name); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); java.io.File possibleDataFile = new java.io.File(BaseSystem.getTempDir() + file.getNameOnDisk()); if (possibleDataFile.exists()) { Logger.log("File exists in " + BaseSystem.getTempDir() + " pulling " + possibleDataFile.getName()); FileInputStream fileInputStream = new FileInputStream(possibleDataFile); try { IOUtils.copy(fileInputStream, outStream); } finally { try { fileInputStream.close(); } catch (Throwable t) { } } } else { List<FileData> fileDataList = HibernateUtil.getInstance().executeQuery(session, "from " + FileData.class.getSimpleName() + " where permissibleObject.id = " + file.getId()); if (fileDataList.size() == 0) { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); Logger.log("Requested content not found: " + fileParameter); response.flushBuffer(); return; } fileData = (FileData) fileDataList.get(0); FileOutputStream fileOutputStream = null; try { java.io.File tmpDir = new java.io.File(BaseSystem.getTempDir()); tmpDir.mkdirs(); fileOutputStream = new FileOutputStream(possibleDataFile); IOUtils.write(fileData.getData(), fileOutputStream); } catch (Throwable t) { Logger.log(t); } finally { try { fileOutputStream.close(); } catch (Throwable t) { } } IOUtils.write(fileData.getData(), outStream); } } catch (Throwable t) { Logger.log(t); try { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.flushBuffer(); } catch (Throwable tt) { } try { response.reset(); response.resetBuffer(); } catch (Throwable tt) { } } finally { file = null; fileData = null; try { outStream.flush(); } catch (Throwable t) { } try { outStream.close(); } catch (Throwable t) { } try { session.close(); } catch (Throwable t) { } } }
|
00
|
Code Sample 1:
public void initialize(IProgressMonitor monitor) throws JETException { IProgressMonitor progressMonitor = monitor; progressMonitor.beginTask("", 10); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_GeneratingJETEmitterFor_message", new Object[] { getTemplateURI() })); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); try { final JETCompiler jetCompiler = getTemplateURIPath() == null ? new MyBaseJETCompiler(getTemplateURI(), getEncoding(), getClassLoader()) : new MyBaseJETCompiler(getTemplateURIPath(), getTemplateURI(), getEncoding(), getClassLoader()); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETParsing_message", new Object[] { jetCompiler.getResolvedTemplateURI() })); jetCompiler.parse(); progressMonitor.worked(1); String packageName = jetCompiler.getSkeleton().getPackageName(); if (getTemplateURIPath() != null) { URI templateURI = URI.createURI(getTemplateURIPath()[0]); URLClassLoader theClassLoader = null; if (templateURI.isPlatformResource()) { IProject project = workspace.getRoot().getProject(templateURI.segment(1)); if (JETNature.getRuntime(project) != null) { List<URL> urls = new ArrayList<URL>(); IJavaProject javaProject = JavaCore.create(project); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); for (IClasspathEntry classpathEntry : javaProject.getResolvedClasspath(true)) { if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath projectPath = classpathEntry.getPath(); IProject otherProject = workspace.getRoot().getProject(projectPath.segment(0)); IJavaProject otherJavaProject = JavaCore.create(otherProject); urls.add(new File(otherProject.getLocation() + "/" + otherJavaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); } } theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderSuperAction(urls)); } } else if (templateURI.isPlatformPlugin()) { final Bundle bundle = Platform.getBundle(templateURI.segment(1)); if (bundle != null) { theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderBundleAction(bundle)); } } if (theClassLoader != null) { String className = (packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName(); if (className.endsWith("_")) { className = className.substring(0, className.length() - 1); } try { Class<?> theClass = theClassLoader.loadClass(className); Class<?> theOtherClass = null; try { theOtherClass = getClassLoader().loadClass(className); } catch (ClassNotFoundException exception) { } if (theClass != theOtherClass) { String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } return; } } catch (ClassNotFoundException exception) { } } } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); jetCompiler.generate(outputStream); final InputStream contents = new ByteArrayInputStream(outputStream.toByteArray()); if (!javaModel.isOpen()) { javaModel.open(new SubProgressMonitor(progressMonitor, 1)); } else { progressMonitor.worked(1); } final IProject project = workspace.getRoot().getProject(jetEmitter.getProjectName()); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETPreparingProject_message", new Object[] { project.getName() })); IJavaProject javaProject; if (!project.exists()) { progressMonitor.subTask("JET creating project " + project.getName()); project.create(new SubProgressMonitor(progressMonitor, 1)); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreatingProject_message", new Object[] { project.getName() })); IProjectDescription description = workspace.newProjectDescription(project.getName()); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); description.setLocation(null); project.open(new SubProgressMonitor(progressMonitor, 1)); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); } else { project.open(new SubProgressMonitor(progressMonitor, 5)); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); } javaProject = JavaCore.create(project); List<IClasspathEntry> classpath = new UniqueEList<IClasspathEntry>(Arrays.asList(javaProject.getRawClasspath())); for (int i = 0, len = classpath.size(); i < len; i++) { IClasspathEntry entry = classpath.get(i); if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && ("/" + project.getName()).equals(entry.getPath().toString())) { classpath.remove(i); } } progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETInitializingProject_message", new Object[] { project.getName() })); IClasspathEntry classpathEntry = JavaCore.newSourceEntry(new Path("/" + project.getName() + "/src")); IClasspathEntry jreClasspathEntry = JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")); classpath.add(classpathEntry); classpath.add(jreClasspathEntry); classpath.addAll(getClassPathEntries()); IFolder sourceFolder = project.getFolder(new Path("src")); if (!sourceFolder.exists()) { sourceFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } IFolder runtimeFolder = project.getFolder(new Path("bin")); if (!runtimeFolder.exists()) { runtimeFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), new SubProgressMonitor(progressMonitor, 1)); javaProject.setOutputLocation(new Path("/" + project.getName() + "/bin"), new SubProgressMonitor(progressMonitor, 1)); javaProject.close(); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETOpeningJavaProject_message", new Object[] { project.getName() })); javaProject.open(new SubProgressMonitor(progressMonitor, 1)); IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots(); IPackageFragmentRoot sourcePackageFragmentRoot = null; for (int j = 0; j < packageFragmentRoots.length; ++j) { IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[j]; if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) { sourcePackageFragmentRoot = packageFragmentRoot; break; } } StringTokenizer stringTokenizer = new StringTokenizer(packageName, "."); IProgressMonitor subProgressMonitor = new SubProgressMonitor(progressMonitor, 1); subProgressMonitor.beginTask("", stringTokenizer.countTokens() + 4); subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_CreateTargetFile_message")); IContainer sourceContainer = sourcePackageFragmentRoot == null ? project : (IContainer) sourcePackageFragmentRoot.getCorrespondingResource(); while (stringTokenizer.hasMoreElements()) { String folderName = stringTokenizer.nextToken(); sourceContainer = sourceContainer.getFolder(new Path(folderName)); if (!sourceContainer.exists()) { ((IFolder) sourceContainer).create(false, true, new SubProgressMonitor(subProgressMonitor, 1)); } } IFile targetFile = sourceContainer.getFile(new Path(jetCompiler.getSkeleton().getClassName() + ".java")); if (!targetFile.exists()) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreating_message", new Object[] { targetFile.getFullPath() })); targetFile.create(contents, true, new SubProgressMonitor(subProgressMonitor, 1)); } else { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETUpdating_message", new Object[] { targetFile.getFullPath() })); targetFile.setContents(contents, true, true, new SubProgressMonitor(subProgressMonitor, 1)); } subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETBuilding_message", new Object[] { project.getName() })); project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, new SubProgressMonitor(subProgressMonitor, 1)); boolean errors = hasErrors(subProgressMonitor, targetFile); if (!errors) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETLoadingClass_message", new Object[] { jetCompiler.getSkeleton().getClassName() + ".class" })); List<URL> urls = new ArrayList<URL>(); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURI().toURL()); final Set<Bundle> bundles = new HashSet<Bundle>(); LOOP: for (IClasspathEntry jetEmitterClasspathEntry : jetEmitter.getClasspathEntries()) { IClasspathAttribute[] classpathAttributes = jetEmitterClasspathEntry.getExtraAttributes(); if (classpathAttributes != null) { for (IClasspathAttribute classpathAttribute : classpathAttributes) { if (classpathAttribute.getName().equals(CodeGenUtil.EclipseUtil.PLUGIN_ID_CLASSPATH_ATTRIBUTE_NAME)) { Bundle bundle = Platform.getBundle(classpathAttribute.getValue()); if (bundle != null) { bundles.add(bundle); continue LOOP; } } } } urls.add(new URL("platform:/resource" + jetEmitterClasspathEntry.getPath() + "/")); } URLClassLoader theClassLoader = AccessController.doPrivileged(new GetURLClassLoaderSuperBundlesAction(bundles, urls)); Class<?> theClass = theClassLoader.loadClass((packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName()); String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } } subProgressMonitor.done(); } catch (CoreException exception) { throw new JETException(exception); } catch (Exception exception) { throw new JETException(exception); } finally { progressMonitor.done(); } }
Code Sample 2:
private boolean confirmAndModify(MDPRArchiveAccessor archiveAccessor) { String candidateBackupName = archiveAccessor.getArchiveFileName() + ".old"; String backupName = createUniqueFileName(candidateBackupName); MessageFormat format = new MessageFormat(AUTO_MOD_MESSAGE); String message = format.format(new String[] { backupName }); boolean ok = MessageDialog.openQuestion(new Shell(Display.getDefault()), AUTO_MOD_TITLE, message); if (ok) { File orig = new File(archiveAccessor.getArchiveFileName()); try { IOUtils.copyFiles(orig, new File(backupName)); DeviceRepositoryAccessorManager dram = new DeviceRepositoryAccessorManager(archiveAccessor, new ODOMFactory()); dram.writeRepository(); } catch (IOException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } catch (RepositoryException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } } return ok; }
|
11
|
Code Sample 1:
public static String SHA(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(s.getBytes(), 0, s.getBytes().length); byte[] hash = md.digest(); StringBuilder sb = new StringBuilder(); int msb; int lsb = 0; int i; for (i = 0; i < hash.length; i++) { msb = ((int) hash[i] & 0x000000FF) / 16; lsb = ((int) hash[i] & 0x000000FF) % 16; sb.append(hexChars[msb]); sb.append(hexChars[lsb]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { return null; } }
Code Sample 2:
public static byte[] createAuthenticator(ByteBuffer data, String secret) { assert data.isDirect() == false : "must not a direct ByteBuffer"; int pos = data.position(); if (pos < RadiusPacket.MIN_PACKET_LENGTH) { System.err.println("packet too small"); return null; } try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] arr = data.array(); md5.reset(); md5.update(arr, 0, pos); md5.update(secret.getBytes()); return md5.digest(); } catch (NoSuchAlgorithmException nsaex) { throw new RuntimeException("Could not access MD5 algorithm, fatal error"); } }
|
11
|
Code Sample 1:
public void execute() throws BuildException { Project proj = getProject(); if (templateFile == null) throw new BuildException("Template file not set"); if (targetFile == null) throw new BuildException("Target file not set"); try { File template = new File(templateFile); File target = new File(targetFile); if (!template.exists()) throw new BuildException("Template file does not exist " + template.toString()); if (!template.canRead()) throw new BuildException("Cannot read template file: " + template.toString()); if (((!append) && (!overwrite)) && (!target.exists())) throw new BuildException("Target file already exists and append and overwrite are false " + target.toString()); if (VERBOSE) { System.out.println("ProcessTemplate: tmpl in " + template.toString()); System.out.println("ProcessTemplate: file out " + target.toString()); } BufferedReader reader = new BufferedReader(new FileReader(template)); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, append)); parse(reader, writer); writer.flush(); writer.close(); } catch (Exception e) { if (VERBOSE) e.printStackTrace(); throw new BuildException(e); } }
Code Sample 2:
public TapdocContextImpl(Registry registry, FileObject javaDom, List<String> javadocLinks, List<String> libraryLocations, FileObject outputDirectory, List<String> tapdocLinks, DocumentGenerator documentGenerator) { this.registry = registry; this.documentGenerator = documentGenerator; try { if (javaDom == null) { javaDom = outputDirectory.resolveFile("tapdoc-javadom.xml"); } if (!javaDom.exists()) { javaDom.createFile(); javaDom.close(); IOUtils.copy(new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?><tapdoc-javadom></tapdoc-javadom>"), javaDom.getContent().getOutputStream()); } this.javaDom = javaDom; this.javadocLinks = javadocLinks; this.tapdocLinks = tapdocLinks; this.libraryLocations = libraryLocations; this.outputDirectory = outputDirectory; } catch (Exception e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
public File nextEntry() { try { while (hasNext()) { String name = waitingArchEntry.getName(); name = name.substring(name.indexOf("/") + 1); File file = new File(targetDir.getAbsolutePath() + "/" + name); if (waitingArchEntry.isDirectory()) { file.mkdirs(); waitingArchEntry = ais.getNextEntry(); } else { OutputStream os = new FileOutputStream(file); try { IOUtils.copy(ais, os); } finally { IOUtils.closeQuietly(os); } return file; } } } catch (IOException e) { return null; } return null; }
Code Sample 2:
public void jsFunction_extract(ScriptableFile outputFile) throws IOException, FileSystemException, ArchiveException { InputStream is = file.jsFunction_createInputStream(); OutputStream output = outputFile.jsFunction_createOutputStream(); BufferedInputStream buf = new BufferedInputStream(is); ArchiveInputStream input = ScriptableZipArchive.getFactory().createArchiveInputStream(buf); try { long count = 0; while (input.getNextEntry() != null) { if (count == offset) { IOUtils.copy(input, output); break; } count++; } } finally { input.close(); output.close(); is.close(); } }
|
00
|
Code Sample 1:
public void copyFileToFileWithPaths(String sourcePath, String destinPath) throws Exception { BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File file1 = new File(sourcePath); if (file1.exists() && (file1.isFile())) { File file2 = new File(destinPath); if (file2.exists()) { file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(sourcePath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(destinPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); } out.flush(); in.close(); out.close(); } else { throw new Exception("Source file not exist ! sourcePath = (" + sourcePath + ")"); } }
Code Sample 2:
public boolean downloadFile(String webdir, String fileName, String localdir) { boolean result = false; checkDownLoadDirectory(localdir); FTPClient ftp = new FTPClient(); try { ftp.connect(url); ftp.login(username, password); if (!"".equals(webdir.trim())) ftp.changeDirectory(webdir); ftp.download(fileName, new File(localdir + "//" + fileName)); result = true; ftp.disconnect(true); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (FTPIllegalReplyException e) { e.printStackTrace(); } catch (FTPException e) { e.printStackTrace(); } catch (FTPDataTransferException e) { e.printStackTrace(); } catch (FTPAbortedException e) { e.printStackTrace(); } return result; }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public void getZipFiles(String filename) { try { String destinationname = "c:\\mods\\peu\\"; byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; zipinputstream = new ZipInputStream(new FileInputStream(filename)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); System.out.println("entryname " + entryName); int n; FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(destinationname + entryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n); fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
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:
public static void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).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:
private static MapEntry<String, Properties> loadFpmConf() throws ConfigurationReadException { MapEntry<String, Properties> ret = null; Scanner sc = new Scanner(CONF_PATHS).useDelimiter(SEP_P); String prev = ""; while (sc.hasNext() && !hasLoaded) { Properties fpmConf = null; boolean relative = false; String path = sc.next(); if (path.startsWith(PREV_P)) { path = path.replace(PREV_P, prev.substring(0, prev.length() - 1)); } else if (path.startsWith(REL_P)) { path = path.replace(REL_P + FS, ""); relative = true; } else if (path.contains(HOME_P)) { path = path.replace(HOME_P, USER_HOME); } prev = path; path = path.concat(MAIN_CONF_FILE); try { InputStream is = null; if (relative) { is = ClassLoader.getSystemResourceAsStream(path); path = getSystemConfDir(); Strings.getOne().createPath(path); path += MAIN_CONF_FILE; FileOutputStream os = new FileOutputStream(path); IOUtils.copy(is, os); os.flush(); os.close(); os = null; } else { is = new FileInputStream(path); } fpmConf = new Properties(); fpmConf.load(is); if (fpmConf.isEmpty()) { throw new ConfigurationReadException(); } ret = new MapEntry<String, Properties>(path, fpmConf); hasLoaded = true; } catch (FileNotFoundException e) { fpmConf = null; singleton = null; hasLoaded = false; } catch (IOException e) { throw new ConfigurationReadException(); } } return ret; }
Code Sample 2:
protected void createValueListAnnotation(IProgressMonitor monitor, IPackageFragment pack, Map model) throws CoreException { IProject pj = pack.getJavaProject().getProject(); QualifiedName qn = new QualifiedName(JstActivator.PLUGIN_ID, JstActivator.PACKAGE_INFO_LOCATION); String location = pj.getPersistentProperty(qn); if (location != null) { IFolder javaFolder = pj.getFolder(new Path(NexOpenFacetInstallDataModelProvider.WEB_SRC_MAIN_JAVA)); IFolder packageInfo = javaFolder.getFolder(location); if (!packageInfo.exists()) { Logger.log(Logger.INFO, "package-info package [" + location + "] does not exists."); Logger.log(Logger.INFO, "ValueList annotation will not be added by this wizard. " + "You must add manually in your package-info class if exist " + "or create a new one at location " + location); return; } IFile pkginfo = packageInfo.getFile("package-info.java"); if (!pkginfo.exists()) { Logger.log(Logger.INFO, "package-info class at location [" + location + "] does not exists."); return; } InputStream in = pkginfo.getContents(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(in, baos); String content = new String(baos.toByteArray()); VelocityEngine engine = VelocityEngineHolder.getEngine(); model.put("adapterType", getAdapterType()); model.put("packageInfo", location.replace('/', '.')); model.put("defaultNumberPerPage", "5"); model.put("defaultSortDirection", "asc"); if (isFacadeAdapter()) { model.put("facadeType", "true"); } if (content.indexOf("@ValueLists({})") > -1) { appendValueList(monitor, model, pkginfo, content, engine, true); return; } else if (content.indexOf("@ValueLists") > -1) { appendValueList(monitor, model, pkginfo, content, engine, false); return; } String vl = VelocityEngineUtils.mergeTemplateIntoString(engine, "ValueList.vm", model); ByteArrayInputStream bais = new ByteArrayInputStream(vl.getBytes()); try { pkginfo.setContents(bais, true, false, monitor); } finally { bais.close(); } return; } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O exception", e); throw new CoreException(status); } catch (VelocityException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "Velocity exception", e); throw new CoreException(status); } finally { try { baos.close(); in.close(); } catch (IOException e) { } } } Logger.log(Logger.INFO, "package-info location property does not exists."); }
|
11
|
Code Sample 1:
private String fetchCompareContent() throws IOException { URL url = new URL(compareTo); StringWriter sw = new StringWriter(); IOUtils.copy(url.openStream(), sw); return sw.getBuffer().toString(); }
Code Sample 2:
public static void copy(File from, File to, int bufferSize) throws IOException { if (to.exists()) { logger.info("File " + to + " exists, will replace it."); to.delete(); } to.getParentFile().mkdirs(); to.createNewFile(); FileInputStream ois = null; FileOutputStream cos = null; try { ois = new FileInputStream(from); cos = new FileOutputStream(to); byte[] buf = new byte[bufferSize]; int read; while ((read = ois.read(buf, 0, bufferSize)) > 0) { cos.write(buf, 0, read); } cos.flush(); } finally { try { if (ois != null) ois.close(); } catch (IOException ignored) { logger.warn("Could not close file input stream " + from, ignored); } try { if (cos != null) { cos.close(); } } catch (IOException ignored) { logger.warn("Could not close file output stream " + to, ignored); } } }
|
11
|
Code Sample 1:
public void authenticate(final ConnectionHandler ch, final AuthenticationCriteria ac) throws NamingException { byte[] hash = new byte[DIGEST_SIZE]; try { final MessageDigest md = MessageDigest.getInstance(this.passwordScheme); md.update(((String) ac.getCredential()).getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new NamingException(e.getMessage()); } ch.connect(this.config.getBindDn(), this.config.getBindCredential()); NamingEnumeration<SearchResult> en = null; try { en = ch.getLdapContext().search(ac.getDn(), "userPassword={0}", new Object[] { String.format("{%s}%s", this.passwordScheme, LdapUtil.base64Encode(hash)).getBytes() }, LdapConfig.getCompareSearchControls()); if (!en.hasMore()) { throw new AuthenticationException("Compare authentication failed."); } } finally { if (en != null) { en.close(); } } }
Code Sample 2:
protected boolean check(String username, String password, String realm, String nonce, String nc, String cnonce, String qop, String uri, String response, HttpServletRequest request) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update((byte) ':'); md.update(realm.getBytes()); md.update((byte) ':'); md.update(password.getBytes()); byte[] ha1 = md.digest(); md.reset(); md.update(request.getMethod().getBytes()); md.update((byte) ':'); md.update(uri.getBytes()); byte[] ha2 = md.digest(); md.update(TypeUtil.toString(ha1, 16).getBytes()); md.update((byte) ':'); md.update(nonce.getBytes()); md.update((byte) ':'); md.update(nc.getBytes()); md.update((byte) ':'); md.update(cnonce.getBytes()); md.update((byte) ':'); md.update(qop.getBytes()); md.update((byte) ':'); md.update(TypeUtil.toString(ha2, 16).getBytes()); byte[] digest = md.digest(); return response.equals(encode(digest)); } catch (Exception e) { e.printStackTrace(); return false; } }
|
11
|
Code Sample 1:
public void run() throws Exception { logger.debug("#run enter"); logger.debug("#run lineId : " + lineId); logger.debug("#run quantityNew : " + quantityNew); logger.debug("#run priceNew : " + priceNew); ResultSet rs = null; PreparedStatement ps = null; try { connection.setAutoCommit(false); Integer itemId = null; Integer quantity = null; ps = connection.prepareStatement(SQL_SELECT_ORDER_LINE); ps.setInt(1, lineId); rs = ps.executeQuery(); while (rs.next()) { itemId = rs.getInt("ITEM_ID"); quantity = rs.getInt("QUANTITY"); } rs.close(); ps.close(); ps = connection.prepareStatement(SQL_UPDATE_ITEM_BALANCE); ps.setInt(1, quantityNew - quantity); ps.setInt(2, itemId); ps.executeUpdate(); ps = connection.prepareStatement(SQL_UPDATE_ORDER_LINE); ps.setDouble(1, priceNew); ps.setInt(2, quantityNew); ps.setInt(3, lineId); ps.executeUpdate(); ps.close(); ps.close(); connection.commit(); } catch (SQLException ex) { logger.error("SQLException", ex); connection.rollback(); throw new Exception("Не удалось обновить позицию в заказе. Ошибка : " + ex.getMessage()); } finally { connection.setAutoCommit(true); } logger.debug("#run exit"); }
Code Sample 2:
protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException { PreparedStatement preStat = null; StringBuffer sqlStat = new StringBuffer(); DmsRelationalWord tmpDmsRelationalWord = (DmsRelationalWord) ((DmsRelationalWord) obj).clone(); synchronized (dbConn) { try { Integer nextID = getNextPrimaryID(); Timestamp currTime = Utility.getCurrentTimestamp(); sqlStat.append("INSERT "); sqlStat.append("INTO DMS_RELATIONAL_WORD(ID, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE, WORD, PARENT_ID, TYPE) "); sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "); preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); setPrepareStatement(preStat, 1, nextID); setPrepareStatement(preStat, 2, tmpDmsRelationalWord.getRecordStatus()); setPrepareStatement(preStat, 3, new Integer(0)); setPrepareStatement(preStat, 4, tmpDmsRelationalWord.getCreatorID()); setPrepareStatement(preStat, 5, currTime); setPrepareStatement(preStat, 6, tmpDmsRelationalWord.getUpdaterID()); setPrepareStatement(preStat, 7, currTime); if (tmpDmsRelationalWord.getWord() == null || "".equals(tmpDmsRelationalWord.getWord().trim())) { return null; } setPrepareStatement(preStat, 8, tmpDmsRelationalWord.getWord()); setPrepareStatement(preStat, 9, tmpDmsRelationalWord.getParentID()); setPrepareStatement(preStat, 10, tmpDmsRelationalWord.getType()); preStat.executeUpdate(); tmpDmsRelationalWord.setID(nextID); tmpDmsRelationalWord.setCreatorID(tmpDmsRelationalWord.getCreatorID()); tmpDmsRelationalWord.setCreateDate(currTime); tmpDmsRelationalWord.setUpdaterID(tmpDmsRelationalWord.getUpdaterID()); tmpDmsRelationalWord.setUpdateDate(currTime); tmpDmsRelationalWord.setUpdateCount(new Integer(0)); tmpDmsRelationalWord.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getCreatorID())); tmpDmsRelationalWord.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getUpdaterID())); dbConn.commit(); return (tmpDmsRelationalWord); } catch (Exception e) { try { dbConn.rollback(); } catch (Exception ee) { } log.error(e, e); throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } } }
|
11
|
Code Sample 1:
public static boolean copyFileChannel(final File _fileFrom, final File _fileTo, final boolean _append) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(_fileFrom).getChannel(); dstChannel = new FileOutputStream(_fileTo, _append).getChannel(); if (_append) { dstChannel.transferFrom(srcChannel, dstChannel.size(), srcChannel.size()); } else { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } srcChannel.close(); dstChannel.close(); } catch (final IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } try { if (dstChannel != null) { dstChannel.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } } return true; }
Code Sample 2:
public static Object fetchCached(String address, int hours) throws MalformedURLException, IOException { String cacheName = md5(address); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); Date d = new Date(); long limit = d.getTime() - (1000 * 60 * 60 * hours); if (!r.exists() || (hours != -1 && r.lastModified() < limit)) { InputStream is = (InputStream) fetch(address); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); return fis; }
|
00
|
Code Sample 1:
@Override protected void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { res.setHeader("X-Generator", "VisualMon"); String path = req.getPathInfo(); if (null == path || "".equals(path)) res.sendRedirect(req.getServletPath() + "/"); else if ("/chart".equals(path)) { try { res.setHeader("Cache-Control", "private,no-cache,no-store,must-revalidate"); res.addHeader("Cache-Control", "post-check=0,pre-check=0"); res.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); renderChart(req, res); } catch (InterruptedException e) { log.info("Chart generation was interrupted", e); Thread.currentThread().interrupt(); } } else if (path.startsWith("/log_")) { String name = path.substring(5); LogProvider provider = null; for (LogProvider prov : cfg.getLogProviders()) { if (name.equals(prov.getName())) { provider = prov; break; } } if (null == provider) { log.error("Log provider with name \"{}\" not found", name); res.sendError(HttpServletResponse.SC_NOT_FOUND); } else { render(res, provider.getLog(filter.getLocale())); } } else if ("/".equals(path)) { List<LogEntry> logs = new ArrayList<LogEntry>(); for (LogProvider provider : cfg.getLogProviders()) logs.add(new LogEntry(provider.getName(), provider.getTitle(filter.getLocale()))); render(res, new ProbeDataList(filter.getSnapshot(), filter.getAlerts(), logs, ResourceBundle.getBundle("de.frostcode.visualmon.stats", filter.getLocale()).getString("category.empty"), cfg.getDashboardTitle().get(filter.getLocale()))); } else { URL url = Thread.currentThread().getContextClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + req.getPathInfo()); if (null == url) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } res.setDateHeader("Last-Modified", new File(url.getFile()).lastModified()); res.setDateHeader("Expires", new Date().getTime() + YEAR_IN_SECONDS * 1000L); res.setHeader("Cache-Control", "max-age=" + YEAR_IN_SECONDS); URLConnection conn = url.openConnection(); String resourcePath = url.getPath(); String contentType = conn.getContentType(); if (resourcePath.endsWith(".xsl")) { contentType = "text/xml"; res.setCharacterEncoding(ENCODING); } if (contentType == null || "content/unknown".equals(contentType)) { if (resourcePath.endsWith(".css")) contentType = "text/css"; else contentType = getServletContext().getMimeType(resourcePath); } res.setContentType(contentType); res.setContentLength(conn.getContentLength()); OutputStream out = res.getOutputStream(); IOUtils.copy(conn.getInputStream(), out); IOUtils.closeQuietly(conn.getInputStream()); IOUtils.closeQuietly(out); } }
Code Sample 2:
private static void dumpUrl(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { System.out.println(s); s = reader.readLine(); } reader.close(); }
|
11
|
Code Sample 1:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
Code Sample 2:
@Override public void objectToEntry(String object, TupleOutput output) { byte array[] = object.getBytes(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream out = new GZIPOutputStream(baos); ByteArrayInputStream in = new ByteArrayInputStream(array); IOUtils.copyTo(in, out); in.close(); out.close(); byte array2[] = baos.toByteArray(); if (array2.length + 4 < array.length) { output.writeBoolean(true); output.writeInt(array2.length); output.write(array2); } else { output.writeBoolean(false); output.writeString(object); } } catch (IOException err) { throw new RuntimeException(err); } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { FileOutputStream f = new FileOutputStream("test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of Java Zipping"); for (String arg : args) { print("Writing file " + arg); BufferedReader in = new BufferedReader(new FileReader(arg)); zos.putNextEntry(new ZipEntry(arg)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.flush(); } out.close(); print("Checksum: " + csum.getChecksum().getValue()); print("Reading file"); FileInputStream fi = new FileInputStream("test.zip"); CheckedInputStream csumi = new CheckedInputStream(fi, new CRC32()); ZipInputStream in2 = new ZipInputStream(csumi); BufferedInputStream bis = new BufferedInputStream(in2); ZipEntry ze; while ((ze = in2.getNextEntry()) != null) { print("Reading file " + ze); int x; while ((x = bis.read()) != -1) { System.out.write(x); } if (args.length == 1) { print("Checksum: " + csumi.getChecksum().getValue()); } bis.close(); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(sid); 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) { } }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.