label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
protected void handleUrl(URL url) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String s; boolean moreResults = false; while ((s = in.readLine()) != null) { if (s.indexOf("<h1>Search Results</h1>") > -1) { System.err.println("found severals result"); moreResults = true; } else if (s.indexOf("Download <a href=") > -1) { if (s.indexOf("in JCAMP-DX format.") > -1) { System.err.println("download masspec"); super.handleUrl(new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); } moreResults = false; } if (moreResults == true) { if (s.indexOf("<li><a href=\"/cgi/cbook.cgi?ID") > -1) { System.err.println("\tdownloading new url " + new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); this.handleUrl(new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); } } } }
Code Sample 2:
public void getLyricsFromMAWebSite(TrackMABean tb) throws Exception { URL fileURL = new URL("http://www.metal-archives.com/viewlyrics.php?id=" + tb.getMaid()); URLConnection urlConnection = fileURL.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); String ligne; boolean chargerLyrics = false; StringBuffer sb = new StringBuffer(""); String lyrics = null; while ((ligne = br.readLine()) != null) { log.debug("==> " + ligne); if (chargerLyrics && ligne.indexOf("<center>") != -1) { break; } if (chargerLyrics) { sb.append(ligne.trim()); } if (!chargerLyrics && ligne.indexOf("<center>") != -1) { chargerLyrics = true; } } lyrics = sb.toString(); lyrics = lyrics.replaceAll("<br>", "\n").trim(); log.debug("Parole : " + lyrics); tb.setLyrics(lyrics); br.close(); httpStream.close(); }
|
11
|
Code Sample 1:
public InstanceMonitor(String awsAccessId, String awsSecretKey, String bucketName, boolean first) throws IOException { this.awsAccessId = awsAccessId; this.awsSecretKey = awsSecretKey; props = new Properties(); while (true) { try { s3 = new RestS3Service(new AWSCredentials(awsAccessId, awsSecretKey)); bucket = new S3Bucket(bucketName); S3Object obj = s3.getObject(bucket, EW_PROPERTIES); props.load(obj.getDataInputStream()); break; } catch (S3ServiceException ex) { logger.error("problem fetching props from bucket, retrying", ex); try { Thread.sleep(1000); } catch (InterruptedException iex) { } } } URL url = new URL("http://169.254.169.254/latest/meta-data/hostname"); hostname = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/instance-id"); instanceId = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/public-ipv4"); externalIP = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); this.dns = new NetticaAPI(props.getProperty(NETTICA_USER), props.getProperty(NETTICA_PASS)); this.userData = awsAccessId + " " + awsSecretKey + " " + bucketName; this.first = first; logger.info("InstanceMonitor initialized, first=" + first); }
Code Sample 2:
public static String getStringFromAFileAtURL(String anURL) { String htmlCode = "<html><body></body></html>"; try { URL url = new URL(anURL); URLConnection urlConnection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine = ""; htmlCode = ""; while ((inputLine = in.readLine()) != null) htmlCode += inputLine + "\n"; in.close(); } catch (Exception e) { logs.info("URLResolver : lien mort"); JOptionPane.showMessageDialog(null, "lien mort"); return "<html><body></body></html>"; } return checkXMLTagsLowerCase(htmlCode); }
|
00
|
Code Sample 1:
private String getMd5(String base64image) { String token = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(base64image.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); token = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return token; }
Code Sample 2:
@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(); } }
|
00
|
Code Sample 1:
private static String sort(final String item) { final char[] chars = item.toCharArray(); for (int i = 1; i < chars.length; i++) { for (int j = 0; j < chars.length - 1; j++) { if (chars[j] > chars[j + 1]) { final char temp = chars[j]; chars[j] = chars[j + 1]; chars[j + 1] = temp; } } } return String.valueOf(chars); }
Code Sample 2:
static ConversionMap create(String file) { ConversionMap out = new ConversionMap(); URL url = ConversionMap.class.getResource("data/" + file); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { if (line.length() > 0) { String[] arr = line.split("\t"); try { double value = Double.parseDouble(arr[1]); out.put(translate(lowercase(arr[0].getBytes())), value); out.defaultValue += value; out.length = arr[0].length(); } catch (NumberFormatException e) { throw new RuntimeException("Something is wrong with in conversion file: " + e); } } line = in.readLine(); } in.close(); out.defaultValue /= Math.pow(4, out.length); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Their was an error while reading the conversion map: " + e); } return out; }
|
00
|
Code Sample 1:
public InstanceMonitor(String awsAccessId, String awsSecretKey, String bucketName, boolean first) throws IOException { this.awsAccessId = awsAccessId; this.awsSecretKey = awsSecretKey; props = new Properties(); while (true) { try { s3 = new RestS3Service(new AWSCredentials(awsAccessId, awsSecretKey)); bucket = new S3Bucket(bucketName); S3Object obj = s3.getObject(bucket, EW_PROPERTIES); props.load(obj.getDataInputStream()); break; } catch (S3ServiceException ex) { logger.error("problem fetching props from bucket, retrying", ex); try { Thread.sleep(1000); } catch (InterruptedException iex) { } } } URL url = new URL("http://169.254.169.254/latest/meta-data/hostname"); hostname = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/instance-id"); instanceId = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/public-ipv4"); externalIP = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); this.dns = new NetticaAPI(props.getProperty(NETTICA_USER), props.getProperty(NETTICA_PASS)); this.userData = awsAccessId + " " + awsSecretKey + " " + bucketName; this.first = first; logger.info("InstanceMonitor initialized, first=" + first); }
Code Sample 2:
public static void copyFile(String oldPath, String newPath) throws IOException { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); } }
|
00
|
Code Sample 1:
public InputStream getConfResourceAsInputStream(String name) { try { URL url = getResource(name); if (url == null) { LOG.info(name + " not found"); return null; } else { LOG.info("found resource " + name + " at " + url); } return url.openStream(); } catch (Exception e) { return null; } }
Code Sample 2:
private boolean handlePart(Part p) throws MessagingException, GetterException { String filename = p.getFileName(); if (!p.isMimeType("multipart/*")) { String disp = p.getDisposition(); if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (checkCriteria(p)) { if (filename == null) filename = "Attachment" + attnum++; if (result == null) { try { File f = File.createTempFile("amorph_pop3-", ".tmp"); f.deleteOnExit(); OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); InputStream is = p.getInputStream(); int c; while ((c = is.read()) != -1) os.write(c); os.close(); result = new FileInputStream(f); System.out.println("saved attachment to file: " + f.getAbsolutePath()); return true; } catch (IOException ex) { throw new GetterException(ex, "Failed to save attachment: " + ex); } } } } } return false; }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public 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:
private void publishZip(LWMap map) { try { if (map.getFile() == null) { VueUtil.alert(VueResources.getString("dialog.mapsave.message"), VueResources.getString("dialog.mapsave.title")); return; } File savedCMap = PublishUtil.createZip(map, Publisher.resourceVector); InputStream istream = new BufferedInputStream(new FileInputStream(savedCMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(ActionUtil.selectFile("Export to Zip File", "zip"))); int fileLength = (int) savedCMap.length(); byte bytes[] = new byte[fileLength]; while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); istream.close(); ostream.close(); } catch (Exception ex) { System.out.println(ex); VueUtil.alert(VUE.getDialogParent(), VueResources.getString("dialog.export.message") + ex.getMessage(), VueResources.getString("dialog.export.title"), JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } }
Code Sample 2:
public static String CreateHash(String s) { String str = s.toString(); if (str == null || str.length() == 0) { throw new IllegalArgumentException("String cannot be null or empty"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return (hexString.toString()); }
|
11
|
Code Sample 1:
public static boolean copyFile(File src, File dest) throws IOException { if (src == null) { throw new IllegalArgumentException("src == null"); } if (dest == null) { throw new IllegalArgumentException("dest == null"); } if (!src.isFile()) { return false; } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); return true; } catch (IOException e) { throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
Code Sample 2:
public static void copieFichier(File fichier1, File fichier2) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fichier1).getChannel(); out = new FileOutputStream(fichier2).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void copyFile(File source, File dest) { try { FileChannel in = new FileInputStream(source).getChannel(); if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); FileChannel out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static synchronized String toMD5(String str) { Nulls.failIfNull(str, "Cannot create an MD5 encryption form a NULL string"); String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance(MD5); md5.update(str.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); return Strings.padLeft(hashword, 32, "0"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return hashword; }
Code Sample 2:
@Override public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) { throw new NullPointerException(); } ResourceBundle bundle = null; if (format.equals(XML)) { String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, format); URL url = loader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { if (reload) { connection.setUseCaches(false); } InputStream stream = connection.getInputStream(); if (stream != null) { BufferedInputStream bis = new BufferedInputStream(stream); bundle = new XMLResourceBundle(bis); bis.close(); } } } } return bundle; }
|
00
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.B64InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
@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 main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESENC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.encrypt(reader, writer, key, mode); }
Code Sample 2:
public Object execute(ExecutionEvent event) throws ExecutionException { final List<InformationUnit> informationUnitsFromExecutionEvent = InformationHandlerUtil.getInformationUnitsFromExecutionEvent(event); Shell activeShell = HandlerUtil.getActiveShell(event); DirectoryDialog fd = new DirectoryDialog(activeShell, SWT.SAVE); String section = Activator.getDefault().getDialogSettings().get("lastExportSection"); fd.setFilterPath(section); final String open = fd.open(); if (open != null) { Activator.getDefault().getDialogSettings().put("lastExportSection", open); CancelableRunnable runnable = new CancelableRunnable() { @Override protected IStatus runCancelableRunnable(IProgressMonitor monitor) { IStatus returnValue = Status.OK_STATUS; monitor.beginTask(NLS.bind(Messages.SaveFileOnDiskHandler_SavingFiles, open), informationUnitsFromExecutionEvent.size()); for (InformationUnit informationUnit : informationUnitsFromExecutionEvent) { if (!monitor.isCanceled()) { monitor.setTaskName(NLS.bind(Messages.SaveFileOnDiskHandler_Saving, informationUnit.getLabel())); InformationStructureRead read = InformationStructureRead.newSession(informationUnit); read.getValueByNodeId(Activator.FILENAME); IFile binaryReferenceFile = InformationUtil.getBinaryReferenceFile(informationUnit); FileWriter writer = null; try { if (binaryReferenceFile != null) { File file = new File(open, (String) read.getValueByNodeId(Activator.FILENAME)); InputStream contents = binaryReferenceFile.getContents(); writer = new FileWriter(file); IOUtils.copy(contents, writer); monitor.worked(1); } } catch (Exception e) { returnValue = StatusCreator.newStatus(NLS.bind(Messages.SaveFileOnDiskHandler_ErrorSaving, informationUnit.getLabel(), e)); break; } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (IOException e) { } } } } } return returnValue; } }; ProgressMonitorDialog progressMonitorDialog = new ProgressMonitorDialog(activeShell); try { progressMonitorDialog.run(true, true, runnable); } catch (InvocationTargetException e) { if (e.getCause() instanceof CoreException) { ErrorDialog.openError(activeShell, Messages.SaveFileOnDiskHandler_ErrorSaving2, Messages.SaveFileOnDiskHandler_ErrorSaving2, ((CoreException) e.getCause()).getStatus()); } else { ErrorDialog.openError(activeShell, Messages.SaveFileOnDiskHandler_ErrorSaving2, Messages.SaveFileOnDiskHandler_ErrorSaving2, StatusCreator.newStatus(Messages.SaveFileOnDiskHandler_ErrorSaving3, e)); } } catch (InterruptedException e) { } } return null; }
|
00
|
Code Sample 1:
public void encryptPassword() { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.out.print(e); } try { digest.update(passwordIn.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.out.println("cannot find char set for getBytes"); } byte digestBytes[] = digest.digest(); passwordHash = (new BASE64Encoder()).encode(digestBytes); }
Code Sample 2:
private void copy(File src, File dest, String name) { File srcFile = new File(src, name); File destFile = new File(dest, name); if (destFile.exists()) { if (destFile.lastModified() == srcFile.lastModified()) return; destFile.delete(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(srcFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); } catch (IOException e) { } try { if (out != null) out.close(); } catch (IOException e) { } } destFile.setLastModified(srcFile.lastModified()); }
|
00
|
Code Sample 1:
public static void main(String[] args) { URL url = null; EventHeap eh = new EventHeap("iw-room2"); Event newEvent; float chan1 = -1, chan2 = -1; try { url = new URL("http://iw--bluetooth-ap/cgi-bin/sens.cgi"); } catch (MalformedURLException e) { } byte buf[] = new byte[1000]; while (true) { try { InputStream in = url.openStream(); int length = in.read(buf); String page = new String(buf); String data = page.substring(290); if (data.startsWith("No Sensors Found")) { Thread.sleep(1000); } else { String sensorID = data.substring(15, 32); String channel1 = data.substring(163, 167); String channel2 = data.substring(266, 270); if (Float.parseFloat(channel1) != chan1) { System.out.println(sensorID); System.out.println("Channel 1:" + channel1); newEvent = new Event("iStuffInputEvent"); newEvent.addField("Device", "Slider"); newEvent.addField("ID", sensorID + ":channel1"); newEvent.addField("Value", channel1); newEvent.addField("Max", String.valueOf(5)); newEvent.addField("Min", String.valueOf(0)); eh.putEvent(newEvent); chan1 = Float.parseFloat(channel1); } } } catch (Exception e) { e.printStackTrace(); } } }
Code Sample 2:
public boolean addSiteScore(ArrayList<InitScoreTable> siteScores, InitScoreTable scoreTable, String filePath, String strTime) { boolean bResult = false; String strSql = ""; Connection conn = null; Statement stm = null; try { conn = db.getConnection(); conn.setAutoCommit(false); stm = conn.createStatement(); strSql = "delete from t_siteScore where strTaskId = '" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); for (int i = 0; i < siteScores.size(); i++) { InitScoreTable temp = siteScores.get(i); String tempSql = "select * from t_tagConf where strTagName='" + temp.getStrSiteScoreTagName() + "' and strTagYear='" + temp.getStrSiteScoreYear() + "' "; System.out.println(tempSql); ResultSet rst = stm.executeQuery(tempSql); if (rst.next()) { temp.setStrSiteScoreTagId(rst.getString("strId")); temp.setStrSiteinfoScoreParentId(rst.getString("strParentId")); } rst = null; } Iterator<InitScoreTable> it = siteScores.iterator(); String strCreatedTime = com.siteeval.common.Format.getDateTime(); String taskId = ""; while (it.hasNext()) { InitScoreTable thebean = it.next(); taskId = thebean.getStrSiteScoreTaskId(); String strId = UID.getID(); strSql = "INSERT INTO " + strTableName3 + "(strId,strTaskId,strTagId," + "strTagType,strTagName,strParentId,flaTagScore,strYear,datCreatedTime,strCreator) " + "VALUES('" + strId + "','" + taskId + "','" + thebean.getStrSiteScoreTagId() + "','" + thebean.getStrSiteScoreTagType() + "','" + thebean.getStrSiteScoreTagName() + "','" + thebean.getStrSiteinfoScoreParentId() + "','" + thebean.getFlaSiteScoreTagScore() + "','" + thebean.getStrSiteScoreYear() + "','" + strCreatedTime + "','" + thebean.getStrSiteScoreCreator() + "')"; stm.executeUpdate(strSql); } strSql = "update t_siteTotalScore set strSiteState=1,flaSiteScore='" + scoreTable.getFlaSiteScore() + "',flaInfoDisclosureScore='" + scoreTable.getFlaInfoDisclosureScore() + "',flaOnlineServicesScore='" + scoreTable.getFlaOnlineServicesScore() + "',flaPublicParticipationSore='" + scoreTable.getFlaPublicParticipationSore() + "',flaWebDesignScore='" + scoreTable.getFlaWebDesignScore() + "',strSiteFeature='" + scoreTable.getStrTotalScoreSiteFeature() + "',strSiteAdvantage='" + scoreTable.getStrTotalScoreSiteAdvantage() + "',strSiteFailure='" + scoreTable.getStrTotalScoreSiteFailure() + "' where strTaskId='" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); strSql = "update " + strTableName1 + " set templateUrl='" + filePath + "',dTaskBeginTime='" + strTime + "',dTaskEndTime='" + strTime + "' where strid = '" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); conn.commit(); bResult = true; } catch (Exception e) { try { conn.rollback(); } catch (Exception eee) { } System.out.println("������վ���ֱ���Ϣʱ���?"); } finally { try { conn.setAutoCommit(true); if (stm != null) { stm.close(); } if (conn != null) { conn.close(); } } catch (Exception ee) { } } return bResult; }
|
00
|
Code Sample 1:
@Override public MD2Model loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException { boolean baseURLWasNull = setBaseURLFromModelURL(url); MD2Model model = loadModel(url.openStream(), skin); if (baseURLWasNull) { popBaseURL(); } return (model); }
Code Sample 2:
private void fetch() throws IOException { if (getAttachmentUrl() != null && (!getAttachmentUrl().isEmpty())) { InputStream input = null; ByteArrayOutputStream output = null; try { URL url = new URL(getAttachmentUrl()); input = url.openStream(); output = new ByteArrayOutputStream(); int i; while ((i = input.read()) != -1) { output.write(i); } this.data = output.toByteArray(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } } } }
|
11
|
Code Sample 1:
private static void readAndWriteFile(File source, File target) { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
public static void invokeMvnArtifact(final IProject project, final IModuleExtension moduleExtension, final String location) throws CoreException, InterruptedException, IOException { final Properties properties = new Properties(); properties.put("archetypeGroupId", "org.nexopenframework.plugins"); properties.put("archetypeArtifactId", "openfrwk-archetype-webmodule"); final String version = org.maven.ide.eclipse.ext.Maven2Plugin.getArchetypeVersion(); properties.put("archetypeVersion", version); properties.put("artifactId", moduleExtension.getArtifact()); properties.put("groupId", moduleExtension.getGroup()); properties.put("version", moduleExtension.getVersion()); final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating WEB module using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { final String dfPom = getPomFile(moduleExtension.getGroup(), moduleExtension.getArtifact()); final ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); final File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (final IOException e) { } } String goalName = "archetype:create"; boolean offline = false; try { final Class clazz = Thread.currentThread().getContextClassLoader().loadClass("org.maven.ide.eclipse.Maven2Plugin"); final Maven2Plugin plugin = (Maven2Plugin) clazz.getMethod("getDefault", new Class[0]).invoke(null, new Object[0]); offline = plugin.getPreferenceStore().getBoolean("eclipse.m2.offline"); } catch (final ClassNotFoundException e) { Logger.logException("No class [org.maven.ide.eclipse.ext.Maven2Plugin] in classpath", e); } catch (final NoSuchMethodException e) { Logger.logException("No method getDefault", e); } catch (final Throwable e) { Logger.logException(e); } if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } if (!offline) { final IPreferenceStore ps = Maven2Plugin.getDefault().getPreferenceStore(); final String repositories = ps.getString(Maven2PreferenceConstants.P_M2_REPOSITORIES); final String[] repos = repositories.split(org.maven.ide.eclipse.ext.Maven2Plugin.REPO_SEPARATOR); final StringBuffer sbRepos = new StringBuffer(); for (int k = 0; k < repos.length; k++) { sbRepos.append(repos[k]); if (k != repos.length - 1) { sbRepos.append(","); } } properties.put("remoteRepositories", sbRepos.toString()); } workingCopy.setAttribute(ATTR_GOALS, goalName); workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(new NullProgressMonitor(), workingCopy, project, timeout); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), new File(location)); FileUtils.deleteDirectory(new File(location + "/src")); FileUtils.forceDelete(new File(location, "pom.xml")); project.refreshLocal(IResource.DEPTH_INFINITE, null); } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } }
|
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:
public static String encrypt(String plaintext) throws EncryptionException { if (plaintext == null) { throw new EncryptionException(); } try { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); return Base64.encodeBytes(md.digest()); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e); } catch (UnsupportedEncodingException e) { throw new EncryptionException(e); } }
|
11
|
Code Sample 1:
public int procesar() { int mas = 0; String uriOntologia = "", source = "", uri = ""; String fichOrigenHTML = "", fichOrigenLN = ""; String ficheroOutOWL = ""; md5 firma = null; StringTokenV2 entra = null, entra2 = null, entra3 = null; FileInputStream lengNat = null; BufferedInputStream lengNat2 = null; DataInputStream entradaLenguajeNatural = null; FileWriter salOWL = null; BufferedWriter salOWL2 = null; PrintWriter salidaOWL = null; String sujeto = "", verbo = "", CD = "", CI = "", fraseOrigen = ""; StringTokenV2 token2; boolean bandera = false; OntClass c = null; OntClass cBak = null; String claseTrabajo = ""; String nombreClase = "", nombrePropiedad = "", variasPalabras = ""; int incre = 0, emergencia = 0; String lineaSalida = ""; String[] ontologia = new String[5]; ontologia[0] = "http://www.criado.info/owl/vertebrados_es.owl#"; ontologia[1] = "http://www.w3.org/2001/sw/WebOnt/guide-src/wine#"; ontologia[2] = "http://www.co-ode.org/ontologies/pizza/2005/10/18/pizza.owl#"; ontologia[3] = "http://www.w3.org/2001/sw/WebOnt/guide-src/food#"; ontologia[4] = "http://www.daml.org/2001/01/gedcom/gedcom#"; String[] ontologiaSource = new String[5]; ontologiaSource[0] = this.directorioMapeo + "\\" + "mapeo_vertebrados_es.xml"; ontologiaSource[1] = this.directorioMapeo + "\\" + "mapeo_wine_es.xml"; ontologiaSource[2] = this.directorioMapeo + "\\" + "mapeo_pizza_es.xml"; ontologiaSource[3] = this.directorioMapeo + "\\" + "mapeo_food_es.xml"; ontologiaSource[4] = this.directorioMapeo + "\\" + "mapeo_parentesco_es.xml"; mapeoIdiomas clasesOntologias; try { if ((entrada = entradaFichero.readLine()) != null) { if (entrada.trim().length() > 10) { entrada2 = new StringTokenV2(entrada.trim(), "\""); if (entrada2.isIncluidaSubcadena("<fichero ontologia=")) { ontologiaOrigen = entrada2.getToken(2); fichOrigenHTML = entrada2.getToken(4); fichOrigenLN = entrada2.getToken(6); if (ontologiaOrigen.equals("VERTEBRADOS")) { source = ontologiaSource[0]; uriOntologia = ontologia[0]; } if (ontologiaOrigen.equals("WINE")) { source = ontologiaSource[1]; uriOntologia = ontologia[1]; } if (ontologiaOrigen.equals("PIZZA")) { source = ontologiaSource[2]; uriOntologia = ontologia[2]; } if (ontologiaOrigen.equals("FOOD")) { source = ontologiaSource[3]; uriOntologia = ontologia[3]; } if (ontologiaOrigen.equals("PARENTESCOS")) { source = ontologiaSource[4]; uriOntologia = ontologia[4]; } firma = new md5(uriOntologia, false); clasesOntologias = new mapeoIdiomas(source); uri = ""; ficheroOutOWL = ""; entra2 = new StringTokenV2(fichOrigenHTML, "\\"); int numToken = entra2.getNumeroTokenTotales(); entra = new StringTokenV2(fichOrigenHTML, " "); if (entra.isIncluidaSubcadena(directorioLocal)) { entra = new StringTokenV2(entra.getQuitar(directorioLocal) + "", " "); uri = entra.getCambiar("\\", "/"); uri = entra.getQuitar(entra2.getToken(numToken)) + ""; entra3 = new StringTokenV2(entra2.getToken(numToken), "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; uri = urlPatron + uri + ficheroOutOWL; } entra3 = new StringTokenV2(fichOrigenHTML, "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; lineaSalida = "<vistasemantica origen=\"" + fichOrigenLN + "\" destino=\"" + uri + "\" />"; lengNat = new FileInputStream(fichOrigenLN); lengNat2 = new BufferedInputStream(lengNat); entradaLenguajeNatural = new DataInputStream(lengNat2); salOWL = new FileWriter(ficheroOutOWL); salOWL2 = new BufferedWriter(salOWL); salidaOWL = new PrintWriter(salOWL2); while ((entradaInstancias = entradaLenguajeNatural.readLine()) != null) { sujeto = ""; verbo = ""; CD = ""; CI = ""; fraseOrigen = ""; if (entradaInstancias.trim().length() > 10) { entrada2 = new StringTokenV2(entradaInstancias.trim(), "\""); if (entrada2.isIncluidaSubcadena("<oracion sujeto=")) { sujeto = entrada2.getToken(2).trim(); verbo = entrada2.getToken(4).trim(); CD = entrada2.getToken(6).trim(); CI = entrada2.getToken(8).trim(); fraseOrigen = entrada2.getToken(10).trim(); if (sujeto.length() > 0 & verbo.length() > 0 & CD.length() > 0) { bandera = false; c = null; cBak = null; nombreClase = clasesOntologias.getClaseInstancia(CD); if (nombreClase.length() > 0) { bandera = true; } if (bandera) { if (incre == 0) { salidaOWL.write(" <rdf:RDF " + "\n"); salidaOWL.write(" xmlns:j.0=\"" + uriOntologia + "\"" + "\n"); salidaOWL.write(" xmlns:protege=\"http://protege.stanford.edu/plugins/owl/protege#\"" + "\n"); salidaOWL.write(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" + "\n"); salidaOWL.write(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"" + "\n"); salidaOWL.write(" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"" + "\n"); salidaOWL.write(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\" " + "\n"); salidaOWL.write(" xmlns=\"" + uri + "#\"" + "\n"); salidaOWL.write(" xml:base=\"" + uri + "\">" + "\n"); salidaOWL.write(" <owl:Ontology rdf:about=\"\">" + "\n"); salidaOWL.write(" <owl:imports rdf:resource=\"" + uriOntologia + "\"/>" + "\n"); salidaOWL.write(" </owl:Ontology>" + "\n"); salidaOWL.flush(); salida.write(lineaSalida + "\n"); salida.flush(); incre = 1; } salidaOWL.write(" <j.0:" + nombreClase + " rdf:ID=\"" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" <owl:AllDifferent>" + "\n"); salidaOWL.write(" <owl:distinctMembers rdf:parseType=\"Collection\">" + "\n"); salidaOWL.write(" <" + nombreClase + " rdf:about=\"#" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" </owl:distinctMembers>" + "\n"); salidaOWL.write(" </owl:AllDifferent>" + "\n"); salidaOWL.flush(); bandera = false; } } } } } salidaOWL.write(" </rdf:RDF>" + "\n" + "\n"); salidaOWL.write("<!-- Creado por [html2ws] http://www.luis.criado.org -->" + "\n"); salidaOWL.flush(); } } mas = 1; } else { salida.write("</listaVistasSemanticas>\n"); salida.flush(); salida.close(); bw2.close(); fw2.close(); salidaOWL.close(); entradaFichero.close(); ent2.close(); ent1.close(); mas = -1; } } catch (Exception e) { mas = -2; salida.write("No se encuentra: " + fichOrigen + "\n"); salida.flush(); } return mas; }
Code Sample 2:
private void fileCopy(File filename) throws IOException { if (this.stdOut) { this.fileDump(filename); return; } File source_file = new File(spoolPath + "/" + filename); File destination_file = new File(copyPath + "/" + filename); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("no such source file: " + source_file); if (!source_file.canRead()) throw new FileCopyException("source file is unreadable: " + source_file); if (destination_file.exists()) { if (destination_file.isFile()) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); if (!destination_file.canWrite()) throw new FileCopyException("destination file is unwriteable: " + destination_file); if (!this.overwrite) { System.out.print("File " + destination_file + " already exists. Overwrite? (Y/N): "); System.out.flush(); if (!in.readLine().toUpperCase().equals("Y")) throw new FileCopyException("copy cancelled."); } } else throw new FileCopyException("destination is not a file: " + destination_file); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("destination directory doesn't exist: " + destination_file); if (!parentdir.canWrite()) throw new FileCopyException("destination directory is unwriteable: " + destination_file); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while ((bytes_read = source.read(buffer)) != -1) { destination.write(buffer, 0, bytes_read); } System.out.println("File " + filename + " successfull copied to " + destination_file); if (this.keep == false && source_file.isFile()) { try { source.close(); } catch (Exception e) { } if (source_file.delete()) { new File(this.spoolPath + "/info/" + filename + ".desc").delete(); } } } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.flush(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } }
|
11
|
Code Sample 1:
static Object executeMethod(HttpMethod method, int timeout, boolean array) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException { try { method.getParams().setSoTimeout(timeout * 1000); int status = -1; Object result = null; System.out.println("Execute method: " + method.getPath() + " " + method.getQueryString()); TwitterclipseConfig config = TwitterclipsePlugin.getDefault().getTwitterclipseConfiguration(); HttpClient httpClient = HttpClientUtils.createHttpClient(TWITTER_BASE_URL, config.getUserId(), config.getPassword()); status = httpClient.executeMethod(method); System.out.println("Received response. status = " + status); if (status == HttpStatus.SC_OK) { InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); String response = new String(baos.toByteArray(), "UTF-8"); System.out.println(response); if (array) result = JSONArray.fromString(response); else result = JSONObject.fromString(response); } else { throw new HttpRequestFailureException(status); } return result; } catch (SocketTimeoutException e) { throw new HttpRequestTimeoutException(e); } finally { method.releaseConnection(); } }
Code Sample 2:
public static boolean writeFileByBinary(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileOutputStream fos = new FileOutputStream(pFile, pAppend); IOUtils.copy(pIs, fos); fos.flush(); fos.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; }
|
00
|
Code Sample 1:
public static void reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, out); writer.setPdfVersion(PdfWriter.VERSION_1_3); writer.setFullCompression(); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STRENGTH128BITS, password, null, securityType); } final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } else if (base_url != null) { document.addTitle(base_url); } final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } else { document.addCreator(IHtmlToPdfTransformer.VERSION); } final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.addProducer(sproducer); } else { document.addProducer(IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer); } document.open(); } PdfImportedPage page; for (int j = 0; j < n; ) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } } document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext(); ) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i).replaceAll("<pagecount>", "" + n); final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } else { reader = new PdfReader(tmp2.getAbsolutePath()); } final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STRENGTH128BITS, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } if (reason != null) { sap.setReason(reason); } if (location != null) { sap.setLocation(location); } stp.close(); oldOut.flush(); } } catch (final Exception e) { throw new CConvertException("ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } finally { try { tmp.delete(); } catch (final Exception ignore) { } try { tmp2.delete(); } catch (final Exception ignore) { } } }
Code Sample 2:
public FlickrObject perform(boolean chkResponse) throws FlickrException { validate(); String data = getRequestData(); OutputStream os = null; InputStream is = null; try { URL url = null; try { url = new URL(m_url); } catch (MalformedURLException mux) { IllegalStateException iax = new IllegalStateException(); iax.initCause(mux); throw iax; } HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); os = con.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(data); osw.flush(); is = con.getInputStream(); return processRespons(is, chkResponse); } catch (FlickrException fx) { throw fx; } catch (IOException iox) { throw new FlickrException(iox); } finally { if (os != null) try { os.close(); } catch (IOException _) { } if (is != null) try { is.close(); } catch (IOException _) { } } }
|
00
|
Code Sample 1:
public boolean refresh() { try { synchronized (text) { stream = (new URL(url)).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } text = sb.toString(); } price = 0; date = null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); return false; } finally { if (stream != null) try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } return true; }
Code Sample 2:
public CopyAllDataToOtherFolderResponse CopyAllDataToOtherFolder(DPWSContext context, CopyAllDataToOtherFolder CopyAllDataInps) throws DPWSException { CopyAllDataToOtherFolderResponse cpyRp = new CopyAllDataToOtherFolderResponseImpl(); int hany = 0; String errorMsg = null; try { if ((rootDir == null) || (rootDir.length() == (-1))) { errorMsg = LocalStorVerify.ISNT_ROOTFLD; } else { String sourceN = CopyAllDataInps.getSourceName(); String targetN = CopyAllDataInps.getTargetName(); if (LocalStorVerify.isValid(sourceN) && LocalStorVerify.isValid(targetN)) { String srcDir = rootDir + File.separator + sourceN; String trgDir = rootDir + File.separator + targetN; if (LocalStorVerify.isLength(srcDir) && LocalStorVerify.isLength(trgDir)) { for (File fs : new File(srcDir).listFiles()) { File ft = new File(trgDir + '\\' + fs.getName()); FileChannel in = null, out = null; try { in = new FileInputStream(fs).getChannel(); out = new FileOutputStream(ft).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); hany++; } } } else { errorMsg = LocalStorVerify.FLD_TOOLNG; } } else { errorMsg = LocalStorVerify.ISNT_VALID; } } } catch (Throwable tr) { tr.printStackTrace(); errorMsg = tr.getMessage(); hany = (-1); } if (errorMsg != null) { } cpyRp.setNum(hany); return cpyRp; }
|
00
|
Code Sample 1:
public GridDirectoryList(URL url) throws McIDASException { try { urlc = (AddeURLConnection) url.openConnection(); inputStream = new DataInputStream(new BufferedInputStream(urlc.getInputStream())); } catch (IOException e) { throw new McIDASException("Error opening URL for grids:" + e); } readDirectory(); }
Code Sample 2:
private ArrayList loadResults(String text, String index, int from) { loadingMore = true; JSONObject job = new JSONObject(); ArrayList al = new ArrayList(); try { String req = job.put("OperationId", "2").toString(); InputStream is = null; String result = ""; JSONObject jArray = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.1.4:8080/newgenlibctxt/CarbonServlet"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("OperationId", "2")); nameValuePairs.add(new BasicNameValuePair("Text", text)); nameValuePairs.add(new BasicNameValuePair("Index", index)); nameValuePairs.add(new BasicNameValuePair("From", from + "")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } try { JSONObject jobres = new JSONObject(result); JSONArray jarr = jobres.getJSONArray("Records"); for (int i = 0; i < jarr.length(); i++) { String title = jarr.getJSONObject(i).getString("title"); String author = jarr.getJSONObject(i).getString("author"); String[] id = new String[2]; id[0] = jarr.getJSONObject(i).getString("cataloguerecordid"); id[1] = jarr.getJSONObject(i).getString("ownerlibraryid"); alOnlyIds.add(id); al.add(Html.fromHtml("<html><body><b>" + title + "</b><br>by " + author + "</body></html>")); } } catch (JSONException e) { e.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(); } loadingMore = false; return al; }
|
00
|
Code Sample 1:
public void run() { Thread.currentThread().setName("zhongwen.com watcher"); String url = getURL(); try { while (m_shouldBeRunning) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "ISO8859_1")); String line; Vector chatLines = new Vector(); boolean startGrabbing = false; while ((line = reader.readLine()) != null) { if (line.indexOf("</style>") >= 0) { startGrabbing = true; } else if (startGrabbing) { if (line.equals(m_mostRecentKnownLine)) { break; } chatLines.addElement(line); } } reader.close(); for (int i = chatLines.size() - 1; i >= 0; --i) { String chatLine = (String) chatLines.elementAt(i); m_mostRecentKnownLine = chatLine; if (chatLine.indexOf(":") >= 0) { String from = chatLine.substring(0, chatLine.indexOf(":")); String message = stripTags(chatLine.substring(chatLine.indexOf(":"))); m_source.pushMessage(new ZhongWenMessage(m_source, from, message)); } else { m_source.pushMessage(new ZhongWenMessage(m_source, null, stripTags(chatLine))); } } Thread.sleep(SLEEP_TIME); } catch (InterruptedIOException e) { } catch (InterruptedException e) { } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RuntimeException e) { m_source.disconnect(); throw e; } catch (Error e) { m_source.disconnect(); throw e; } }
Code Sample 2:
public void xtestURL1() throws Exception { URL url = new URL(IOTest.URL); InputStream inputStream = url.openStream(); OutputStream outputStream = new FileOutputStream("C:/Temp/testURL1.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }
|
00
|
Code Sample 1:
public String getHttpText() { URL url = null; try { url = new URL(getUrl()); } catch (MalformedURLException e) { log.error(e.getMessage()); } StringBuffer sb = new StringBuffer(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(getRequestMethod()); conn.setDoOutput(true); if (getRequestProperty() != null && "".equals(getRequestProperty())) { conn.setRequestProperty("Accept", getRequestProperty()); } PrintWriter out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), getCharset())); out.println(getParam()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), getCharset())); String inputLine; int i = 1; while ((inputLine = in.readLine()) != null) { if (getStartLine() == 0 && getEndLine() == 0) { sb.append(inputLine).append("\n"); } else { if (getEndLine() > 0) { if (i >= getStartLine() && i <= getEndLine()) { sb.append(inputLine).append("\n"); } } else { if (i >= getStartLine()) { sb.append(inputLine).append("\n"); } } } i++; } in.close(); } catch (IOException e) { log.error(e.getMessage()); } finally { if (conn != null) { conn.disconnect(); } } return sb.toString(); }
Code Sample 2:
private void insert(Connection c) throws SQLException { if (m_fromDb) throw new IllegalStateException("The record already exists in the database"); StringBuffer names = new StringBuffer("INSERT INTO ifServices (nodeID,ipAddr,serviceID"); StringBuffer values = new StringBuffer("?,?,?"); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) { values.append(",?"); names.append(",ifIndex"); } if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) { values.append(",?"); names.append(",status"); } if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { values.append(",?"); names.append(",lastGood"); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { values.append(",?"); names.append(",lastFail"); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) { values.append(",?"); names.append(",source"); } if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) { values.append(",?"); names.append(",notify"); } if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) { values.append(",?"); names.append(",qualifier"); } names.append(") VALUES (").append(values).append(')'); if (log().isDebugEnabled()) log().debug("DbIfServiceEntry.insert: SQL insert statment = " + names.toString()); PreparedStatement stmt = null; PreparedStatement delStmt = null; final DBUtils d = new DBUtils(getClass()); try { stmt = c.prepareStatement(names.toString()); d.watch(stmt); names = null; int ndx = 1; stmt.setInt(ndx++, m_nodeId); stmt.setString(ndx++, m_ipAddr.getHostAddress()); stmt.setInt(ndx++, m_serviceId); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) stmt.setInt(ndx++, m_ifIndex); if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) stmt.setString(ndx++, new String(new char[] { m_status })); if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { stmt.setTimestamp(ndx++, m_lastGood); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { stmt.setTimestamp(ndx++, m_lastFail); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) stmt.setString(ndx++, new String(new char[] { m_source })); if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) stmt.setString(ndx++, new String(new char[] { m_notify })); if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) stmt.setString(ndx++, m_qualifier); int rc; try { rc = stmt.executeUpdate(); } catch (SQLException e) { log().warn("ifServices DB insert got exception; will retry after " + "deletion of any existing records for this ifService " + "that are marked for deletion.", e); c.rollback(); String delCmd = "DELETE FROM ifServices WHERE status = 'D' " + "AND nodeid = ? AND ipAddr = ? AND serviceID = ?"; delStmt = c.prepareStatement(delCmd); d.watch(delStmt); delStmt.setInt(1, m_nodeId); delStmt.setString(2, m_ipAddr.getHostAddress()); delStmt.setInt(3, m_serviceId); rc = delStmt.executeUpdate(); rc = stmt.executeUpdate(); } log().debug("insert(): SQL update result = " + rc); } finally { d.cleanUp(); } m_fromDb = true; m_changed = 0; }
|
11
|
Code Sample 1:
private void doProcess(HttpServletRequest request, HttpServletResponse resp) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { Analyzer analyzer = new Analyzer(); ServletContext context = getServletContext(); String xml = context.getRealPath("data\\log.xml"); String xsd = context.getRealPath("data\\log.xsd"); String grs = context.getRealPath("reports\\" + request.getParameter("type") + ".grs"); String pdf = context.getRealPath("html\\report.pdf"); System.out.println("omg: " + request.getParameter("type")); System.out.println("omg: " + request.getParameter("pc")); int pcount = Integer.parseInt(request.getParameter("pc")); String[] params = new String[pcount]; for (int i = 0; i < pcount; i++) { params[i] = request.getParameter("p" + i); } try { analyzer.generateReport(xml, xsd, grs, pdf, params); } catch (Exception e) { e.printStackTrace(); } File file = new File(pdf); byte[] bs = tryLoadFile(pdf); if (bs == null) throw new NullPointerException(); resp.setHeader("Content-Disposition", " filename=\"" + file.getName() + "\";"); resp.setContentLength(bs.length); InputStream is = new ByteArrayInputStream(bs); IOUtils.copy(is, resp.getOutputStream()); }
Code Sample 2:
protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } }
|
00
|
Code Sample 1:
private void handleServerIntroduction(DataPacket serverPacket) { DataPacketIterator iter = serverPacket.getDataPacketIterator(); String version = iter.nextString(); int serverReportedUDPPort = iter.nextUByte2(); _authKey = iter.nextUByte4(); _introKey = iter.nextUByte4(); _clientKey = makeClientKey(_authKey, _introKey); String passwordKey = iter.nextString(); _logger.log(Level.INFO, "Connection to version " + version + " with udp port " + serverReportedUDPPort); DataPacket packet = null; if (initUDPSocketAndStartPacketReader(_tcpSocket.getInetAddress(), serverReportedUDPPort)) { ParameterBuilder builder = new ParameterBuilder(); builder.appendUByte2(_udpSocket.getLocalPort()); builder.appendString(_user); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ignore) { } md5.update(_serverKey.getBytes()); md5.update(passwordKey.getBytes()); md5.update(_password.getBytes()); for (byte b : md5.digest()) { builder.appendByte(b); } packet = new DataPacketImpl(ClientCommandConstants.INTRODUCTION, builder.toParameter()); } else { packet = new DataPacketImpl(ClientCommandConstants.TCP_ONLY); } sendTCPPacket(packet); }
Code Sample 2:
public static boolean saveMap(LWMap map, boolean saveAs, boolean export) { Log.info("saveMap: " + map); GUI.activateWaitCursor(); if (map == null) return false; File file = map.getFile(); int response = -1; if (map.getSaveFileModelVersion() == 0) { final Object[] defaultOrderButtons = { VueResources.getString("saveaction.saveacopy"), VueResources.getString("saveaction.save") }; Object[] messageObject = { map.getLabel() }; response = VueUtil.option(VUE.getDialogParent(), VueResources.getFormatMessage(messageObject, "dialog.saveaction.message"), VueResources.getFormatMessage(messageObject, "dialog.saveaction.title"), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, defaultOrderButtons, VueResources.getString("saveaction.saveacopy")); } if (response == 0) { saveAs = true; } if ((saveAs || file == null) && !export) { file = ActionUtil.selectFile("Save Map", null); } else if (export) { file = ActionUtil.selectFile("Export Map", "export"); } if (file == null) { try { return false; } finally { GUI.clearWaitCursor(); } } try { Log.info("saveMap: target[" + file + "]"); final String name = file.getName().toLowerCase(); if (name.endsWith(".rli.xml")) { new IMSResourceList().convert(map, file); } else if (name.endsWith(".xml") || name.endsWith(".vue")) { ActionUtil.marshallMap(file, map); } else if (name.endsWith(".jpeg") || name.endsWith(".jpg")) ImageConversion.createActiveMapJpeg(file, VueResources.getDouble("imageExportFactor")); else if (name.endsWith(".png")) ImageConversion.createActiveMapPng(file, VueResources.getDouble("imageExportFactor")); else if (name.endsWith(".svg")) SVGConversion.createSVG(file); else if (name.endsWith(".pdf")) { PresentationNotes.createMapAsPDF(file); } else if (name.endsWith(".zip")) { Vector resourceVector = new Vector(); Iterator i = map.getAllDescendents(LWComponent.ChildKind.PROPER).iterator(); while (i.hasNext()) { LWComponent component = (LWComponent) i.next(); System.out.println("Component:" + component + " has resource:" + component.hasResource()); if (component.hasResource() && (component.getResource() instanceof URLResource)) { URLResource resource = (URLResource) component.getResource(); try { if (resource.isLocalFile()) { String spec = resource.getSpec(); System.out.println(resource.getSpec()); Vector row = new Vector(); row.add(new Boolean(true)); row.add(resource); row.add(new Long(file.length())); row.add("Ready"); resourceVector.add(row); } } catch (Exception ex) { System.out.println("Publisher.setLocalResourceVector: Resource " + resource.getSpec() + ex); ex.printStackTrace(); } } } File savedCMap = PublishUtil.createZip(map, resourceVector); InputStream istream = new BufferedInputStream(new FileInputStream(savedCMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(file)); int fileLength = (int) savedCMap.length(); byte bytes[] = new byte[fileLength]; try { while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); } catch (Exception e) { e.printStackTrace(); } finally { istream.close(); ostream.close(); } } else if (name.endsWith(".html")) { HtmlOutputDialog hod = new HtmlOutputDialog(); hod.setVisible(true); if (hod.getReturnVal() > 0) new ImageMap().createImageMap(file, hod.getScale(), hod.getFormat()); } else if (name.endsWith(".rdf")) { edu.tufts.vue.rdf.RDFIndex index = new edu.tufts.vue.rdf.RDFIndex(); String selectionType = VueResources.getString("rdf.export.selection"); if (selectionType.equals("ALL")) { Iterator<LWMap> maps = VUE.getLeftTabbedPane().getAllMaps(); while (maps.hasNext()) { index.index(maps.next()); } } else if (selectionType.equals("ACTIVE")) { index.index(VUE.getActiveMap()); } else { index.index(VUE.getActiveMap()); } FileWriter writer = new FileWriter(file); index.write(writer); writer.close(); } else if (name.endsWith(VueUtil.VueArchiveExtension)) { Archive.writeArchive(map, file); } else { Log.warn("Unknown save type for filename extension: " + name); return false; } Log.debug("Save completed for " + file); if (!VUE.isApplet()) { VueFrame frame = (VueFrame) VUE.getMainWindow(); String title = VUE.getName() + ": " + name; frame.setTitle(title); } if (name.endsWith(".vue")) { RecentlyOpenedFilesManager rofm = RecentlyOpenedFilesManager.getInstance(); rofm.updateRecentlyOpenedFiles(file.getAbsolutePath()); } return true; } catch (Throwable t) { Log.error("Exception attempting to save file " + file + ": " + t); Throwable e = t; if (t.getCause() != null) e = t.getCause(); if (e instanceof java.io.FileNotFoundException) { Log.error("Save Failed: " + e); } else { Log.error("Save failed for \"" + file + "\"; ", e); } if (e != t) Log.error("Exception attempting to save file " + file + ": " + e); VueUtil.alert(String.format(Locale.getDefault(), VueResources.getString("saveaction.savemap.error") + "\"%s\";\n" + VueResources.getString("saveaction.targetfiel") + "\n\n" + VueResources.getString("saveaction.problem"), map.getLabel(), file, Util.formatLines(e.toString(), 80)), "Problem Saving Map"); } finally { GUI.invokeAfterAWT(new Runnable() { public void run() { GUI.clearWaitCursor(); } }); } return false; }
|
00
|
Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public void run() { try { if (FileDenAccount.loginsuccessful) { host = FileDenAccount.username + " | FileDen.com"; } else { host = "FileDen.com"; uploadFailed(); return; } if (file.length() > 1073741824) { JOptionPane.showMessageDialog(neembuuuploader.NeembuuUploader.getInstance(), "<html><b>" + getClass().getSimpleName() + "</b> " + TranslationProvider.get("neembuuuploader.uploaders.maxfilesize") + ": <b>1GB</b></html>", getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE); uploadFailed(); return; } file_ext = file.getName().substring(file.getName().lastIndexOf(".") + 1); String[] unsupported = new String[] { "html", "htm", "php", "php3", "phtml", "htaccess", "htpasswd", "cgi", "pl", "asp", "aspx", "cfm", "exe", "ade", "adp", "bas", "bat", "chm", "cmd", "com", "cpl", "crt", "hlp", "hta", "inf", "ins", "isp", "jse", "lnk", "mdb", "mde", "msc", "msi", "msp", "mst", "pcd", "pif", "reg", "scr", "sct", "shs", "url", "vbe", "vbs", "wsc", "wsf", "wsh", "shb", "js", "vb", "ws", "mdt", "mdw", "mdz", "shb", "scf", "pl", "pm", "dll" }; for (int i = 0; i < unsupported.length; i++) { if (file_ext.equalsIgnoreCase(unsupported[i])) { file_extension_not_supported = true; break; } } if (file_extension_not_supported) { JOptionPane.showMessageDialog(neembuuuploader.NeembuuUploader.getInstance(), "<html><b>" + getClass().getSimpleName() + "</b> " + TranslationProvider.get("neembuuuploader.uploaders.filetypenotsupported") + ": <b>" + file_ext + "</b></html>", getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE); uploadFailed(); return; } status = UploadStatus.INITIALISING; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.fileden.com/upload_old.php"); httppost.setHeader("Cookie", FileDenAccount.getCookies().toString()); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("action", new StringBody("upload")); mpEntity.addPart("upload_to", new StringBody("")); mpEntity.addPart("overwrite_option", new StringBody("overwrite")); mpEntity.addPart("thumbnail_size", new StringBody("small")); mpEntity.addPart("create_img_tags", new StringBody("1")); mpEntity.addPart("file0", new MonitoredFileBody(file, uploadProgress)); httppost.setEntity(mpEntity); NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine()); NULogger.getLogger().info("Now uploading your file into fileden"); status = UploadStatus.UPLOADING; HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); status = UploadStatus.GETTINGLINK; if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } NULogger.getLogger().info(uploadresponse); downloadlink = CommonUploaderTasks.parseResponse(uploadresponse, "'link':'", "'"); NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink); downURL = downloadlink; httpclient.getConnectionManager().shutdown(); uploadFinished(); } catch (Exception e) { Logger.getLogger(RapidShare.class.getName()).log(Level.SEVERE, null, e); uploadFailed(); } }
|
00
|
Code Sample 1:
public void writeFile(String resource, InputStream is) throws IOException { File f = prepareFsReferenceAsFile(resource); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); try { IOUtils.copy(is, bos); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(bos); } }
Code Sample 2:
private static void testTidy() { try { String url = "http://groups.google.com/group/dengues/files"; java.io.InputStream is = new java.net.URL(url).openStream(); org.w3c.dom.Document doc = dengues.system.HTMLWebHelper.parseDOM(is); org.w3c.dom.NodeList list = doc.getElementsByTagName("td"); org.w3c.dom.Element stockTypeElement = null; for (int i = 0; i < list.getLength(); i++) { org.w3c.dom.Node item = list.item(i); String content = dengues.system.HTMLWebHelper.getContent(item); String convert = dengues.system.HTMLWebHelper.convert(content); if (convert.equals("zDevil")) { stockTypeElement = (org.w3c.dom.Element) item.getParentNode().getParentNode(); break; } } if (stockTypeElement != null) { org.w3c.dom.NodeList trList = stockTypeElement.getElementsByTagName("tr"); for (int i = 0; i < trList.getLength(); i++) { org.w3c.dom.NodeList trListChildren = trList.item(i).getChildNodes(); if (trListChildren.getLength() > 2) { org.w3c.dom.Node node_0 = trListChildren.item(0); org.w3c.dom.Node node_1 = trListChildren.item(1); String content = dengues.system.HTMLWebHelper.getContent(node_0); String convert_0 = dengues.system.HTMLWebHelper.convert(content); content = dengues.system.HTMLWebHelper.getContent(node_1); String convert_1 = dengues.system.HTMLWebHelper.convert(content); if (!"".equals(convert_0)) { System.out.println(convert_0 + " => " + convert_1); } } } } is.close(); } catch (java.net.MalformedURLException ex) { ex.printStackTrace(); } catch (java.io.IOException ex) { ex.printStackTrace(); } }
|
00
|
Code Sample 1:
public void updateUserInfo(AuthSession authSession, AuthUserExtendedInfo infoAuth) { log.info("Start update auth"); PreparedStatement ps = null; DatabaseAdapter db = null; try { db = DatabaseAdapter.getInstance(); String sql = "update WM_AUTH_USER " + "set " + "ID_FIRM=?, IS_USE_CURRENT_FIRM=?, " + "ID_HOLDING=?, IS_HOLDING=? " + "WHERE ID_AUTH_USER=? "; ps = db.prepareStatement(sql); if (infoAuth.getAuthInfo().getCompanyId() == null) { ps.setNull(1, Types.INTEGER); ps.setInt(2, 0); } else { ps.setLong(1, infoAuth.getAuthInfo().getCompanyId()); ps.setInt(2, infoAuth.getAuthInfo().isCompany() ? 1 : 0); } if (infoAuth.getAuthInfo().getHoldingId() == null) { ps.setNull(3, Types.INTEGER); ps.setInt(4, 0); } else { ps.setLong(3, infoAuth.getAuthInfo().getHoldingId()); ps.setInt(4, infoAuth.getAuthInfo().isHolding() ? 1 : 0); } ps.setLong(5, infoAuth.getAuthInfo().getAuthUserId()); ps.executeUpdate(); processDeletedRoles(db, infoAuth); processNewRoles(db, infoAuth.getRoles(), infoAuth.getAuthInfo().getAuthUserId()); db.commit(); } catch (Throwable e) { try { if (db != null) db.rollback(); } catch (Exception e001) { } final String es = "Error add user auth"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(db, ps); ps = null; db = null; log.info("End update auth"); } }
Code Sample 2:
public static File copyToLibDirectory(final File file) throws FileNotFoundException, IOException { if (file == null || !file.exists()) { throw new FileNotFoundException(); } File directory = new File("lib/"); File dest = new File(directory, file.getName()); File parent = dest.getParentFile(); while (parent != null && !parent.equals(directory)) { parent = parent.getParentFile(); } if (parent.equals(directory)) { return file; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return dest; }
|
00
|
Code Sample 1:
@Test public void testCopy_inputStreamToOutputStream_IO84() throws Exception { long size = (long) Integer.MAX_VALUE + (long) 1; InputStream in = new NullInputStreamTest(size); OutputStream out = new OutputStream() { @Override public void write(int b) throws IOException { } @Override public void write(byte[] b) throws IOException { } @Override public void write(byte[] b, int off, int len) throws IOException { } }; assertEquals(-1, IOUtils.copy(in, out)); in.close(); assertEquals("copyLarge()", size, IOUtils.copyLarge(in, out)); }
Code Sample 2:
public void insert() throws Exception { Connection con = DbUtil.connectToDb(); PreparedStatement pStmt = null; try { pStmt = con.prepareStatement("INSERT INTO " + Constants.TABLENAME + " (name,phone,address)" + " values(?,?,?)"); con.setAutoCommit(false); pStmt.setString(1, name); pStmt.setString(2, phone); pStmt.setString(3, address); int j = pStmt.executeUpdate(); con.commit(); } catch (Exception ex) { try { con.rollback(); } catch (SQLException sqlex) { sqlex.printStackTrace(System.out); } throw ex; } finally { try { pStmt.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } }
|
00
|
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 static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
|
00
|
Code Sample 1:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String realUrl = "http:/" + request.getPathInfo(); if (request.getQueryString() != null) { realUrl += "?" + request.getQueryString(); } URL url = new URL(realUrl); URLConnection connection = url.openConnection(); HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); } boolean hasContent = false; Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String header = (String) headers.nextElement(); if ("content-type".equals(header.toLowerCase())) hasContent = true; Enumeration values = request.getHeaders(header); while (values.hasMoreElements()) { String value = (String) values.nextElement(); if (value != null) { connection.addRequestProperty(header, value); } } } try { connection.setDoInput(true); if (hasContent) { InputStream proxyRequest = request.getInputStream(); connection.setDoOutput(true); IO.copy(proxyRequest, connection.getOutputStream()); } connection.connect(); } catch (Exception e) { context.log("proxy", e); } InputStream proxyResponse = null; int code = 500; if (http != null) { proxyResponse = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); } if (proxyResponse == null) { try { proxyResponse = connection.getInputStream(); } catch (Exception e) { if (http != null) proxyResponse = http.getErrorStream(); context.log("stream", e); } } int i = 0; String header = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); while (header != null || value != null) { if (header != null && value != null) { response.addHeader(header, value); } ++i; header = connection.getHeaderFieldKey(i); value = connection.getHeaderField(i); } if (proxyResponse != null) { IO.copy(proxyResponse, response.getOutputStream()); } }
Code Sample 2:
@Test public void testClient() throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpHost proxy = new HttpHost("127.0.0.1", 1280, "http"); HttpGet httpget = new HttpGet("http://a.b.c.d/pdn/"); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } InputStream is = response.getEntity().getContent(); readInputStream(is); System.out.println("----------------------------------------"); httpget.abort(); httpclient.getConnectionManager().shutdown(); }
|
00
|
Code Sample 1:
public void fetch(URL url, HTTPMethod method, String payload, WithResponse wr) throws IOException { System.out.println("fetchin' " + url.toString() + " with GAE fetch service"); HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setReadTimeout(10000); connection.setRequestMethod(method.name()); System.out.println(method.name().toString()); connection.setRequestProperty("Connection", "close"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (wr != null) { connection.setDoOutput(true); } connection.connect(); System.out.println(connection.toString()); if (payload != null) { OutputStream out = null; OutputStreamWriter outWriter = null; try { out = connection.getOutputStream(); outWriter = new OutputStreamWriter(out, "UTF-8"); outWriter.write(payload); System.out.println(out.toString()); } finally { close(outWriter); close(out); } } if (wr != null) { InputStream in = null; InputStreamReader reader = null; StringBuilder sb = new StringBuilder(); try { in = connection.getInputStream(); reader = new InputStreamReader(in); BufferedReader bufReader = new BufferedReader(reader); String line; while ((line = bufReader.readLine()) != null) { sb.append(line).append('\n'); } System.out.println(line); } finally { close(reader); close(in); } } } finally { if (connection != null) { connection.disconnect(); } } }
Code Sample 2:
public InputStream getResourceAsStream(String name) { try { URL url = getResource(name); System.out.println("Loading \"" + url + "\"..."); URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setFollowRedirects(true); httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); System.out.println(httpURLConnection.getResponseMessage() + ", " + httpURLConnection.getContentLength() + " bytes" + ", " + new Date(httpURLConnection.getDate()) + ", " + new Date(httpURLConnection.getLastModified())); if (responseCode != HttpURLConnection.HTTP_OK) { return null; } } return urlConnection.getInputStream(); } catch (Exception ex) { ex.printStackTrace(); return null; } }
|
00
|
Code Sample 1:
public static String generateSig(Map<String, String> params, String secret) { SortedSet<String> keys = new TreeSet<String>(params.keySet()); keys.remove(FacebookParam.SIGNATURE.toString()); String str = ""; for (String key : keys) { str += key + "=" + params.get(key); } str += secret; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes("UTF-8")); StringBuilder result = new StringBuilder(); for (byte b : md.digest()) { result.append(Integer.toHexString((b & 0xf0) >>> 4)); result.append(Integer.toHexString(b & 0x0f)); } return result.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
protected static void clearTables() throws SQLException { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); ClearData.clearTables(stmt); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (2, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (3, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (4, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (5, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (6, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (7, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (8, '')"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } }
|
11
|
Code Sample 1:
public static void readFile(FOUserAgent ua, String uri, Writer output, String encoding) throws IOException { InputStream in = getURLInputStream(ua, uri); try { StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, encoding); } finally { IOUtils.closeQuietly(in); } }
Code Sample 2:
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private synchronized void configure() { final Map res = new HashMap(); try { final Enumeration resources = getConfigResources(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); while (resources.hasMoreElements()) { final URL url = (URL) resources.nextElement(); DefaultHandler saxHandler = new DefaultHandler() { private Group group; private StringBuffer tagContent = new StringBuffer(); public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("group".equals(qName)) { group = new Group(attributes.getValue("name")); String minimizeJs = attributes.getValue("minimize"); String minimizeCss = attributes.getValue("minimizeCss"); group.setMinimize(!"false".equals(minimizeJs)); group.setMinimizeCss("true".equals(minimizeCss)); } else if ("js".equals(qName) || "css".equals(qName) || "group-ref".equals(qName)) tagContent.setLength(0); } public void characters(char ch[], int start, int length) throws SAXException { tagContent.append(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { if ("group".equals(qName)) res.put(group.getName(), group); else if ("js".equals(qName)) group.getJsNames().add(tagContent.toString()); else if ("css".equals(qName)) group.getCssNames().add(tagContent.toString()); else if ("group-ref".equals(qName)) { String name = tagContent.toString(); Group subGroup = (Group) res.get(name); if (subGroup == null) throw new RuntimeException("Error parsing " + url.toString() + " <group-ref>" + name + "</group-ref> unknown"); group.getSubgroups().add(subGroup); } } }; try { saxParser.parse(url.openStream(), saxHandler); } catch (Throwable e) { log.warn(e.toString(), e); log.warn("Exception " + e.toString() + " ignored, let's move on.."); } } configurationFilesMaxModificationTime = findMaxConfigModificationTime(); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } this.groups = res; }
|
11
|
Code Sample 1:
private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException, XMLStreamException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); byte[] byteArray = baos.toByteArray(); String resMessage = new String(byteArray, "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + resMessage); return resMessage; }
Code Sample 2:
private void forcedCopy(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(); } } }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { closeQuietly(in); closeQuietly(out); } return success; }
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 void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
Code Sample 2:
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
11
|
Code Sample 1:
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpClientInfo clientInfo = HttpUtil.parseClientInfo((HttpServletRequest) request); if (request.getParameter("_debug_") != null) { StringBuffer buffer = new StringBuffer(); Enumeration iter = request.getHeaderNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); buffer.append(name + "=" + request.getHeader(name)).append("\n"); } buffer.append("\n"); iter = request.getParameterNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); String value = request.getParameter(name); if (!"ISO-8859-1".equalsIgnoreCase(clientInfo.getPreferCharset())) value = new String(value.getBytes("ISO-8859-1"), clientInfo.getPreferCharset()); buffer.append(name).append("=").append(value).append("\n"); } response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(buffer.toString()); return null; } Object resultObj = handleRequest(request); if (resultObj == null) { String requestException = (String) request.getAttribute("XSMP.handleRequest.Exception"); if (requestException != null) response.sendError(500, requestException); else response.setContentLength(0); } else { if (resultObj instanceof DataHandler) { response.setContentType(((DataHandler) resultObj).getContentType()); response.setContentLength(((DataHandler) resultObj).getInputStream().available()); IOUtils.copy(((DataHandler) resultObj).getInputStream(), response.getOutputStream()); } else { String temp = resultObj.toString(); if (temp.startsWith("<") && temp.endsWith(">")) response.setContentType("text/html; charset=" + clientInfo.getPreferCharset()); else response.setContentType("text/plain; charset=" + clientInfo.getPreferCharset()); byte[] buffer = temp.getBytes(clientInfo.getPreferCharset()); response.setContentLength(buffer.length); response.getOutputStream().write(buffer); } } return null; }
Code Sample 2:
private byte[] getBytes(String resource) throws IOException { InputStream is = HttpServletFileDownloadTest.class.getResourceAsStream(resource); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); IOUtils.closeQuietly(is); return out.toByteArray(); }
|
11
|
Code Sample 1:
public static String md(String passwd) { MessageDigest md5 = null; String digest = passwd; try { md5 = MessageDigest.getInstance("MD5"); md5.update(passwd.getBytes()); byte[] digestData = md5.digest(); digest = byteArrayToHex(digestData); } catch (NoSuchAlgorithmException e) { LOG.warn("MD5 not supported. Using plain string as password!"); } catch (Exception e) { LOG.warn("Digest creation failed. Using plain string as password!"); } return digest; }
Code Sample 2:
public String hash(String senha) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(senha.getBytes()); byte[] hashMd5 = md.digest(); for (int i = 0; i < hashMd5.length; i++) result += Integer.toHexString((((hashMd5[i] >> 4) & 0xf) << 4) | (hashMd5[i] & 0xf)); } catch (NoSuchAlgorithmException ex) { Logger.getInstancia().log(TipoLog.ERRO, ex); } return result; }
|
11
|
Code Sample 1:
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(); } } }
Code Sample 2:
public static String compressFile(String fileName) throws IOException { String newFileName = fileName + ".gz"; FileInputStream fis = new FileInputStream(fileName); FileOutputStream fos = new FileOutputStream(newFileName); GZIPOutputStream gzos = new GZIPOutputStream(fos); byte[] buf = new byte[10000]; int bytesRead; while ((bytesRead = fis.read(buf)) > 0) gzos.write(buf, 0, bytesRead); fis.close(); gzos.close(); return newFileName; }
|
00
|
Code Sample 1:
@Before public void setUp() throws Exception { configureSslSocketConnector(); SecurityHandler securityHandler = createBasicAuthenticationSecurityHandler(); HandlerList handlerList = new HandlerList(); handlerList.addHandler(securityHandler); handlerList.addHandler(new AbstractHandler() { @Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); } }); server.addHandler(handlerList); server.start(); }
Code Sample 2:
public RobotList<Percentage> sort_incr_Percentage(RobotList<Percentage> list, String field) { int length = list.size(); Index_value[] distri = new Index_value[length]; for (int i = 0; i < length; i++) { distri[i] = new Index_value(i, list.get(i).percent); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (distri[i].value > distri[i + 1].value) { Index_value a = distri[i]; distri[i] = distri[i + 1]; distri[i + 1] = a; permut = true; } } } while (permut); RobotList<Percentage> sol = new RobotList<Percentage>(Percentage.class); for (int i = 0; i < length; i++) { sol.addLast(new Percentage(distri[i].value)); } return sol; }
|
11
|
Code Sample 1:
public String readTemplateToString(String fileName) { URL url = null; url = classLoader.getResource(fileName); StringBuffer content = new StringBuffer(); if (url == null) { String error = "Template file could not be found: " + fileName; throw new RuntimeException(error); } try { BufferedReader breader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String strLine = ""; while ((strLine = breader.readLine()) != null) { content.append(strLine).append("\n"); } breader.close(); } catch (Exception e) { throw new RuntimeException("Problem while loading file: " + fileName); } return content.toString(); }
Code Sample 2:
public void startElement(String uri, String tag, String qName, org.xml.sax.Attributes attributes) throws SAXException { wabclient.Attributes prop = new wabclient.Attributes(attributes); try { if (tag.equals("window")) { if (prop == null) { System.err.println("window without properties"); return; } int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); Color bgcolor = prop.getValue("bgcolor", Color.white); String caption = prop.getValue("caption", ""); layout = prop.getValue("layout", 0); boolean statusbar = prop.getValue("statusbar", false); if (sheet.opentype == WABSheet.LAYERED) { Point pos = frame.getNextMDIPos(); sheet.setBounds(pos.x, pos.y, 400, 200); sheet.setNormalBounds(new Rectangle(pos.x, pos.y, 400, 200)); } else { sheet.setBounds(x, y, width, height); sheet.setNormalBounds(new Rectangle(x, y, width, height)); } if (sheet.opentype == WABSheet.MAXIMIZED) sheet.setMaximum(true); else sheet.setMaximum(false); sheet.setTitle(caption); frame.addSheetToMenu(caption); sheet.setBackground(bgcolor); if (layout == 1) sheet.getContentPane().setLayout(new FlowLayout()); else if (layout == 2) sheet.getContentPane().setLayout(new BorderLayout()); else sheet.getContentPane().setLayout(null); } else if (tag.equals("menu")) { if (prop == null) { System.err.println("menu without properties"); return; } String id = prop.getValue("id", ""); String label = prop.getValue("label", ""); if ((id != null && id.equals("WINDOW_MENU") || label.equalsIgnoreCase("window"))) { windowMenu = new JMenu(); menu = windowMenu; sheet.setWindowMenu(menu); } else { menu = new JMenu(); } menu.setText(label); sheet.menubar.add(menu); } else if (tag.equals("menuitem")) { if (prop == null) { System.err.println("menuitem without properties"); return; } JMenuItem item; String action = prop.getValue("action", ""); String label = prop.getValue("label", ""); boolean visible = prop.getValue("visible", true); String icon = prop.getValue("icon", ""); if (action.equals("WINDOW_OVERLAPPED")) { item = windowMenuOverlapped = new JMenuItem(); item.setActionCommand("10001"); item.addActionListener(frame); } else if (action.equals("WINDOW_TILE_HORIZONTALLY")) { item = windowMenuTile = new JMenuItem(); item.setActionCommand("10002"); item.addActionListener(frame); } else if (action.equals("WINDOW_TILE_VERTICALLY")) { item = windowMenuArrange = new JMenuItem(); item.setActionCommand("10003"); item.addActionListener(frame); } else { item = new JMenuItem(); item.setActionCommand(action); item.addActionListener((WABClient) global); } item.setText(label); if (!visible) menu.setVisible(false); menu.add(item); if (frame.getToolBar() != null) { if (icon.length() > 0) { try { ImageIcon img = new ImageIcon(new URL(icon)); BufferedImage image = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); Graphics g = image.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 4, 4, 16, 16, (ImageObserver) null); BufferedImage pressed = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); g = pressed.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 5, 5, 16, 16, (ImageObserver) null); g.setColor(new Color(132, 132, 132)); g.drawLine(0, 0, 24, 0); g.drawLine(0, 0, 0, 24); g.setColor(new Color(255, 255, 255)); g.drawLine(24, 24, 24, 0); g.drawLine(24, 24, 0, 24); BufferedImage over = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); g = over.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 4, 4, 16, 16, (ImageObserver) null); g.setColor(new Color(255, 255, 255)); g.drawLine(0, 0, 24, 0); g.drawLine(0, 0, 0, 24); g.setColor(new Color(132, 132, 132)); g.drawLine(24, 24, 24, 0); g.drawLine(24, 24, 0, 24); JButton b = new JButton(new ImageIcon(image)); b.setRolloverEnabled(true); b.setPressedIcon(new ImageIcon(pressed)); b.setRolloverIcon(new ImageIcon(over)); b.setToolTipText(label); b.setActionCommand(action); b.setFocusPainted(false); b.setBorderPainted(false); b.setContentAreaFilled(false); b.setMargin(new Insets(0, 0, 0, 0)); b.addActionListener(sheet); sheet.toolbar.add(b); } catch (Exception e) { } } } } else if (tag.equals("separator")) { menu.addSeparator(); } else if (tag.equals("choice")) { if (prop == null) { System.err.println("choice without properties"); return; } combo = new JComboBox(); list = null; int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); Object constraints = prop.getValue("constraints"); boolean editable = prop.getValue("editable", false); boolean visible = prop.getValue("visible", true); boolean enabled = prop.getValue("enabled", true); combo_text = prop.getValue("text", ""); combo.setBounds(x, y, width, height); combo.setName((String) id); if (editable) { combo.setEditable(editable); combo.setSelectedItem(combo_text); } if (!visible) combo.setVisible(false); if (!enabled) combo.setEnabled(false); if (layout == 0) sheet.getContentPane().add(combo); else sheet.getContentPane().add(combo, constraints); } else if (tag.equals("list")) { if (prop == null) { System.err.println("list without properties"); return; } list = new JList(); combo = null; listdata = new Vector(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); Object constraints = prop.getValue("constraints"); list.setName((String) id); list.setListData(listdata); JScrollPane sp = new JScrollPane(list); sp.setBounds(x, y, width, height); if (layout == 0) sheet.getContentPane().add(sp); else sheet.getContentPane().add(sp, constraints); } else if (tag.equals("option")) { if (prop == null) { System.err.println("choice.option without properties"); return; } String value = prop.getValue("value", ""); String text = prop.getValue("text", ""); if (list != null) listdata.addElement(new ComboOption(text, value)); if (combo != null) { ComboOption co = new ComboOption(text, value); combo.addItem(co); if (combo_text.equals(text.trim())) combo.setSelectedItem(co); } } else if (tag.equals("label")) { if (prop == null) { System.err.println("label without properties"); return; } JLabel label = new JLabel(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); boolean visible = prop.getValue("visible", true); label.setBounds(x, y, width, height); label.setText(text); if (!visible) label.setVisible(false); if (layout == 0) sheet.getContentPane().add(label); else sheet.getContentPane().add(label, constraints); } else if (tag.equals("button")) { if (prop == null) { System.err.println("button without properties"); return; } JButton btn = new JButton(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); String onmouseup = prop.getValue("onmouseup", ""); Object constraints = prop.getValue("constraints"); btn.setBounds(x, y, width, height); btn.setText(text); btn.addActionListener(sheet); btn.setActionCommand(onmouseup); if (layout == 0) sheet.getContentPane().add(btn); else sheet.getContentPane().add(btn, constraints); } else if (tag.equals("radiobutton")) { if (prop == null) { System.err.println("radiobutton without properties"); return; } JRadioButton rb = new JRadioButton(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); String checked = prop.getValue("checked", "false"); rb.setBounds(x, y, width, height); rb.setText(text); rb.setName((String) id); rb.addActionListener(sheet); rb.setSelected(checked.equalsIgnoreCase("true")); if (layout == 0) sheet.getContentPane().add(rb); else sheet.getContentPane().add(rb, constraints); } else if (tag.equals("checkbox")) { if (prop == null) { System.err.println("checkbox without properties"); return; } JCheckBox cb = new JCheckBox(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); String onmouseup = prop.getValue("onmouseup", ""); Object constraints = prop.getValue("constraints"); String checked = prop.getValue("checked", "false"); cb.setBounds(x, y, width, height); cb.setText(text); cb.setName((String) id); cb.setSelected(checked.equalsIgnoreCase("true")); if (layout == 0) sheet.getContentPane().add(cb); else sheet.getContentPane().add(cb, constraints); } else if (tag.equals("image")) { if (prop == null) { System.err.println("image without properties"); return; } JLabel label = new JLabel(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String src = prop.getValue("src", ""); Object constraints = prop.getValue("constraints"); label.setIcon(new ImageIcon(new URL(src))); label.setBounds(x, y, width, height); if (layout == 0) sheet.getContentPane().add(label); else sheet.getContentPane().add(label, constraints); } else if (tag.equals("singlelineedit")) { if (prop == null) { System.err.println("singlelineedit without properties"); return; } String pwd = prop.getValue("password", ""); JTextField sle; if (pwd.equalsIgnoreCase("true")) sle = new JPasswordField(); else sle = new JTextField(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); Object id = prop.getValue("id"); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); sle.setBounds(x, y, width, height); sle.setText(text); sle.setName((String) id); if (layout == 0) sheet.getContentPane().add(sle); else sheet.getContentPane().add(sle, constraints); } else if (tag.equals("treeview")) { if (prop == null) { System.err.println("treeview without properties"); return; } treeview_root = new DefaultMutableTreeNode("root"); treeview = new JTree(treeview_root); Object constraints = prop.getValue("constraints"); sheet.getContentPane().add(new JScrollPane(treeview), constraints); } else if (tag.equals("treeitem")) { if (prop == null) { System.err.println("treeview.treeitem without properties"); return; } String text = prop.getValue("text", ""); String value = prop.getValue("value", ""); DefaultMutableTreeNode node = new DefaultMutableTreeNode(text); treeview_root.add(node); } else if (tag.equals("table")) { if (prop == null) { System.err.println("table without properties"); return; } String id = prop.getValue("id", ""); table = new JTable(); model = new DefaultTableModel() { public boolean isCellEditable(int row, int col) { return false; } }; table.setModel(model); table.setName((String) id); Object constraints = prop.getValue("constraints"); sheet.getContentPane().add(new JScrollPane(table), constraints); rowNumber = 0; columnNumber = 0; headerWidths = new Vector(); } else if (tag.equals("header")) { if (prop == null) { System.err.println("table.header without properties"); return; } String text = prop.getValue("text", ""); int width = prop.getValue("width", 0); headerWidths.addElement(new Integer(width)); model.addColumn(text); } else if (tag.equals("row")) { rowNumber++; columnNumber = 0; model.setRowCount(rowNumber); } else if (tag.equals("column")) { columnNumber++; if (prop == null) { System.err.println("table.column without properties"); return; } String value = prop.getValue("value", ""); model.setValueAt(value, rowNumber - 1, columnNumber - 1); } else if (tag.equals("script")) { sheet.beginScript(); String url = prop.getValue("src"); if (url.length() > 0) { try { BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String buffer; while (true) { buffer = r.readLine(); if (buffer == null) break; sheet.script += buffer + "\n"; } r.close(); sheet.endScript(); } catch (IOException ioe) { System.err.println("[IOError] " + ioe.getMessage()); System.exit(0); } } } else System.err.println("[sheet] unparsed tag: " + tag); } catch (Exception e) { e.printStackTrace(System.err); } }
|
11
|
Code Sample 1:
private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); }
Code Sample 2:
private void copyThemeProviderClass() throws Exception { InputStream is = getClass().getResourceAsStream("/zkthemer/ThemeProvider.class"); if (is == null) throw new RuntimeException("Cannot find ThemeProvider.class"); File outFile = new File(theme.getJarRootFile(), "zkthemer/ThemeProvider.class"); outFile.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(outFile); IOUtils.copy(is, out); out.close(); FileUtils.writeStringToFile(new File(theme.getJarRootFile(), "zkthemer.properties"), "theme=" + theme.getName() + "\r\nfileList=" + fileList.deleteCharAt(fileList.length() - 1).toString()); }
|
00
|
Code Sample 1:
public boolean synch(boolean verbose) { try { this.verbose = verbose; if (verbose) System.out.println(" -- Synchronizing: " + destDir + " to " + urlStr); URLConnection urc = new URL(urlStr + "/" + MANIFEST).openConnection(); InputStream is = urc.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); while (true) { String str = r.readLine(); if (str == null) { break; } dealWith(str); } is.close(); } catch (Exception ex) { System.out.println("Synchronization of " + destDir + " failed."); ex.printStackTrace(); return false; } return true; }
Code Sample 2:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
00
|
Code Sample 1:
public static final void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.apache.org/"); System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); try { System.out.println(reader.readLine()); } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { httpget.abort(); throw ex; } finally { reader.close(); } } }
Code Sample 2:
public void refreshStatus() { if (!enabledDisplay) return; try { String url = getServerFortURL(); BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String data = null; int counter = 0; while ((data = reader.readLine()) != null && counter < 9) { status[counter] = UNKNOWN; if (data.matches(".*_alsius.gif.*")) { status[counter] = ALSIUS; counter++; } if (data.matches(".*_syrtis.gif.*")) { status[counter] = SYRTIS; counter++; } if (data.matches(".*_ignis.gif.*")) { status[counter] = IGNIS; counter++; } } } catch (Exception exc) { for (int i = 0; i < status.length; i++) status[i] = UNKNOWN; } }
|
11
|
Code Sample 1:
@Override public String entryToObject(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } }
Code Sample 2:
private static void copier(FichierElectronique source, FichierElectronique cible) throws IOException { cible.setNom(source.getNom()); cible.setTaille(source.getTaille()); cible.setTypeMime(source.getTypeMime()); cible.setSoumetteur(source.getSoumetteur()); cible.setDateDerniereModification(source.getDateDerniereModification()); cible.setEmprunteur(source.getEmprunteur()); cible.setDateEmprunt(source.getDateEmprunt()); cible.setNumeroVersion(source.getNumeroVersion()); InputStream inputStream = source.getInputStream(); OutputStream outputStream = cible.getOutputStream(); try { IOUtils.copy(inputStream, outputStream); } finally { try { inputStream.close(); } finally { outputStream.close(); } if (source instanceof FichierElectroniqueDefaut) { FichierElectroniqueDefaut fichierElectroniqueTemporaire = (FichierElectroniqueDefaut) source; fichierElectroniqueTemporaire.deleteTemp(); } } }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
@Override public void run() { try { FileChannel in = new FileInputStream(inputfile).getChannel(); long pos = 0; for (int i = 1; i <= noofparts; i++) { FileChannel out = new FileOutputStream(outputfile.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Rozdělovač: Rozděluji část " + i + ".."); in.transferTo(pos, splitsize, out); pos += splitsize; remainingsize -= splitsize; if (remainingsize < splitsize) in.transferTo(pos, remainingsize, out); pb.setValue(100 * i / noofparts); out.close(); } in.close(); if (deleteOnFinish) new File(inputfile + "").delete(); status.setText("Rozdělovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Rozděleno!", "Rozdělovač", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { } }
|
00
|
Code Sample 1:
public String[] fetchAutocomplete(String text) { String[] result = new String[0]; String url = NbBundle.getMessage(MrSwingDataFeed.class, "MrSwingDataFeed.autocomplete.url", text); HttpContext context = new BasicHttpContext(); HttpGet method = new HttpGet(url); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity).split("\n"); EntityUtils.consume(entity); } } catch (Exception ex) { result = new String[0]; } finally { method.abort(); } return result; }
Code Sample 2:
public void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
00
|
Code Sample 1:
private void readURL(URL url) throws IOException { statusLine.setText("Opening " + url.toExternalForm()); URLConnection connection = url.openConnection(); StringBuffer buffer = new StringBuffer(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { buffer.append(line).append('\n'); statusLine.setText("Read " + buffer.length() + " bytes..."); } } finally { if (in != null) in.close(); } String type = connection.getContentType(); if (type == null) type = "text/plain"; statusLine.setText("Content type " + type); content.setContentType(type); content.setText(buffer.toString()); statusLine.setText("Done"); }
Code Sample 2:
public static void copyFile(File source, File destination) throws IOException { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = null; try { fos = new FileOutputStream(destination); FileChannel sourceChannel = fis.getChannel(); FileChannel destinationChannel = fos.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); destinationChannel.close(); sourceChannel.close(); } finally { if (fos != null) fos.close(); fis.close(); } }
|
00
|
Code Sample 1:
public void handler(List<GoldenBoot> gbs, TargetPage target) { try { URL url = new URL(target.getUrl()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; String include = "Top Scorers"; while ((line = reader.readLine()) != null) { if (line.indexOf(include) != -1) { buildGildenBoot(line, gbs); break; } } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
Code Sample 2:
protected HttpResponseImpl makeRequest(final HttpMethod m, final String requestId) { try { HttpResponseImpl ri = new HttpResponseImpl(); ri.setRequestMethod(m); ri.setResponseCode(_client.executeMethod(m)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(m.getResponseBodyAsStream(), bos); ri.setResponseBody(bos.toByteArray()); notifyOfRequestSuccess(requestId, m, ri); return ri; } catch (HttpException ex) { notifyOfRequestFailure(requestId, m, ex); } catch (IOException ex) { notifyOfRequestFailure(requestId, m, ex); } return null; }
|
00
|
Code Sample 1:
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); }
Code Sample 2:
@Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; }
|
00
|
Code Sample 1:
public static void importDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = output + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); createTablesDB(); } else G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); long tiempoInicio = System.currentTimeMillis(); String directoryPath = input + File.separator; File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(input + File.separator + G.imagesName); if (!fileXML.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero XML", "Error", JOptionPane.ERROR_MESSAGE); } else { SAXBuilder builder = new SAXBuilder(false); Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); List<Element> globalLanguages = root.getChild("languages").getChildren("language"); Iterator<Element> langsI = globalLanguages.iterator(); HashMap<String, Integer> languageIDs = new HashMap<String, Integer>(); HashMap<String, Integer> typeIDs = new HashMap<String, Integer>(); Element e; int i = 0; int contTypes = 0; int contImages = 0; while (langsI.hasNext()) { e = langsI.next(); languageIDs.put(e.getText(), i); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO language (id,name) VALUES (?,?)"); stmt.setInt(1, i); stmt.setString(2, e.getText()); stmt.executeUpdate(); stmt.close(); i++; } G.conn.setAutoCommit(false); while (j.hasNext()) { Element image = (Element) j.next(); String id = image.getAttributeValue("id"); List languages = image.getChildren("language"); Iterator k = languages.iterator(); if (exists(list, id)) { String pathSrc = directoryPath.concat(id); String pathDst = output + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = output + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } 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.toString()); } while (k.hasNext()) { Element languageElement = (Element) k.next(); String language = languageElement.getAttributeValue("id"); List words = languageElement.getChildren("word"); Iterator l = words.iterator(); while (l.hasNext()) { Element wordElement = (Element) l.next(); String type = wordElement.getAttributeValue("type"); if (!typeIDs.containsKey(type)) { typeIDs.put(type, contTypes); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO type (id,name) VALUES (?,?)"); stmt.setInt(1, contTypes); stmt.setString(2, type); stmt.executeUpdate(); stmt.close(); contTypes++; } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, wordElement.getText().toLowerCase()); stmt.setInt(2, languageIDs.get(language)); stmt.setInt(3, typeIDs.get(type)); stmt.setString(4, id); stmt.setString(5, id); stmt.executeUpdate(); stmt.close(); if (contImages == 5000) { G.conn.commit(); contImages = 0; } else contImages++; } } } else { } } G.conn.setAutoCommit(true); G.conn.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private List parseUrlGetUids(String url) throws FetchError { List hids = new ArrayList(); try { InputStream is = (new URL(url)).openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String inputLine = ""; Pattern pattern = Pattern.compile("\\<input\\s+type=hidden\\s+name=hid\\s+value=(\\d+)\\s?\\>", Pattern.CASE_INSENSITIVE); while ((inputLine = in.readLine()) != null) { Matcher matcher = pattern.matcher(inputLine); if (matcher.find()) { String id = matcher.group(1); if (!hids.contains(id)) { hids.add(id); } } } } catch (Exception e) { System.out.println(e); throw new FetchError(e); } return hids; }
|
11
|
Code Sample 1:
private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } }
Code Sample 2:
public MemoryTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); }
|
11
|
Code Sample 1:
@Override protected void setUp() throws Exception { this.logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN); File repoFolder = new File("target/repository"); removeRepository(repoFolder); InputStream repoConfigIn = getClass().getResourceAsStream(REPO_CONFIG_FILE); File tempRepoConfigFile = File.createTempFile("repository", "xml"); tempRepoConfigFile.deleteOnExit(); OutputStream tempRepoConfigOut = new FileOutputStream(tempRepoConfigFile); try { IOUtils.copy(repoConfigIn, tempRepoConfigOut); } finally { repoConfigIn.close(); tempRepoConfigOut.close(); } Repository repo = new TransientRepository(tempRepoConfigFile.getAbsolutePath(), "target/repository"); ServerAdapterFactory factory = new ServerAdapterFactory(); RemoteRepository remoteRepo = factory.getRemoteRepository(repo); reg = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); reg.rebind(REMOTE_REPO_NAME, remoteRepo); session = repo.login(new SimpleCredentials(LOGIN, PWD.toCharArray()), WORKSPACE); InputStream nodeTypeDefIn = getClass().getResourceAsStream(MQ_JCR_XML_NODETYPES_FILE); JackrabbitInitializerHelper.setupRepository(session, new InputStreamReader(nodeTypeDefIn), ""); }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final Map<String, String> fileAttr = new HashMap<String, String>(); boolean download = false; String dw = req.getParameter("d"); if (StringUtils.isNotEmpty(dw) && StringUtils.equals(dw, "true")) { download = true; } final ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream(DEFAULT_CONTENT_LENGTH_SIZE); InputStream imageInputStream = null; try { imageInputStream = getImageAsStream(req, fileAttr); IOUtils.copy(imageInputStream, imageOutputStream); resp.setHeader("Cache-Control", "no-store"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType(fileAttr.get("mimetype")); if (download) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileAttr.get("filename") + "\""); } final ServletOutputStream responseOutputStream = resp.getOutputStream(); responseOutputStream.write(imageOutputStream.toByteArray()); responseOutputStream.flush(); responseOutputStream.close(); } catch (Exception e) { e.printStackTrace(); resp.setContentType("text/html"); resp.getWriter().println("<h1>Sorry... cannot find document</h1>"); } finally { IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(imageOutputStream); } }
|
11
|
Code Sample 1:
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType(req.getContentType()); IOUtils.copy(req.getReader(), resp.getWriter()); }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
|
00
|
Code Sample 1:
@Deprecated public static void getAndProcessContents(String videoPageURL, int bufsize, String charset, Closure<String> process) throws IOException { URL url = null; HttpURLConnection connection = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { url = new URL(videoPageURL); connection = (HttpURLConnection) url.openConnection(); is = connection.getInputStream(); isr = new InputStreamReader(is, charset); br = new BufferedReader(isr); for (String line = br.readLine(); line != null; line = br.readLine()) { process.exec(line); } } finally { Closeables.closeQuietly(br); Closeables.closeQuietly(isr); Closeables.closeQuietly(is); HttpUtils.disconnect(connection); } }
Code Sample 2:
private String copyTutorial() throws IOException { File inputFile = new File(getFilenameForOriginalTutorial()); File outputFile = new File(getFilenameForCopiedTutorial()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return getFilenameForCopiedTutorial(); }
|
11
|
Code Sample 1:
private void copyPhoto(final IPhoto photo, final Map.Entry<String, Integer> size) { final File fileIn = new File(storageService.getPhotoPath(photo, storageService.getOriginalDir())); final File fileOut = new File(storageService.getPhotoPath(photo, size.getKey())); InputStream fileInputStream; OutputStream fileOutputStream; try { fileInputStream = new FileInputStream(fileIn); fileOutputStream = new FileOutputStream(fileOut); IOUtils.copy(fileInputStream, fileOutputStream); fileInputStream.close(); fileOutputStream.close(); } catch (final IOException e) { log.error("file io exception", e); return; } }
Code Sample 2:
private void copyEntries() { if (zipFile != null) { Enumeration<? extends ZipEntry> enumerator = zipFile.entries(); while (enumerator.hasMoreElements()) { ZipEntry entry = enumerator.nextElement(); if (!entry.isDirectory() && !toIgnore.contains(normalizePath(entry.getName()))) { ZipEntry originalEntry = new ZipEntry(entry.getName()); try { zipOutput.putNextEntry(originalEntry); IOUtils.copy(getInputStream(entry.getName()), zipOutput); zipOutput.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } } } }
|
11
|
Code Sample 1:
public static void fileCopy(File source, File dest) throws IOException { 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:
private String createDefaultRepoConf() throws IOException { InputStream confIn = getClass().getResourceAsStream(REPO_CONF_PATH); File tempConfFile = File.createTempFile("repository", "xml"); tempConfFile.deleteOnExit(); IOUtils.copy(confIn, new FileOutputStream(tempConfFile)); return tempConfFile.getAbsolutePath(); }
|
11
|
Code Sample 1:
private String generateServiceId(ObjectName mbeanName) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(mbeanName.toString().getBytes()); StringBuffer hexString = new StringBuffer(); byte[] digest = md5.digest(); for (int i = 0; i < digest.length; i++) { hexString.append(Integer.toHexString(0xFF & digest[i])); } return hexString.toString().toUpperCase(); } catch (Exception ex) { RuntimeException runTimeEx = new RuntimeException("Unexpected error during MD5 hash creation, check your JRE"); runTimeEx.initCause(ex); throw runTimeEx; } }
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 (Exception e) { e.printStackTrace(); mDigest = null; } if (mDigest == null) return null; byte[] raw = mDigest.digest(); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(raw); }
|
11
|
Code Sample 1:
public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; boolean ok = true; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; }
Code Sample 2:
public static String sendScripts(Session session) { Channel channel = null; String tempDirectory = ""; Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "Start sendScripts."); try { { channel = session.openChannel("exec"); final String command = "mktemp -d /tmp/scipionXXXXXXXX"; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); tempDirectory = result[1]; tempDirectory = tempDirectory.replaceAll("\n", ""); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + tempDirectory); IOUtils.closeQuietly(in); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream rsyncHelperContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_HELPER_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(rsyncHelperContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream askPassContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_ASKPASS_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(askPassContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } } catch (IOException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } catch (JSchException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "End sendScripts."); return tempDirectory; }
|
11
|
Code Sample 1:
public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
Code Sample 2:
public 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:
private void buildCache() { cache = new HashMap<String, byte[]>(); JarInputStream jis = null; BufferedInputStream bis = null; URL[] urls = getURLs(); for (URL url : urls) { try { if (url.getPath().endsWith(".jar")) { jis = new JarInputStream(url.openStream()); bis = new BufferedInputStream(jis); JarEntry jarEntry = null; while ((jarEntry = jis.getNextJarEntry()) != null) { String name = jarEntry.getName(); if (!jarEntry.isDirectory() && name.toLowerCase().endsWith(".class")) { String className = name.replaceAll("/", ".").substring(0, name.length() - 6); if (isClassLoaderConditonVerified(className)) { ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; try { baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos); int i = -1; while ((i = bis.read()) != -1) { bos.write(i); } bos.flush(); cache.put(className, baos.toByteArray()); } finally { if (baos != null) { try { baos.close(); } catch (IOException ignore) { } } if (bos != null) { try { bos.close(); } catch (IOException ex) { } } } jis.closeEntry(); } } } try { jis.close(); } catch (IOException ignore) { } } else { File file = new File(url.getFile()); buildCacheFromFile(file, null); } } catch (IOException ex) { continue; } } }
Code Sample 2:
private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); }
|
11
|
Code Sample 1:
@Override public void send() { BufferedReader in = null; StringBuffer result = new StringBuffer(); try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { result.append(str); } } catch (ConnectException ce) { logger.error("MockupExecutableCommand excute fail: " + ce.getMessage()); } catch (Exception e) { logger.error("MockupExecutableCommand excute fail: " + e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } }
Code Sample 2:
private static List lookupForImplementations(final Class clazz, final ClassLoader loader, final String[] defaultImplementations, final boolean onlyFirst, final boolean returnInstances) throws ClassNotFoundException { if (clazz == null) { throw new IllegalArgumentException("Argument 'clazz' cannot be null!"); } ClassLoader classLoader = loader; if (classLoader == null) { classLoader = clazz.getClassLoader(); } String interfaceName = clazz.getName(); ArrayList tmp = new ArrayList(); ArrayList toRemove = new ArrayList(); String className = System.getProperty(interfaceName); if (className != null && className.trim().length() > 0) { tmp.add(className.trim()); } Enumeration en = null; try { en = classLoader.getResources("META-INF/services/" + clazz.getName()); } catch (IOException e) { e.printStackTrace(); } while (en != null && en.hasMoreElements()) { URL url = (URL) en.nextElement(); InputStream is = null; try { is = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; do { line = reader.readLine(); boolean remove = false; if (line != null) { if (line.startsWith("#-")) { remove = true; line = line.substring(2); } int pos = line.indexOf('#'); if (pos >= 0) { line = line.substring(0, pos); } line = line.trim(); if (line.length() > 0) { if (remove) { toRemove.add(line); } else { tmp.add(line); } } } } while (line != null); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } if (defaultImplementations != null) { for (int i = 0; i < defaultImplementations.length; i++) { tmp.add(defaultImplementations[i].trim()); } } if (!clazz.isInterface()) { int m = clazz.getModifiers(); if (!Modifier.isAbstract(m) && Modifier.isPublic(m) && !Modifier.isStatic(m)) { tmp.add(interfaceName); } } tmp.removeAll(toRemove); ArrayList res = new ArrayList(); for (Iterator it = tmp.iterator(); it.hasNext(); ) { className = (String) it.next(); try { Class c = Class.forName(className, false, classLoader); if (c != null) { if (clazz.isAssignableFrom(c)) { if (returnInstances) { Object o = null; try { o = c.newInstance(); } catch (Throwable e) { e.printStackTrace(); } if (o != null) { res.add(o); if (onlyFirst) { return res; } } } else { res.add(c); if (onlyFirst) { return res; } } } else { logger.warning("MetaInfLookup: Class '" + className + "' is not a subclass of class : " + interfaceName); } } } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Cannot create implementation of interface: " + interfaceName, e); } } if (res.size() == 0) { throw new ClassNotFoundException("Cannot find any implemnetation of class " + interfaceName); } return res; }
|
00
|
Code Sample 1:
public static String getEncodedHex(String text) { MessageDigest md = null; String encodedString = null; try { md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } Hex hex = new Hex(); encodedString = new String(hex.encode(md.digest())); md.reset(); return encodedString; }
Code Sample 2:
static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; }
|
00
|
Code Sample 1:
public List<String> extractUrlList(String url) throws IOException, XPathExpressionException { LinkedList<String> list = new LinkedList<String>(); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); Tidy tidy = new Tidy(); tidy.setErrout(new NullPrintWriter()); Document doc = tidy.parseDOM(conn.getInputStream(), null); int len = conn.getContentLength(); if (len <= 0) len = 32000; ByteArrayOutputStream bout = new ByteArrayOutputStream(len); PrintStream ps = new PrintStream(bout); tidy.pprint(doc, ps); ps.flush(); String content = bout.toString(); Pattern p = Pattern.compile("(http://[\\w\\\\\\./=&?;-]+)"); Matcher m = p.matcher(content); while (m.find()) { list.add(m.group()); } return list; }
Code Sample 2:
@SuppressWarnings("unchecked") protected void handleRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost) throws ServletException, IOException { HttpClient httpclient = WebReader.getHttpClient(); try { StringBuffer sb = new StringBuffer(); sb.append(targetServer); sb.append(req.getRequestURI()); if (req.getQueryString() != null) { sb.append("?" + req.getQueryString()); } HttpRequestBase targetRequest = null; if (isPost) { HttpPost post = new HttpPost(sb.toString()); Enumeration<String> paramNames = req.getParameterNames(); String paramName = null; List<NameValuePair> params = new ArrayList<NameValuePair>(); while (paramNames.hasMoreElements()) { paramName = paramNames.nextElement(); params.add(new BasicNameValuePair(paramName, req.getParameterValues(paramName)[0])); } post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); targetRequest = post; } else { System.out.println("GET"); HttpGet get = new HttpGet(sb.toString()); targetRequest = get; } HttpResponse targetResponse = httpclient.execute(targetRequest); HttpEntity entity = targetResponse.getEntity(); InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output)); String line = reader.readLine(); while (line != null) { writer.write(line + "\n"); line = reader.readLine(); } reader.close(); writer.close(); } finally { WebReader.returnHttpClient(httpclient); } }
|
11
|
Code Sample 1:
public void markAsCachedHelper(Item item, Date from, Date to, Map<String, Boolean> properties) { if (properties.size() == 0) { return; } Connection conn = null; Iterable<Integer> props = representer.getInternalReps(properties.keySet()); Integer hostIndex = representer.lookUpInternalRep(item.getResolved().getHost()); HashMap<Integer, long[]> periods = new HashMap<Integer, long[]>(); for (Map.Entry<String, Boolean> e : properties.entrySet()) { periods.put(representer.lookUpInternalRep(e.getKey()), new long[] { from.getTime(), to.getTime(), e.getValue() ? 1 : 0 }); } try { conn = getConnection(); conn.setAutoCommit(false); conn.setSavepoint(); PreparedStatement stmt = null; try { stmt = conn.prepareStatement("SELECT MIN(starttime), MAX(endtime), MAX(hasvalues) FROM cachedperiods WHERE " + "id = ? AND host = ? AND prop = ? AND " + "starttime <= ? AND endtime >= ?"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); stmt.setLong(4, to.getTime()); stmt.setLong(5, from.getTime()); for (Map.Entry<Integer, long[]> e1 : periods.entrySet()) { stmt.setInt(3, e1.getKey()); ResultSet rs = stmt.executeQuery(); if (rs.next()) { e1.getValue()[0] = Math.min(rs.getLong(1), e1.getValue()[0]); e1.getValue()[1] = Math.max(rs.getLong(2), e1.getValue()[1]); e1.getValue()[2] = Math.max(rs.getInt(3), e1.getValue()[2]); } StorageUtils.close(rs); } StorageUtils.close(stmt); stmt = conn.prepareStatement("DELETE FROM cachedperiods WHERE " + "id = ? AND host = ? AND " + "starttime <= ? AND endtime >= ? AND " + "prop IN (" + StringUtils.join(props.iterator(), ",") + ")"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); stmt.setLong(3, to.getTime()); stmt.setLong(4, from.getTime()); stmt.executeUpdate(); StorageUtils.close(stmt); stmt = conn.prepareStatement("INSERT INTO cachedperiods (id, host, prop, starttime, endtime, hasvalues) VALUES (?, ?, ?, ?, ?, ?)"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); for (Map.Entry<Integer, long[]> e2 : periods.entrySet()) { stmt.setInt(3, e2.getKey()); stmt.setLong(4, e2.getValue()[0]); stmt.setLong(5, e2.getValue()[1]); stmt.setInt(6, (int) e2.getValue()[2]); stmt.executeUpdate(); } } finally { StorageUtils.close(stmt); } conn.commit(); } catch (SQLException ex) { Logger.getLogger(MetaDataStoragerImpl.class.getName()).log(Level.SEVERE, "Cannot update cachedperiods table.", ex); try { conn.rollback(); } catch (SQLException ex1) { Logger.getLogger(MetaDataStoragerImpl.class.getName()).log(Level.SEVERE, "Could not roll back database, please consult system administrator.", ex1); } } finally { StorageUtils.close(conn); } }
Code Sample 2:
public boolean saveNote(NoteData n) { String query; try { conn.setAutoCommit(false); Statement stmt = null; ResultSet rset = null; stmt = conn.createStatement(); query = "select * from notes where noteid = " + n.getID(); rset = stmt.executeQuery(query); if (rset.next()) { query = "UPDATE notes SET title = '" + escapeCharacters(n.getTitle()) + "', keywords = '" + escapeCharacters(n.getKeywords()) + "' WHERE noteid = " + n.getID(); try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; PreparedStatement pstmt = conn.prepareStatement("UPDATE fielddata SET data = ? WHERE noteid = ? AND fieldid = ?"); try { while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(1, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(1, f.getData()); } pstmt.setInt(2, n.getID()); pstmt.setInt(3, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } query = "DELETE FROM links WHERE (note1id = " + n.getID() + " OR note2id = " + n.getID() + ")"; try { stmt.execute(query); } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> associations = n.getAssociations(); ListIterator<Link> itr = associations.listIterator(); Link association = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?, ?)"); try { while (itr.hasNext()) { association = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, association.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } else { query = "INSERT INTO notes (templateid, title, keywords) VALUES (" + n.getTemplate().getID() + ", '" + escapeCharacters(n.getTitle()) + "', '" + escapeCharacters(n.getKeywords()) + "')"; try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; n.setID(Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()"))); PreparedStatement pstmt; try { pstmt = conn.prepareStatement("INSERT INTO fielddata (noteid, fieldid, data) VALUES (?,?,?)"); while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(3, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(3, f.getData()); } pstmt.setInt(1, n.getID()); pstmt.setInt(2, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> assoc = n.getAssociations(); Iterator<Link> itr = assoc.listIterator(); Link l = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?,?)"); try { while (itr.hasNext()) { l = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, l.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } conn.commit(); conn.setAutoCommit(true); } catch (SQLException ex) { ex.printStackTrace(); return false; } return true; }
|
00
|
Code Sample 1:
public static String upload_file(String sessionid, String localFilePath, String remoteTagPath) { String jsonstring = "If you see this message, there is some problem inside the function:upload_file()"; String srcPath = localFilePath; String uploadUrl = "https://s2.cloud.cm/rpc/json/?session_id=" + sessionid + "&c=Storage&m=upload_file&tag=" + remoteTagPath; String end = "\r\n"; String twoHyphens = "--"; String boundary = "******"; try { URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream()); dos.writeBytes(twoHyphens + boundary + end); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + srcPath.substring(srcPath.lastIndexOf("/") + 1) + "\"" + end); dos.writeBytes(end); FileInputStream fis = new FileInputStream(srcPath); byte[] buffer = new byte[8192]; int count = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writeBytes(end); dos.writeBytes(twoHyphens + boundary + twoHyphens + end); dos.flush(); InputStream is = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); jsonstring = br.readLine(); dos.close(); is.close(); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
Code Sample 2:
public static int my_rename(String source, String dest) { logger.debug("RENAME " + source + " to " + dest); if (source == null || dest == null) return -1; { logger.debug("\tMoving file across file systems."); FileChannel srcChannel = null; FileChannel dstChannel = null; FileLock lock = null; try { srcChannel = new FileInputStream(source).getChannel(); dstChannel = new FileOutputStream(dest).getChannel(); lock = dstChannel.lock(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); dstChannel.force(true); } catch (IOException e) { logger.fatal("Error while copying file '" + source + "' to file '" + dest + "'. " + e.getMessage(), e); return common_h.ERROR; } finally { try { lock.release(); } catch (Throwable t) { logger.fatal("Error releasing file lock - " + dest); } try { srcChannel.close(); } catch (Throwable t) { } try { dstChannel.close(); } catch (Throwable t) { } } } return common_h.OK; }
|
00
|
Code Sample 1:
private InputStream callService(String text) { InputStream in = null; try { URL url = new URL(SERVLET_URL); URLConnection conn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("POST"); httpConn.setDoInput(true); httpConn.setDoOutput(true); httpConn.connect(); DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream()); dataStream.writeBytes(text); dataStream.flush(); dataStream.close(); int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { ex.printStackTrace(); } return in; }
Code Sample 2:
public boolean saveNote(NoteData n) { String query; try { conn.setAutoCommit(false); Statement stmt = null; ResultSet rset = null; stmt = conn.createStatement(); query = "select * from notes where noteid = " + n.getID(); rset = stmt.executeQuery(query); if (rset.next()) { query = "UPDATE notes SET title = '" + escapeCharacters(n.getTitle()) + "', keywords = '" + escapeCharacters(n.getKeywords()) + "' WHERE noteid = " + n.getID(); try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; PreparedStatement pstmt = conn.prepareStatement("UPDATE fielddata SET data = ? WHERE noteid = ? AND fieldid = ?"); try { while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(1, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(1, f.getData()); } pstmt.setInt(2, n.getID()); pstmt.setInt(3, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } query = "DELETE FROM links WHERE (note1id = " + n.getID() + " OR note2id = " + n.getID() + ")"; try { stmt.execute(query); } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> associations = n.getAssociations(); ListIterator<Link> itr = associations.listIterator(); Link association = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?, ?)"); try { while (itr.hasNext()) { association = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, association.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } else { query = "INSERT INTO notes (templateid, title, keywords) VALUES (" + n.getTemplate().getID() + ", '" + escapeCharacters(n.getTitle()) + "', '" + escapeCharacters(n.getKeywords()) + "')"; try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; n.setID(Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()"))); PreparedStatement pstmt; try { pstmt = conn.prepareStatement("INSERT INTO fielddata (noteid, fieldid, data) VALUES (?,?,?)"); while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(3, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(3, f.getData()); } pstmt.setInt(1, n.getID()); pstmt.setInt(2, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> assoc = n.getAssociations(); Iterator<Link> itr = assoc.listIterator(); Link l = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?,?)"); try { while (itr.hasNext()) { l = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, l.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } conn.commit(); conn.setAutoCommit(true); } catch (SQLException ex) { ex.printStackTrace(); return false; } return true; }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public FlashExObj get(String s, int page) { FlashExObj retVal = new FlashExObj(); s = s.replaceAll("[^a-z0-9_]", ""); ArrayList list = new ArrayList(); retVal.list = list; try { String result = null; URL url = new URL("http://www.flashcardexchange.com/flashcards/list/" + URLEncoder.encode(s, "UTF-8") + "?page=" + page); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(false); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String inputLine; int state = 2; StringBuilder sb = new StringBuilder(); while ((inputLine = in.readLine()) != null) { if (state == 0) { int textPos = inputLine.indexOf("Number of Card"); if (textPos >= 0) { state = 1; } } else if (state == 1) { int s1 = inputLine.indexOf(">"); int s2 = inputLine.indexOf("<", 1); if (s1 >= 0 && s1 < s2) { String numOfCardStr = inputLine.substring(s1 + 1, s2); try { } catch (Exception e) { } state = 2; } } else if (state == 2) { int textPos = inputLine.indexOf("tbody class=\"shaded\""); if (textPos >= 0) { state = 3; } } else if (state == 3) { int textPos = inputLine.indexOf("tbody"); if (textPos >= 0) { break; } sb.append(inputLine); sb.append(" "); } } in.close(); Pattern myPattern = Pattern.compile("<td>(.*?)</td>"); Matcher myMatcher = myPattern.matcher(sb); String str; int counter = 0; String buff[] = new String[4]; while (myMatcher.find()) { int tt = counter % 4; buff[tt] = myMatcher.group(1); if (tt == 3) { String toAdd[] = new String[2]; toAdd[0] = buff[1]; toAdd[1] = buff[2]; list.add(toAdd); } counter++; } } catch (Exception e) { e.printStackTrace(); } return retVal; }
|
00
|
Code Sample 1:
private static String[] loadDB(String name) throws IOException { URL url = SpecialConstants.class.getResource(name); if (url == null) throw new FileNotFoundException("file " + name + " not found"); InputStream is = url.openStream(); try { InputStreamReader isr = new InputStreamReader(is, "utf8"); BufferedReader br = new BufferedReader(isr); ArrayList<String> entries = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; line = line.trim(); if (line.length() > 0 && line.charAt(0) != '#') { entries.add(line); } } String[] r = new String[entries.size()]; entries.toArray(r); return r; } finally { is.close(); } }
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); } } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws Exception { HttpGet get = new HttpGet("https://localhost/docs/index.html"); DefaultHttpClient client = new DefaultHttpClient(); ServerConfig config = new ServerConfig(new Properties()); config.setParam("https.keyStoreFile", "test.keystore"); config.setParam("https.keyPassword", "nopassword"); config.setParam("https.keyStoreType", "JKS"); config.setParam("https.protocol", "SSLv3"); SSLContextCreator ssl = new SSLContextCreator(config); SSLContext ctx = ssl.getSSLContext(); SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); Scheme sch = new Scheme("https", 443, socketFactory); client.getConnectionManager().getSchemeRegistry().register(sch); HttpResponse response = client.execute(get); System.out.println(response.getStatusLine().getStatusCode()); }
Code Sample 2:
public static String getMD5(String password) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (byte aB : b) { sb.append((Integer.toHexString((aB & 0xFF) | 0x100)).substring(1, 3)); } return sb.toString(); }
|
00
|
Code Sample 1:
public static String hashMD5(String passw) { String passwHash = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(passw.getBytes()); byte[] result = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { String tmpStr = "0" + Integer.toHexString((0xff & result[i])); sb.append(tmpStr.substring(tmpStr.length() - 2)); } passwHash = sb.toString(); } catch (NoSuchAlgorithmException ecc) { log.error("Errore algoritmo " + ecc); } return passwHash; }
Code Sample 2:
public static void main(String[] args) { try { URL url = new URL("http://www.lineadecodigo.com"); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); } catch (Throwable t) { } String inputLine; String inputText = ""; while ((inputLine = in.readLine()) != null) { inputText = inputText + inputLine; } System.out.println("El contenido de la URL es: " + inputText); in.close(); } catch (MalformedURLException me) { System.out.println("URL erronea"); } catch (IOException ioe) { System.out.println("Error IO"); } }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); String forw = null; try { int maxUploadSize = 50000000; MultipartRequest multi = new MultipartRequest(request, ".", maxUploadSize); String descrizione = multi.getParameter("text"); File myFile = multi.getFile("uploadfile"); String filePath = multi.getOriginalFileName("uploadfile"); String path = "C:\\files\\"; try { FileInputStream inStream = new FileInputStream(myFile); FileOutputStream outStream = new FileOutputStream(path + myFile.getName()); while (inStream.available() > 0) { outStream.write(inStream.read()); } inStream.close(); outStream.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } forw = "../sendDoc.jsp"; request.setAttribute("contentType", context.getMimeType(path + myFile.getName())); request.setAttribute("text", descrizione); request.setAttribute("path", path + myFile.getName()); request.setAttribute("size", Long.toString(myFile.length()) + " Bytes"); RequestDispatcher rd = request.getRequestDispatcher(forw); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
private void deleteProject(String uid, String home, HttpServletRequest request, HttpServletResponse response) throws Exception { String project = request.getParameter("project"); String line; response.setContentType("text/html"); PrintWriter out = response.getWriter(); htmlHeader(out, "Project Status", ""); try { synchronized (Class.forName("com.sun.gep.SunTCP")) { Vector list = new Vector(); String directory = home; Runtime.getRuntime().exec("/usr/bin/rm -rf " + directory + project); FilePermission perm = new FilePermission(directory + SUNTCP_LIST, "read,write,execute"); File listfile = new File(directory + SUNTCP_LIST); BufferedReader read = new BufferedReader(new FileReader(listfile)); while ((line = read.readLine()) != null) { if (!((new StringTokenizer(line, "\t")).nextToken().equals(project))) { list.addElement(line); } } read.close(); if (list.size() > 0) { PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter(listfile))); for (int i = 0; i < list.size(); i++) { write.println((String) list.get(i)); } write.close(); } else { listfile.delete(); } out.println("The project was successfully deleted."); } } catch (Exception e) { out.println("Error accessing this project."); } out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>"); htmlFooter(out); }
Code Sample 2:
protected void copyFile(String from, String to, String workingDirectory) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File f = new File(monitorCallShellScriptUrl.getFile()); String directoryPath = f.getAbsolutePath(); String fileName = from; InputStream in = null; if (directoryPath.indexOf(".jar!") > -1) { URL urlJar = new URL(directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!'))); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); fileName = je.getName(); in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } else { in = new FileInputStream(f); } File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) fos.write(nextChar); fos.flush(); fos.close(); try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
|
11
|
Code Sample 1:
public static void resourceToFile(final String resource, final String filePath) throws IOException { log.debug("Classloader is " + IOCopyUtils.class.getClassLoader()); InputStream in = IOCopyUtils.class.getResourceAsStream(resource); if (in == null) { log.warn("Resource not '" + resource + "' found. Try to prefix with '/'"); in = IOCopyUtils.class.getResourceAsStream("/" + resource); } if (in == null) { throw new IOException("Resource not '" + resource + "' found."); } final File file = new File(filePath); final OutputStream out = FileUtils.openOutputStream(file); final int bytes = IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); log.debug("Copied resource '" + resource + "' to file " + filePath + " (" + bytes + " bytes)"); }
Code Sample 2:
public static void main(String[] args) { if (args.length <= 0) { System.out.println(" *** SQL script generator and executor ***"); System.out.println(" You must specify name of the file with SQL script data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with administrator priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have: '@' before schema to create,"); System.out.println(" '#' before table to create, '&' before table to insert,"); System.out.println(" '$' before trigger (inverse 'FK on delete cascade') to create,"); System.out.println(" '>' before table to drop, '<' before schema to drop."); System.out.println(" Other rows contain parameters of these actions:"); System.out.println(" for & action each parameter is a list of values,"); System.out.println(" for @ -//- is # acrion, for # -//- is column/constraint "); System.out.println(" definition or $ action. $ syntax to delete from table:"); System.out.println(" fullNameOfTable:itsColInWhereClause=matchingColOfThisTable"); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" If you specify 2nd command line argument - file name too -"); System.out.println(" connection will be established but all statements will"); System.out.println(" be saved in that output file and not transmitted to DB"); System.out.println(" If you specify 3nd command line argument - connect_string -"); System.out.println(" connect information will be added to output file"); System.out.println(" in the form 'connect user/password@connect_string'"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; try { for (int i = 0; i < 4; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); SQLScript script = new SQLScript(connection); if (args.length > 1) { writer = new FileWriter(args[1]); if (args.length > 2) writer.write("connect " + info[2] + "/" + info[3] + "@" + args[2] + script.statementTerminator); } try { System.out.println(script.executeScript(reader, writer) + " updates has been performed during script execution"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); System.out.println(" Script execution error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static SOAPMessage call(SOAPMessage request, URL url) throws IOException, SOAPException { URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); request.writeTo(conn.getOutputStream()); MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); return mf.createMessage(null, conn.getInputStream()); }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) { if (!in.exists() || !in.canRead()) { LOGGER.warn("Can't copy file : " + in); return; } if (!out.getParentFile().exists()) { if (!out.getParentFile().mkdirs()) { LOGGER.info("Didn't create parent directories : " + out.getParentFile().getAbsolutePath()); } } if (!out.exists()) { try { out.createNewFile(); } catch (IOException e) { LOGGER.error("Exception creating new file : " + out.getAbsolutePath(), e); } } LOGGER.debug("Copying file : " + in + ", to : " + out); FileChannel inChannel = null; FileChannel outChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(in); inChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(out); outChannel = fileOutputStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (Exception e) { LOGGER.error("Exception copying file : " + in + ", to : " + out, e); } finally { close(fileInputStream); close(fileOutputStream); if (inChannel != null) { try { inChannel.close(); } catch (Exception e) { LOGGER.error("Exception closing input channel : ", e); } } if (outChannel != null) { try { outChannel.close(); } catch (Exception e) { LOGGER.error("Exception closing output channel : ", e); } } } }
Code Sample 2:
public static void copy(File from, File to) { if (from.getAbsolutePath().equals(to.getAbsolutePath())) { return; } FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(from); os = new FileOutputStream(to); int read = -1; byte[] buffer = new byte[10000]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } catch (Exception e) { throw new RuntimeException(); } finally { try { is.close(); } catch (Exception e) { } try { os.close(); } catch (Exception e) { } } }
|
00
|
Code Sample 1:
public void patchFile(final File classFile) { if (!classFile.exists()) { myErrors.add(new FormErrorInfo(null, "Class to bind does not exist: " + myRootContainer.getClassToBind())); return; } FileInputStream fis; try { byte[] patchedData; fis = new FileInputStream(classFile); try { patchedData = patchClass(fis); if (patchedData == null) { return; } } finally { fis.close(); } FileOutputStream fos = new FileOutputStream(classFile); try { fos.write(patchedData); } finally { fos.close(); } } catch (IOException e) { myErrors.add(new FormErrorInfo(null, "Cannot read or write class file " + classFile.getPath() + ": " + e.toString())); } }
Code Sample 2:
public void actionPerformed(ActionEvent e) { String line, days; String oldType, newType; String dept = ""; buttonPressed = true; char first; int caretIndex; int tempIndex; int oldDisplayNum = displayNum; for (int i = 0; i < 10; i++) { if (e.getSource() == imageButtons[i]) { if (rePrintAnswer) printAnswer(); print.setVisible(true); selectTerm.setVisible(true); displayNum = i; textArea2.setCaretPosition(textArea2.getText().length() - 1); caretIndex = textArea2.getText().indexOf("#" + (i + 1)); if (caretIndex != -1) textArea2.setCaretPosition(caretIndex); repaint(); } } if (e.getSource() == print) { if (textArea2.getText().charAt(0) != '#') printAnswer(); String data = textArea2.getText(); int start = data.indexOf("#" + (displayNum + 1)); start = data.indexOf("\n", start); start++; int end = data.indexOf("\n---------", start); data = data.substring(start, end); String tr = ""; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String s = getCodeBase().toString() + "schedule.cgi?term=" + tr + "&data=" + URLEncoder.encode(data); try { AppletContext a = getAppletContext(); URL u = new URL(s); a.showDocument(u, "_blank"); } catch (MalformedURLException rea) { } } if (e.getSource() == webSite) { String tr; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String num = courseNum.getText().toUpperCase(); String s = "http://sis450.berkeley.edu:4200/OSOC/osoc?p_term=" + tr + "&p_deptname=" + URLEncoder.encode(lst.getSelectedItem().toString()) + "&p_course=" + num; try { AppletContext a = getAppletContext(); URL u = new URL(s); a.showDocument(u, "_blank"); } catch (MalformedURLException rea) { } } if (e.getSource() == loadButton) { printSign("Loading..."); String fileName = idField.getText(); fileName = fileName.replace(' ', '_'); String text = readURL(fileName); if (!publicSign.equals("Error loading.")) { textArea1.setText(text); fileName += ".2"; text = readURL(fileName); absorb(text); printAnswer(); for (int i = 0; i < 10; i++) { if (answer[i].gap != -1 && answer[i].gap != 9999 && answer[i].gap != 10000) { imageButtons[i].setVisible(true); } else imageButtons[i].setVisible(false); } if (!imageButtons[0].isVisible()) { print.setVisible(false); selectTerm.setVisible(false); } else { print.setVisible(true); selectTerm.setVisible(true); } printSign("Load complete."); } displayNum = 0; repaint(); } if (e.getSource() == saveButton) { String fileName = idField.getText(); fileName = fileName.replace(' ', '_'); printSign("Saving..."); writeURL(fileName, 1); printSign("Saving......"); fileName += ".2"; writeURL(fileName, 2); printSign("Save complete."); } if (e.getSource() == instructions) { showInstructions(); } if (e.getSource() == net) { drawWarning = false; String inputLine = ""; String text = ""; String out; String urlIn = ""; textArea2.setText("Retrieving Data..."); try { String tr; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String num = courseNum.getText().toUpperCase(); dept = lst.getSelectedItem().toString(); { urlIn = "http://sis450.berkeley.edu:4200/OSOC/osoc?p_term=" + tr + "&p_deptname=" + URLEncoder.encode(dept) + "&p_course=" + num; try { URL url = new URL(getCodeBase().toString() + "getURL.cgi"); URLConnection con = url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); DataOutputStream out2 = new DataOutputStream(con.getOutputStream()); String content = "url=" + URLEncoder.encode(urlIn); out2.writeBytes(content); out2.flush(); DataInputStream in = new DataInputStream(con.getInputStream()); String s; while ((s = in.readLine()) != null) { } in.close(); } catch (IOException err) { } } URL yahoo = new URL(this.getCodeBase(), "classData.txt"); URLConnection yc = yahoo.openConnection(); StringBuffer buf = new StringBuffer(""); DataInputStream in = new DataInputStream(new BufferedInputStream(yc.getInputStream())); while ((inputLine = in.readLine()) != null) { buf.append(inputLine); } text = buf.toString(); in.close(); } catch (IOException errr) { } String inText = (parseData(text, false)); if (inText.equals("-1")) inText = parseData(text, true); if (inText.equals("\n")) { textArea2.append("\nNO DATA FOUND \n(" + urlIn + ")"); } else textArea1.append(inText); repaint(); } badInput = false; if (e.getSource() == button1) { if (t != null && t.isAlive()) { t.stop(); epilogue(); return; } displayNum = 0; textArea2.setCaretPosition(0); for (int i = 0; i < 30; i++) for (int j = 0; j < 20; j++) { matrix[i][j] = new entry(); matrix[i][j].time = new Time[4]; for (int k = 0; k < 4; k++) { matrix[i][j].time[k] = new Time(); matrix[i][j].time[k].from = 0; } } val = new entry[30]; for (int i = 0; i < 30; i++) { val[i] = new entry(); val[i].time = new Time[4]; for (int j = 0; j < 4; j++) { val[i].time[j] = new Time(); val[i].time[j].from = 0; } } oldPercentDone = -5; oldAmountDone = -1 * PRINTINTERVAL; percentDone = 0; amountDone = 0; drawWarning = false; errorMessage = ""; String text1 = textArea1.getText(); if (text1.toUpperCase().indexOf("OR:") == -1) containsOR = false; else containsOR = true; text1 = removeOR(text1.toUpperCase()); StringTokenizer st = new StringTokenizer(text1, "\n"); clss = -1; timeEntry = -1; boolean noTimesListed = false; while (st.hasMoreTokens()) { line = st.nextToken().toString(); if (line.equals("")) break; else first = line.charAt(0); if (first == '0') { badInput = true; repaint(); break; } if (first >= '1' && first <= '9') { noTimesListed = false; timeEntry++; if (timeEntry == 30) { rePrintAnswer = true; textArea2.setText("Error: Exceeded 30 time entries per class."); badInput = true; repaint(); return; } nextTime = -1; StringTokenizer andST = new StringTokenizer(line, ","); while (andST.hasMoreTokens()) { String temp; String entry; int index, fromTime, toTime; nextTime++; if (nextTime == 4) { rePrintAnswer = true; textArea2.setText("Error: Exceeded 4 time intervals per entry!"); badInput = true; repaint(); return; } StringTokenizer timeST = new StringTokenizer(andST.nextToken()); temp = timeST.nextToken().toString(); entry = ""; index = 0; if (temp.equals("")) break; while (temp.charAt(index) != '-') { entry += temp.charAt(index); index++; if (index >= temp.length()) { rePrintAnswer = true; textArea2.setText("Error: There should be no space before hyphens."); badInput = true; repaint(); return; } } try { fromTime = Integer.parseInt(entry); } catch (NumberFormatException re) { rePrintAnswer = true; textArea2.setText("Error: There should be no a/p sign after FROM_TIME."); badInput = true; repaint(); return; } index++; entry = ""; if (index >= temp.length()) { badInput = true; repaint(); rePrintAnswer = true; textArea2.setText("Error: am/pm sign missing??"); return; } while (temp.charAt(index) >= '0' && temp.charAt(index) <= '9') { entry += temp.charAt(index); index++; if (index >= temp.length()) { badInput = true; repaint(); rePrintAnswer = true; textArea2.setText("Error: am/pm sign missing??"); return; } } toTime = Integer.parseInt(entry); if (temp.charAt(index) == 'a' || temp.charAt(index) == 'A') { } else { if (isLesse(fromTime, toTime) && !timeEq(toTime, 1200)) { if (String.valueOf(fromTime).length() == 4 || String.valueOf(fromTime).length() == 3) { fromTime += 1200; } else fromTime += 12; } if (!timeEq(toTime, 1200)) { if (String.valueOf(toTime).length() == 4 || String.valueOf(toTime).length() == 3) { toTime += 1200; } else toTime += 12; } } if (String.valueOf(fromTime).length() == 2 || String.valueOf(fromTime).length() == 1) fromTime *= 100; if (String.valueOf(toTime).length() == 2 || String.valueOf(toTime).length() == 1) toTime *= 100; matrix[timeEntry][clss].time[nextTime].from = fromTime; matrix[timeEntry][clss].time[nextTime].to = toTime; if (timeST.hasMoreTokens()) days = timeST.nextToken().toString(); else { rePrintAnswer = true; textArea2.setText("Error: days not specified?"); badInput = true; repaint(); return; } if (days.equals("")) return; if (days.indexOf("M") != -1 || days.indexOf("m") != -1) matrix[timeEntry][clss].time[nextTime].m = 1; if (days.indexOf("TU") != -1 || days.indexOf("Tu") != -1 || days.indexOf("tu") != -1) matrix[timeEntry][clss].time[nextTime].tu = 1; if (days.indexOf("W") != -1 || days.indexOf("w") != -1) matrix[timeEntry][clss].time[nextTime].w = 1; if (days.indexOf("TH") != -1 || days.indexOf("Th") != -1 || days.indexOf("th") != -1) matrix[timeEntry][clss].time[nextTime].th = 1; if (days.indexOf("F") != -1 || days.indexOf("f") != -1) matrix[timeEntry][clss].time[nextTime].f = 1; } } else { if (noTimesListed) clss--; clss++; if (clss == 20) { rePrintAnswer = true; textArea2.setText("Error: No more than 20 class entries!"); badInput = true; repaint(); return; } timeEntry = -1; line = line.trim(); for (int i = 0; i < 30; i++) matrix[i][clss].name = line; noTimesListed = true; } } for (int i = 0; i < 30; i++) { for (int j = 0; j < 4; j++) { val[i].time[j].from = 0; } } for (int i = 0; i < 10; i++) { beat10[i] = 10000; answer[i].gap = 10000; for (int j = 0; j < 30; j++) answer[i].classes[j].name = ""; } time = 0; calcTotal = 0; int k = 0; calculateTotalPercent(0, "\n"); amountToReach = calcTotal; button1.setLabel("...HALT GENERATION..."); printWarn(); if (t != null && t.isAlive()) t.stop(); t = new Thread(this, "Generator"); t.start(); } }
|
00
|
Code Sample 1:
public void setKey(String key) { MessageDigest md5; byte[] mdKey = new byte[32]; try { md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); byte[] digest = md5.digest(); System.arraycopy(digest, 0, mdKey, 0, 16); System.arraycopy(digest, 0, mdKey, 16, 16); } catch (Exception e) { System.out.println("MD5 not implemented, can't generate key out of string!"); System.exit(1); } setKey(mdKey); }
Code Sample 2:
private Map fetchAdData(String url) throws ClientProtocolException, IOException { String app = "1"; String owner = "tx"; String session = ""; String sdk = "ad1.0"; String version = "txLove1.0"; String timestamp = String.valueOf(System.currentTimeMillis()); String sign = ""; String appSecret = "test"; Map<String, String> protocal = new HashMap<String, String>(); protocal.put(AuthUtils.AUTH_APP, app); protocal.put(AuthUtils.AUTH_OWNER, owner); protocal.put(AuthUtils.AUTH_SESSION, session); protocal.put(AuthUtils.SDK, sdk); protocal.put(AuthUtils.VERSION, version); protocal.put(AuthUtils.TIMESTAMP, timestamp); Map<String, String> parameter = new HashMap<String, String>(); parameter.put("uid", String.valueOf(user.getUserId())); parameter.put("ip", "0"); parameter.put("imsi", imsi); parameter.put("width", "0"); sign = AuthUtils.sign(protocal, parameter, appSecret); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url.toString()); request.setHeader(AuthUtils.AUTH_APP, app); request.setHeader(AuthUtils.AUTH_OWNER, owner); request.setHeader(AuthUtils.AUTH_SESSION, session); request.setHeader(AuthUtils.SDK, sdk); request.setHeader(AuthUtils.VERSION, version); request.setHeader(AuthUtils.TIMESTAMP, timestamp); request.setHeader(AuthUtils.SIGN, sign); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = reader.readLine(); JSONObject object; Map map = new HashMap(); try { System.out.println("##################### line = " + line); object = new JSONObject(line); if (object != null) { System.out.println(object.toString()); map.put("imgAddress", object.getString("imgurl")); map.put("imgUrl", object.getString("url")); return map; } } catch (JSONException e) { e.printStackTrace(); } } return null; }
|
11
|
Code Sample 1:
public static List importSymbols(List symbols) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbols); IDQuoteFilter filter = new YahooIDQuoteFilter(); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line; do { line = bufferedInput.readLine(); if (line != null) { try { IDQuote quote = filter.toIDQuote(line); quote.verify(); quotes.add(quote); } catch (QuoteFormatException e) { } } } while (line != null); bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
Code Sample 2:
public static Cursor load(URL url, String descriptor) { if (url == null) { log.log(Level.WARNING, "Trying to load a cursor with a null url."); return null; } String cursorFile = url.getFile(); BufferedReader reader = null; int lineNumber = 0; try { DirectoryTextureLoader loader; URL cursorUrl; if (cursorFile.endsWith(cursorDescriptorFile)) { cursorUrl = url; Cursor cached = cursorCache.get(url); if (cached != null) return cached; reader = new BufferedReader(new InputStreamReader(url.openStream())); loader = new DirectoryTextureLoader(url, false); } else if (cursorFile.endsWith(cursorArchiveFile)) { loader = new DirectoryTextureLoader(url, true); if (descriptor == null) descriptor = defaultDescriptorFile; cursorUrl = loader.makeUrl(descriptor); Cursor cached = cursorCache.get(url); if (cached != null) return cached; ZipInputStream zis = new ZipInputStream(url.openStream()); ZipEntry entry; boolean found = false; while ((entry = zis.getNextEntry()) != null) { if (descriptor.equals(entry.getName())) { found = true; break; } } if (!found) { throw new IOException("Descriptor file \"" + descriptor + "\" was not found."); } reader = new BufferedReader(new InputStreamReader(zis)); } else { log.log(Level.WARNING, "Invalid cursor fileName \"{0}\".", cursorFile); return null; } Cursor cursor = new Cursor(); cursor.url = cursorUrl; List<Integer> delays = new ArrayList<Integer>(); List<String> frameFileNames = new ArrayList<String>(); Map<String, Texture> textureCache = new HashMap<String, Texture>(); String line; while ((line = reader.readLine()) != null) { lineNumber++; int commentIndex = line.indexOf(commentString); if (commentIndex != -1) { line = line.substring(0, commentIndex); } StringTokenizer tokens = new StringTokenizer(line, delims); if (!tokens.hasMoreTokens()) continue; String prefix = tokens.nextToken(); if (prefix.equals(hotSpotXPrefix)) { cursor.hotSpotOffset.x = Integer.valueOf(tokens.nextToken()); } else if (prefix.equals(hotSpotYPrefix)) { cursor.hotSpotOffset.y = Integer.valueOf(tokens.nextToken()); } else if (prefix.equals(timePrefix)) { delays.add(Integer.valueOf(tokens.nextToken())); if (tokens.nextToken().equals(imagePrefix)) { String file = tokens.nextToken(""); file = file.substring(file.indexOf('=') + 1); file.trim(); frameFileNames.add(file); if (textureCache.get(file) == null) { textureCache.put(file, loader.loadTexture(file)); } } else { throw new NoSuchElementException(); } } } cursor.frameFileNames = frameFileNames.toArray(new String[0]); cursor.textureCache = textureCache; cursor.delays = new int[delays.size()]; cursor.images = new Image[frameFileNames.size()]; cursor.textures = new Texture[frameFileNames.size()]; for (int i = 0; i < cursor.frameFileNames.length; i++) { cursor.textures[i] = textureCache.get(cursor.frameFileNames[i]); cursor.images[i] = cursor.textures[i].getImage(); cursor.delays[i] = delays.get(i); } if (delays.size() == 1) cursor.delays = null; if (cursor.images.length == 0) { log.log(Level.WARNING, "The cursor has no animation frames."); return null; } cursor.width = cursor.images[0].getWidth(); cursor.height = cursor.images[0].getHeight(); cursorCache.put(cursor.url, cursor); return cursor; } catch (MalformedURLException mue) { log.log(Level.WARNING, "Unable to load cursor.", mue); } catch (IOException ioe) { log.log(Level.WARNING, "Unable to load cursor.", ioe); } catch (NumberFormatException nfe) { log.log(Level.WARNING, "Numerical error while parsing the " + "file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } catch (IndexOutOfBoundsException ioobe) { log.log(Level.WARNING, "Error, \"=\" expected in the file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } catch (NoSuchElementException nsee) { log.log(Level.WARNING, "Error while parsing the file \"{0}\" at line {1}", new Object[] { url, lineNumber }); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { log.log(Level.SEVERE, "Unable to close the steam.", ioe); } } } return null; }
|
11
|
Code Sample 1:
@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 { is = request.getInputStream(); fos = new FileOutputStream(new File(targetPath + filename)); IOUtils.copy(is, fos); response.setStatus(HttpServletResponse.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.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:
@Override protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (beforeServingFile(req, resp)) { String pathInfo = req.getPathInfo(); Validate.notNull(pathInfo, "the path info is null -> the sevlet should be mapped with /<mapping>/*"); String resurouce = pathInfo.substring(1); if (log.isDebugEnabled()) { log.debug("resource to expose: " + resurouce); } String extension = resurouce.substring(resurouce.lastIndexOf('.') + 1); MimeType mimeType = MimeTypeRegistry.getByExtension(extension); Validate.notNull(mimeType, "no mimetype found for extension: " + extension); if (log.isDebugEnabled()) { log.debug("the mime type to set: " + mimeType.getMimeType()); } File f = new File(mappedFolder, resurouce); Validate.isTrue(f.exists(), "file: " + f + " does not exist"); Validate.isTrue(f.canRead(), "can not read the file: " + f); if (log.isDebugEnabled()) { log.debug("exposing the file: " + f); } resp.setContentType(mimeType.getMimeType()); FileInputStream fis = new FileInputStream(f); ServletOutputStream os = resp.getOutputStream(); IOUtils.copy(fis, os); os.flush(); IOUtils.closeQuietly(fis); IOUtils.closeQuietly(os); } }
|
00
|
Code Sample 1:
public static String getDigest(String user, String realm, String password, String method, String uri, String nonce, String nc, String cnonce, String qop) { String digest1 = user + ":" + realm + ":" + password; String digest2 = method + ":" + uri; try { MessageDigest digestOne = MessageDigest.getInstance("md5"); digestOne.update(digest1.getBytes()); String hexDigestOne = getHexString(digestOne.digest()); MessageDigest digestTwo = MessageDigest.getInstance("md5"); digestTwo.update(digest2.getBytes()); String hexDigestTwo = getHexString(digestTwo.digest()); String digest3 = hexDigestOne + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + hexDigestTwo; MessageDigest digestThree = MessageDigest.getInstance("md5"); digestThree.update(digest3.getBytes()); String hexDigestThree = getHexString(digestThree.digest()); return hexDigestThree; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; }
Code Sample 2:
void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
|
11
|
Code Sample 1:
private void externalizeFiles(Document doc, File out) throws IOException { File[] files = doc.getImages(); if (files.length > 0) { File dir = new File(out.getParentFile(), out.getName() + ".images"); if (!dir.mkdirs()) throw new IOException("cannot create directory " + dir); if (dir.exists()) { for (int i = 0; i < files.length; i++) { File file = files[i]; File copy = new File(dir, file.getName()); FileChannel from = null, to = null; long count = -1; try { from = new FileInputStream(file).getChannel(); count = from.size(); to = new FileOutputStream(copy).getChannel(); from.transferTo(0, count, to); doc.setImage(file, dir.getName() + "/" + copy.getName()); } catch (Throwable t) { LOG.log(Level.WARNING, "Copying '" + file + "' to '" + copy + "' failed (size=" + count + ")", t); } finally { try { to.close(); } catch (Throwable t) { } try { from.close(); } catch (Throwable t) { } } } } } }
Code Sample 2:
public static void copiaAnexos(String from, String to, AnexoTO[] anexoTO) { FileChannel in = null, out = null; for (int i = 0; i < anexoTO.length; i++) { try { in = new FileInputStream(new File((uploadDiretorio.concat(from)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); out = new FileOutputStream(new File((uploadDiretorio.concat(to)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
|
11
|
Code Sample 1:
public static void resourceToFile(final String resource, final String filePath) throws IOException { log.debug("Classloader is " + IOCopyUtils.class.getClassLoader()); InputStream in = IOCopyUtils.class.getResourceAsStream(resource); if (in == null) { log.warn("Resource not '" + resource + "' found. Try to prefix with '/'"); in = IOCopyUtils.class.getResourceAsStream("/" + resource); } if (in == null) { throw new IOException("Resource not '" + resource + "' found."); } final File file = new File(filePath); final OutputStream out = FileUtils.openOutputStream(file); final int bytes = IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); log.debug("Copied resource '" + resource + "' to file " + filePath + " (" + bytes + " bytes)"); }
Code Sample 2:
private static FileChannel getFileChannel(File file, boolean isOut, boolean append) throws OpenR66ProtocolSystemException { FileChannel fileChannel = null; try { if (isOut) { FileOutputStream fileOutputStream = new FileOutputStream(file.getPath(), append); fileChannel = fileOutputStream.getChannel(); if (append) { try { fileChannel.position(file.length()); } catch (IOException e) { } } } else { if (!file.exists()) { throw new OpenR66ProtocolSystemException("File does not exist"); } FileInputStream fileInputStream = new FileInputStream(file.getPath()); fileChannel = fileInputStream.getChannel(); } } catch (FileNotFoundException e) { throw new OpenR66ProtocolSystemException("File not found", e); } return fileChannel; }
|
00
|
Code Sample 1:
public static void copierFichier(URL url, File destination) throws CopieException, IOException { if (destination.exists()) { throw new CopieException("ERREUR : Copie du fichier '" + url.getPath() + "' vers '" + destination.getPath() + "' impossible!\n" + "CAUSE : Le fichier destination existe d�j�."); } URLConnection urlConnection = url.openConnection(); InputStream httpStream = urlConnection.getInputStream(); FileOutputStream destinationFile = new FileOutputStream(destination); byte buffer[] = new byte[512 * 1024]; int nbLecture; while ((nbLecture = httpStream.read(buffer)) != -1) { destinationFile.write(buffer, 0, nbLecture); } log.debug("(COPIE) Copie du fichier : " + url.getPath() + " --> " + destination.getPath()); httpStream.close(); destinationFile.close(); }
Code Sample 2:
public void process() { try { update("Shutdown knowledge base ...", 0); DBHelper.shutdownDB(); update("Shutdown knowledge base ...", 9); String zipDir = P.DIR.getPKBDataPath(); update("Backup in progress ...", 10); List<String> fileList = getFilesToZip(zipDir); File file = new File(fileName); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(file)); byte[] readBuffer = new byte[2156]; int bytesIn = 0; for (int i = 0; i < fileList.size(); i++) { String filePath = fileList.get(i); File f = new File(filePath); FileInputStream fis = new FileInputStream(f); String zipEntryName = f.getPath().substring(zipDir.length() + 1); ZipEntry anEntry = new ZipEntry(zipEntryName); zout.putNextEntry(anEntry); while ((bytesIn = fis.read(readBuffer)) != -1) { zout.write(readBuffer, 0, bytesIn); } fis.close(); int percentage = (int) Math.round((i + 1) * 80.0 / fileList.size()); update("Backup in progress ...", 10 + percentage); } zout.close(); update("Restart knowledge base ...", 91); DBHelper.startDB(); update("Backup is done!", 100); } catch (Exception ex) { ex.printStackTrace(); update("Error occurs during backup!", 100); } }
|
00
|
Code Sample 1:
public static void fileCopy(File src, File dst) throws FileNotFoundException, IOException { if (src.isDirectory() && (!dst.exists() || dst.isDirectory())) { if (!dst.exists()) { if (!dst.mkdirs()) throw new IOException("unable to mkdir " + dst); } File dst1 = new File(dst, src.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); dst = dst1; File[] files = src.listFiles(); for (File f : files) { if (f.isDirectory()) { dst1 = new File(dst, f.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); } else { dst1 = dst; } fileCopy(f, dst1); } return; } else if (dst.isDirectory()) { dst = new File(dst, src.getName()); } FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(dst).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
Code Sample 2:
public Texture loadTexture(String file) throws IOException { URL imageUrl = urlFactory.makeUrl(file); Texture cached = textureLoader.getImageFromCache(imageUrl); if (cached != null) return cached; Image image; if (zip) { ZipInputStream zis = new ZipInputStream(url.openStream()); ZipEntry entry; boolean found = false; while ((entry = zis.getNextEntry()) != null) { if (file.equals(entry.getName())) { found = true; break; } } if (!found) { throw new IOException("Cannot find file \"" + file + "\"."); } int extIndex = file.lastIndexOf('.'); if (extIndex == -1) { throw new IOException("Cannot parse file extension."); } String fileExt = file.substring(extIndex); image = TextureManager.loadImage(fileExt, zis, true); } else { image = TextureManager.loadImage(imageUrl, true); } return textureLoader.loadTexture(imageUrl, image); }
|
00
|
Code Sample 1:
public String getHashedPhoneId(Context aContext) { if (hashedPhoneId == null) { final String androidId = BuildInfo.getAndroidID(aContext); if (androidId == null) { hashedPhoneId = "EMULATOR"; } else { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(androidId.getBytes()); messageDigest.update(aContext.getPackageName().getBytes()); final StringBuilder stringBuilder = new StringBuilder(); for (byte b : messageDigest.digest()) { stringBuilder.append(String.format("%02X", b)); } hashedPhoneId = stringBuilder.toString(); } catch (Exception e) { Log.e(LoggingExceptionHandler.class.getName(), "Unable to get phone id", e); hashedPhoneId = "Not Available"; } } } return hashedPhoneId; }
Code Sample 2:
public static void main(String[] args) { if (args.length <= 0) { System.out.println(" *** SQL script generator and executor ***"); System.out.println(" You must specify name of the file with SQL script data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with administrator priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have: '@' before schema to create,"); System.out.println(" '#' before table to create, '&' before table to insert,"); System.out.println(" '$' before trigger (inverse 'FK on delete cascade') to create,"); System.out.println(" '>' before table to drop, '<' before schema to drop."); System.out.println(" Other rows contain parameters of these actions:"); System.out.println(" for & action each parameter is a list of values,"); System.out.println(" for @ -//- is # acrion, for # -//- is column/constraint "); System.out.println(" definition or $ action. $ syntax to delete from table:"); System.out.println(" fullNameOfTable:itsColInWhereClause=matchingColOfThisTable"); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" If you specify 2nd command line argument - file name too -"); System.out.println(" connection will be established but all statements will"); System.out.println(" be saved in that output file and not transmitted to DB"); System.out.println(" If you specify 3nd command line argument - connect_string -"); System.out.println(" connect information will be added to output file"); System.out.println(" in the form 'connect user/password@connect_string'"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; try { for (int i = 0; i < 4; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); SQLScript script = new SQLScript(connection); if (args.length > 1) { writer = new FileWriter(args[1]); if (args.length > 2) writer.write("connect " + info[2] + "/" + info[3] + "@" + args[2] + script.statementTerminator); } try { System.out.println(script.executeScript(reader, writer) + " updates has been performed during script execution"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); System.out.println(" Script execution error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } }
|
00
|
Code Sample 1:
private static void upload(String login, String password, String file) throws ApiException { System.out.println("Trying to login to 4shared........"); File f = new File(file); if (!f.exists() || !f.canRead() || f.isDirectory()) { System.out.println("File does not exist, unreadable or not a file"); return; } DesktopAppJax2 da = new DesktopAppJax2Service().getDesktopAppJax2Port(); String loginRes = da.login(login, password); if (!loginRes.isEmpty()) { System.out.println("Login failed: " + loginRes); return; } if (!da.hasRightUpload()) { System.out.println("Uploading is temporarily disabled"); return; } System.out.println("4shared Login successful :)"); long newFileId = da.uploadStartFile(login, password, -1, f.getName(), f.length()); System.out.println("File id : " + newFileId); String sessionKey = da.createUploadSessionKey(login, password, -1); long dcId = da.getNewFileDataCenter(login, password); String url = da.getUploadFormUrl((int) dcId, sessionKey); try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); MultipartEntity me = new MultipartEntity(); StringBody rfid = new StringBody("" + newFileId); StringBody rfb = new StringBody("" + 0); InputStreamBody isb = new InputStreamBody(new BufferedInputStream(new FileInputStream(f)), "FilePart"); me.addPart("resumableFileId", rfid); me.addPart("resumableFirstByte", rfb); me.addPart("FilePart", isb); post.setEntity(me); HttpResponse resp = client.execute(post); HttpEntity resEnt = resp.getEntity(); String res = da.uploadFinishFile(login, password, newFileId, DigestUtils.md5Hex(new FileInputStream(f))); if (res.isEmpty()) { System.out.println("File uploaded."); downloadlink = da.getFileDownloadLink(login, password, newFileId); System.out.println("Download link : " + downloadlink); } else { System.out.println("Upload failed: " + res); } } catch (Exception ex) { System.out.println("Upload failed: " + ex.getMessage()); } }
Code Sample 2:
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
11
|
Code Sample 1:
private static synchronized boolean doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { destFile = new File(destFile + FILE_SEPARATOR + srcFile.getName()); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } return destFile.exists(); }
Code Sample 2:
public static void decoupe(String input_file_path) { final int BUFFER_SIZE = 2000000; try { FileInputStream fr = new FileInputStream(input_file_path); byte[] cbuf = new byte[BUFFER_SIZE]; int n_read = 0; int i = 0; boolean bContinue = true; while (bContinue) { n_read = fr.read(cbuf, 0, BUFFER_SIZE); if (n_read == -1) break; FileOutputStream fo = new FileOutputStream("f_" + ++i); fo.write(cbuf, 0, n_read); fo.close(); } fr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
protected boolean update(String sql, int requiredRows, int maxRows) throws SQLException { if (LOG.isDebugEnabled()) { LOG.debug("executing " + sql + "..."); } Connection connection = null; boolean oldAutoCommit = true; try { connection = dataSource.getConnection(); connection.clearWarnings(); oldAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); Statement statement = connection.createStatement(); int rowsAffected = statement.executeUpdate(sql); if (requiredRows != -1 && rowsAffected < requiredRows) { LOG.warn("(" + rowsAffected + ") less than " + requiredRows + " rows affected, rolling back..."); connection.rollback(); return false; } if (maxRows != -1 && rowsAffected > maxRows) { LOG.warn("(" + rowsAffected + ") more than " + maxRows + " rows affected, rolling back..."); connection.rollback(); return false; } connection.commit(); return true; } catch (SQLException e) { LOG.error("Unable to update database using: " + sql, e); throw e; } finally { try { if (connection != null) { connection.setAutoCommit(oldAutoCommit); connection.close(); } } catch (SQLException e) { LOG.error("Unable to close connection: " + e, e); } } }
Code Sample 2:
public static void loadPlugins() { Logger.trace("Loading plugins"); Enumeration<URL> urls = null; try { urls = Play.classloader.getResources("play.plugins"); } catch (Exception e) { } while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); Logger.trace("Found one plugins descriptor, %s", url); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { String[] infos = line.split(":"); PlayPlugin plugin = (PlayPlugin) Play.classloader.loadClass(infos[1].trim()).newInstance(); Logger.trace("Loaded plugin %s", plugin); plugin.index = Integer.parseInt(infos[0]); plugins.add(plugin); } } catch (Exception ex) { Logger.error(ex, "Cannot load %s", url); } } Collections.sort(plugins); for (PlayPlugin plugin : new ArrayList<PlayPlugin>(plugins)) { plugin.onLoad(); } }
|
00
|
Code Sample 1:
public boolean copy(long id) { boolean bool = false; this.result = null; Connection conn = null; Object vo = null; try { PojoParser parser = PojoParser.getInstances(); conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); String sql = SqlUtil.getInsertSql(this.getCls()); vo = this.findById(conn, "select * from " + parser.getTableName(cls) + " where " + parser.getPriamryKey(cls) + "=" + id); String pk = parser.getPriamryKey(cls); this.getClass().getMethod("set" + SqlUtil.getFieldName(pk), new Class[] { long.class }).invoke(vo, new Object[] { 0 }); PreparedStatement ps = conn.prepareStatement(sql); setPsParams(ps, vo); ps.executeUpdate(); ps.close(); conn.commit(); bool = true; } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { } this.result = e.getMessage(); } finally { this.closeConnectWithTransaction(conn); } return bool; }
Code Sample 2:
public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } }
|
11
|
Code Sample 1:
@Override protected IStatus runCancelableRunnable(IProgressMonitor monitor) { IStatus returnValue = Status.OK_STATUS; monitor.beginTask(NLS.bind(Messages.SaveFileOnDiskHandler_SavingFiles, open), informationUnitsFromExecutionEvent.size()); for (InformationUnit informationUnit : informationUnitsFromExecutionEvent) { if (!monitor.isCanceled()) { monitor.setTaskName(NLS.bind(Messages.SaveFileOnDiskHandler_Saving, informationUnit.getLabel())); InformationStructureRead read = InformationStructureRead.newSession(informationUnit); read.getValueByNodeId(Activator.FILENAME); IFile binaryReferenceFile = InformationUtil.getBinaryReferenceFile(informationUnit); FileWriter writer = null; try { if (binaryReferenceFile != null) { File file = new File(open, (String) read.getValueByNodeId(Activator.FILENAME)); InputStream contents = binaryReferenceFile.getContents(); writer = new FileWriter(file); IOUtils.copy(contents, writer); monitor.worked(1); } } catch (Exception e) { returnValue = StatusCreator.newStatus(NLS.bind(Messages.SaveFileOnDiskHandler_ErrorSaving, informationUnit.getLabel(), e)); break; } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (IOException e) { } } } } } return returnValue; }
Code Sample 2:
private synchronized Frame addFrame(INSERT_TYPE type, File source) throws IOException { if (source == null) throw new NullPointerException("Parameter 'source' is null"); if (!source.exists()) throw new IOException("File does not exist: " + source.getAbsolutePath()); if (source.length() <= 0) throw new IOException("File is empty: " + source.getAbsolutePath()); File newLocation = new File(Settings.getPropertyString(ConstantKeys.project_dir), formatFileName(frames_.size())); if (newLocation.compareTo(source) != 0) { switch(type) { case MOVE: source.renameTo(newLocation); break; case COPY: FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(newLocation).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); break; } } Frame f = new Frame(newLocation); f.createThumbNail(); frames_.add(f); return f; }
|
11
|
Code Sample 1:
public static String md5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException ex) { return password; } }
Code Sample 2:
public synchronized String encrypt(String plaintext) { MessageDigest md = null; String hash = null; try { md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); hash = (new BASE64Encoder()).encode(raw); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return hash; }
|
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:
private void appendArchive() throws Exception { String cmd; if (profile == CompilationProfile.UNIX_GCC) { cmd = "cat"; } else if (profile == CompilationProfile.MINGW_WINDOWS) { cmd = "type"; } else { throw new Exception("Unknown cat equivalent for profile " + profile); } compFrame.writeLine("<span style='color: green;'>" + cmd + " \"" + imageArchive.getAbsolutePath() + "\" >> \"" + outputFile.getAbsolutePath() + "\"</span>"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile, true)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageArchive)); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); out.close(); }
|
11
|
Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public static String read(URL url) throws Exception { String filename = Integer.toString(url.toString().hashCode()); boolean cached = false; File dir = new File(Config.CACHE_PATH); for (File file : dir.listFiles()) { if (!file.isFile()) continue; if (file.getName().equals(filename)) { filename = file.getName(); cached = true; break; } } File file = new File(Config.CACHE_PATH, filename); if (Config.USE_CACHE && cached) return read(file); System.out.println(">> CACHE HIT FAILED."); InputStream in = null; try { in = url.openStream(); } catch (Exception e) { System.out.println(">> OPEN STREAM FAILED: " + url.toString()); return null; } String content = read(in); save(file, content); return content; }
Code Sample 2:
public static Collection providers(Class service, ClassLoader loader) { List classList = new ArrayList(); List nameSet = new ArrayList(); String name = "META-INF/services/" + service.getName(); Enumeration services; try { services = (loader == null) ? ClassLoader.getSystemResources(name) : loader.getResources(name); } catch (IOException ioe) { System.err.println("Service: cannot load " + name); return classList; } while (services.hasMoreElements()) { URL url = (URL) services.nextElement(); InputStream input = null; BufferedReader reader = null; try { input = url.openStream(); reader = new BufferedReader(new InputStreamReader(input, "utf-8")); String line = reader.readLine(); while (line != null) { int ci = line.indexOf('#'); if (ci >= 0) line = line.substring(0, ci); line = line.trim(); int si = line.indexOf(' '); if (si >= 0) line = line.substring(0, si); line = line.trim(); if (line.length() > 0) { if (!nameSet.contains(line)) nameSet.add(line); } line = reader.readLine(); } } catch (IOException ioe) { System.err.println("Service: problem with: " + url); } finally { try { if (input != null) input.close(); if (reader != null) reader.close(); } catch (IOException ioe2) { System.err.println("Service: problem with: " + url); } } } Iterator names = nameSet.iterator(); while (names.hasNext()) { String className = (String) names.next(); try { classList.add(Class.forName(className, true, loader).newInstance()); } catch (ClassNotFoundException e) { System.err.println("Service: cannot find class: " + className); } catch (InstantiationException e) { System.err.println("Service: cannot instantiate: " + className); } catch (IllegalAccessException e) { System.err.println("Service: illegal access to: " + className); } catch (NoClassDefFoundError e) { System.err.println("Service: " + e + " for " + className); } catch (Exception e) { System.err.println("Service: exception for: " + className + " " + e); } } return classList; }
|
11
|
Code Sample 1:
public ActionForward uploadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_response) { ActionMessages errors = new ActionMessages(); ActionMessages messages = new ActionMessages(); String returnPage = "submitPocketSampleInformationPage"; UploadForm form = (UploadForm) actForm; Integer shippingId = null; try { eHTPXXLSParser parser = new eHTPXXLSParser(); String proposalCode; String proposalNumber; String proposalName; String uploadedFileName; String realXLSPath; if (request != null) { proposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE); proposalNumber = String.valueOf(request.getSession().getAttribute(Constants.PROPOSAL_NUMBER)); proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = form.getRequestFile().getFileName(); String fileName = proposalName + "_" + uploadedFileName; realXLSPath = request.getRealPath("\\tmp\\") + "\\" + fileName; FormFile f = form.getRequestFile(); InputStream in = f.getInputStream(); File outputFile = new File(realXLSPath); if (outputFile.exists()) outputFile.delete(); FileOutputStream out = new FileOutputStream(outputFile); while (in.available() != 0) { out.write(in.read()); out.flush(); } out.flush(); out.close(); } else { proposalCode = "ehtpx"; proposalNumber = "1"; proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = "ispyb-template41.xls"; realXLSPath = "D:\\" + uploadedFileName; } FileInputStream inFile = new FileInputStream(realXLSPath); parser.retrieveShippingId(realXLSPath); shippingId = parser.getShippingId(); String requestShippingId = form.getShippingId(); if (requestShippingId != null && !requestShippingId.equals("")) { shippingId = new Integer(requestShippingId); } ClientLogger.getInstance().debug("uploadFile for shippingId " + shippingId); if (shippingId != null) { Log.debug(" ---[uploadFile] Upload for Existing Shipment (DewarTRacking): Deleting Samples from Shipment :"); double nbSamplesContainers = DBAccess_EJB.DeleteAllSamplesAndContainersForShipping(shippingId); if (nbSamplesContainers > 0) parser.getValidationWarnings().add(new XlsUploadException("Shipment contained Samples and/or Containers", "Previous Samples and/or Containers have been deleted and replaced by new ones.")); else parser.getValidationWarnings().add(new XlsUploadException("Shipment contained no Samples and no Containers", "Samples and Containers have been added.")); } Hashtable<String, Hashtable<String, Integer>> listProteinAcronym_SampleName = new Hashtable<String, Hashtable<String, Integer>>(); ProposalFacadeLocal proposal = ProposalFacadeUtil.getLocalHome().create(); ProteinFacadeLocal protein = ProteinFacadeUtil.getLocalHome().create(); CrystalFacadeLocal crystal = CrystalFacadeUtil.getLocalHome().create(); ProposalLightValue targetProposal = (ProposalLightValue) (((ArrayList) proposal.findByCodeAndNumber(proposalCode, new Integer(proposalNumber))).get(0)); ArrayList listProteins = (ArrayList) protein.findByProposalId(targetProposal.getProposalId()); for (int p = 0; p < listProteins.size(); p++) { ProteinValue prot = (ProteinValue) listProteins.get(p); Hashtable<String, Integer> listSampleName = new Hashtable<String, Integer>(); CrystalLightValue listCrystals[] = prot.getCrystals(); for (int c = 0; c < listCrystals.length; c++) { CrystalLightValue _xtal = (CrystalLightValue) listCrystals[c]; CrystalValue xtal = crystal.findByPrimaryKey(_xtal.getPrimaryKey()); BlsampleLightValue listSamples[] = xtal.getBlsamples(); for (int s = 0; s < listSamples.length; s++) { BlsampleLightValue sample = listSamples[s]; listSampleName.put(sample.getName(), sample.getBlSampleId()); } } listProteinAcronym_SampleName.put(prot.getAcronym(), listSampleName); } parser.validate(inFile, listProteinAcronym_SampleName, targetProposal.getProposalId()); List listErrors = parser.getValidationErrors(); List listWarnings = parser.getValidationWarnings(); if (listErrors.size() == 0) { parser.open(realXLSPath); if (parser.getCrystals().size() == 0) { parser.getValidationErrors().add(new XlsUploadException("No crystals have been found", "Empty shipment")); } } Iterator errIt = listErrors.iterator(); while (errIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) errIt.next(); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveErrors(request, errors); } catch (Exception e) { } Iterator warnIt = listWarnings.iterator(); while (warnIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) warnIt.next(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveMessages(request, messages); } catch (Exception e) { } if (listErrors.size() > 0) { resetCounts(shippingId); return mapping.findForward("submitPocketSampleInformationPage"); } if (listWarnings.size() > 0) returnPage = "submitPocketSampleInformationPage"; String crystalDetailsXML; XtalDetails xtalDetailsWebService = new XtalDetails(); CrystalDetailsBuilder cDE = new CrystalDetailsBuilder(); CrystalDetailsElement cd = cDE.createCrystalDetailsElement(proposalName, parser.getCrystals()); cDE.validateJAXBObject(cd); crystalDetailsXML = cDE.marshallJaxBObjToString(cd); xtalDetailsWebService.submitCrystalDetails(crystalDetailsXML); String diffractionPlan; DiffractionPlan diffractionPlanWebService = new DiffractionPlan(); DiffractionPlanBuilder dPB = new DiffractionPlanBuilder(); Iterator it = parser.getDiffractionPlans().iterator(); while (it.hasNext()) { DiffractionPlanElement dpe = (DiffractionPlanElement) it.next(); dpe.setProjectUUID(proposalName); diffractionPlan = dPB.marshallJaxBObjToString(dpe); diffractionPlanWebService.submitDiffractionPlan(diffractionPlan); } String crystalShipping; Shipping shippingWebService = new Shipping(); CrystalShippingBuilder cSB = new CrystalShippingBuilder(); Person person = cSB.createPerson("XLS Upload", null, "ISPyB", null, null, "ISPyB", null, "ispyb@esrf.fr", "0000", "0000", null, null); Laboratory laboratory = cSB.createLaboratory("Generic Laboratory", "ISPyB Lab", "Sandwich", "Somewhere", "UK", "ISPyB", "ispyb.esrf.fr", person); DeliveryAgent deliveryAgent = parser.getDeliveryAgent(); CrystalShipping cs = cSB.createCrystalShipping(proposalName, laboratory, deliveryAgent, parser.getDewars()); String shippingName; shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xls")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xls") : 0); if (shippingName.equalsIgnoreCase("")) shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xlt")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xlt") : 0); cs.setName(shippingName); crystalShipping = cSB.marshallJaxBObjToString(cs); shippingWebService.submitCrystalShipping(crystalShipping, (ArrayList) parser.getDiffractionPlans(), shippingId); ServerLogger.Log4Stat("XLS_UPLOAD", proposalName, uploadedFileName); } catch (XlsUploadException e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.getMessage())); ClientLogger.getInstance().error(e.toString()); saveErrors(request, errors); return mapping.findForward("error"); } catch (Exception e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); ClientLogger.getInstance().error(e.toString()); e.printStackTrace(); saveErrors(request, errors); return mapping.findForward("error"); } setCounts(shippingId); return mapping.findForward(returnPage); }
Code Sample 2:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); int i; for (i = 0; ((i < list.length) && !stop); i++) { current = i; if ((list[i].compareTo("Images") != 0) && ((list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".jpg") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".bmp") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".png") == 0))) { String name = list[i]; String pathSrc = directoryPath.concat(list[i]); name = name.replace(' ', '_').replace(',', '-').replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('Á', 'A').replace('É', 'E').replace('Í', 'I').replace('Ó', 'O').replace('Ú', 'U'); String pathDst = directoryPath.concat(name); Vector aux = new Vector(); aux = dataBase.imageSearch(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) pathDst = pathDst.substring(0, pathDst.lastIndexOf('.')) + '_' + aux.size() + ".png"; File src = new File(pathSrc); File absPath = new File(""); String nameSrc = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase() + src.separator + pathDst.substring(pathDst.lastIndexOf(src.separator) + 1, pathDst.length()); String newDirectory = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase(); String imagePathThumb = (nameSrc.substring(0, nameSrc.lastIndexOf("."))).concat("_th.jpg"); ImageIcon image = null; if (src != null) { if (TFileUtils.isJAIRequired(src)) { RenderedOp src_aux = JAI.create("fileload", src.getAbsolutePath()); BufferedImage bufferedImage = src_aux.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(src.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { System.out.print("Error al insertar imagen: "); System.out.println(pathDst); } else { int option = 0; imageFile = new File(directoryPath + "Images"); if (!imageFile.exists()) { TIGNewImageDataDialog dialog = new TIGNewImageDataDialog(editor, dataBase, image, nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length()), list[i].substring(0, list[i].lastIndexOf('.')), myTask); option = dialog.getOption(); if (option != 0) { File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } } if (imageFile.exists()) { dataBase.insertImageDB(list[i].substring(0, list[i].lastIndexOf('.')), nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length())); File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } } if (imageFile.exists() && !stop) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(imageFile); Element dataBaseElement = doc.getDocumentElement(); if (dataBaseElement.getTagName().equals("dataBase")) { NodeList imageNodeList = dataBaseElement.getElementsByTagName("image"); for (int j = 0; j < imageNodeList.getLength(); j++) { current++; Node imageNode = imageNodeList.item(j); NodeList lista = imageNode.getChildNodes(); Node nameNode = imageNode.getChildNodes().item(0); String imageName = nameNode.getChildNodes().item(0).getNodeValue(); int imageKey = dataBase.imageKeySearchName(imageName.substring(0, imageName.lastIndexOf('.'))); if (imageKey != -1) { for (int k = 1; k < imageNode.getChildNodes().getLength(); k++) { Node keyWordNode = imageNode.getChildNodes().item(k); String keyWord = keyWordNode.getChildNodes().item(0).getNodeValue(); int conceptKey = dataBase.conceptKeySearch(keyWord); if (conceptKey == -1) { dataBase.insertConceptDB(keyWord); conceptKey = dataBase.conceptKeySearch(keyWord); } dataBase.insertAsociatedDB(conceptKey, imageKey); } } } } } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } current = lengthOfTask; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.