label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void copy(File source, File dest) throws IOException { System.out.println("copy " + source + " -> " + dest); FileInputStream in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { out.close(); } } finally { in.close(); } }
00
Code Sample 1: public Document load(java.net.URL url) throws DOMTestLoadException { Document doc = null; Exception parseException = null; try { LoadErrorHandler errorHandler = new LoadErrorHandler(); builder.setErrorHandler(errorHandler); doc = builder.parse(url.openStream(), url.toString()); parseException = errorHandler.getFirstException(); } catch (Exception ex) { parseException = ex; } builder.setErrorHandler(null); if (parseException != null) { throw new DOMTestLoadException(parseException); } return doc; } Code Sample 2: protected void copy(File src, File dest) throws IOException { if (src.isDirectory() && dest.isFile()) throw new IOException("Cannot copy a directory to a file"); if (src.isDirectory()) { File newDir = new File(dest, src.getName()); if (!newDir.mkdirs()) throw new IOException("Cannot create a new Directory"); File[] entries = src.listFiles(); for (int i = 0; i < entries.length; ++i) copy(entries[i], newDir); return; } if (dest.isDirectory()) { File newFile = new File(dest, src.getName()); newFile.createNewFile(); copy(src, newFile); return; } try { if (src.length() == 0) { dest.createNewFile(); return; } FileChannel fc = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); long transfered = 0; long totalLength = src.length(); while (transfered < totalLength) { long num = fc.transferTo(transfered, totalLength - transfered, dstChannel); if (num == 0) throw new IOException("Error while copying"); transfered += num; } dstChannel.close(); fc.close(); } catch (IOException e) { if (os.equals("Unix")) { _logger.fine("Trying to use cp to copy file..."); File cp = new File("/usr/bin/cp"); if (!cp.exists()) cp = new File("/bin/cp"); if (!cp.exists()) cp = new File("/usr/local/bin/cp"); if (!cp.exists()) cp = new File("/sbin/cp"); if (!cp.exists()) cp = new File("/usr/sbin/cp"); if (!cp.exists()) cp = new File("/usr/local/sbin/cp"); if (cp.exists()) { Process cpProcess = Runtime.getRuntime().exec(cp.getAbsolutePath() + " '" + src.getAbsolutePath() + "' '" + dest.getAbsolutePath() + "'"); int errCode; try { errCode = cpProcess.waitFor(); } catch (java.lang.InterruptedException ie) { throw e; } return; } } throw e; } }
11
Code Sample 1: public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); } Code Sample 2: public static long copy(File src, File dest) throws UtilException { FileChannel srcFc = null; FileChannel destFc = null; try { srcFc = new FileInputStream(src).getChannel(); destFc = new FileOutputStream(dest).getChannel(); long srcLength = srcFc.size(); srcFc.transferTo(0, srcLength, destFc); return srcLength; } catch (IOException e) { throw new UtilException(e); } finally { try { if (srcFc != null) srcFc.close(); srcFc = null; } catch (IOException e) { } try { if (destFc != null) destFc.close(); destFc = null; } catch (IOException e) { } } }
11
Code Sample 1: private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); ServletContext ctx = getServletContext(); RequestDispatcher rd = ctx.getRequestDispatcher(SETUP_JSP); HttpSession session = request.getSession(false); if (session == null) { session = request.getSession(true); session.setAttribute(ERROR_TAG, "You need to have run the Sniffer before running " + "the Grinder. Go to <a href=\"/index.jsp\">the start page</a> " + " to run the Sniffer."); rd = ctx.getRequestDispatcher(ERROR_JSP); } else { session.setMaxInactiveInterval(-1); String pValue = request.getParameter(ACTION_TAG); if (pValue != null && pValue.equals(START_TAG)) { rd = ctx.getRequestDispatcher(WAIT_JSP); int p = 1; int t = 1; int c = 1; try { p = Integer.parseInt(request.getParameter("procs")); p = p > MAX_PROCS ? MAX_PROCS : p; } catch (NumberFormatException e) { } try { t = Integer.parseInt(request.getParameter("threads")); t = t > MAX_THREADS ? MAX_THREADS : t; } catch (NumberFormatException e) { } try { c = Integer.parseInt(request.getParameter("cycles")); c = c > MAX_CYCLES ? MAX_CYCLES : c; } catch (NumberFormatException e) { } try { String dirname = (String) session.getAttribute(OUTPUT_TAG); File workdir = new File(dirname); (new File(dirname + File.separator + LOG_DIR)).mkdir(); FileInputStream gpin = new FileInputStream(GPROPS); FileOutputStream gpout = new FileOutputStream(dirname + File.separator + GPROPS); copyBytes(gpin, gpout); gpin.close(); InitialContext ictx = new InitialContext(); Boolean isSecure = (Boolean) session.getAttribute(SECURE_TAG); if (isSecure.booleanValue()) { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpsPlugin" + "\n").getBytes()); String certificate = (String) ictx.lookup(CERTIFICATE); String password = (String) ictx.lookup(PASSWORD); gpout.write(("grinder.plugin.parameter.clientCert=" + certificate + "\n").getBytes()); gpout.write(("grinder.plugin.parameter.clientCertPassword=" + password + "\n").getBytes()); } else { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpPlugin\n").getBytes()); } gpout.write(("grinder.processes=" + p + "\n").getBytes()); gpout.write(("grinder.threads=" + t + "\n").getBytes()); gpout.write(("grinder.cycles=" + c + "\n").getBytes()); gpin = new FileInputStream(dirname + File.separator + SNIFFOUT); copyBytes(gpin, gpout); gpin.close(); gpout.close(); String classpath = (String) ictx.lookup(CLASSPATH); String cmd[] = new String[JAVA_PROCESS.length + 1 + GRINDER_PROCESS.length]; int i = 0; int n = JAVA_PROCESS.length; System.arraycopy(JAVA_PROCESS, 0, cmd, i, n); cmd[n] = classpath; i = n + 1; n = GRINDER_PROCESS.length; System.arraycopy(GRINDER_PROCESS, 0, cmd, i, n); for (int j = 0; j < cmd.length; ++j) { System.out.print(cmd[j] + " "); } Process proc = Runtime.getRuntime().exec(cmd, null, workdir); session.setAttribute(PROCESS_TAG, proc); } catch (NamingException e) { e.printStackTrace(); session.setAttribute(ERROR_MSG_TAG, e.toString()); session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(ERROR_JSP); } catch (Throwable e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } else if (pValue != null && pValue.equals(CHECK_TAG)) { boolean finished = true; try { Process p = (Process) session.getAttribute(PROCESS_TAG); int result = p.exitValue(); } catch (IllegalThreadStateException e) { finished = false; } if (finished) { session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(RESULTS_JSP); } else { rd = ctx.getRequestDispatcher(WAIT_JSP); } } try { rd.forward(request, response); } catch (ServletException e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: @Test public void testOther() throws Exception { filter.init(this.mockConfig); ByteArrayOutputStream jpg = new ByteArrayOutputStream(); IOUtils.copy(this.getClass().getResourceAsStream("Buffalo-Theory.jpg"), jpg); MockFilterChain mockChain = new MockFilterChain(); mockChain.setContentType("image/jpg"); mockChain.setOutputData(jpg.toByteArray()); MockResponse mockResponse = new MockResponse(); filter.doFilter(this.mockRequest, mockResponse, mockChain); Assert.assertTrue("Time stamp content type", "image/jpg".equals(mockResponse.getContentType())); Assert.assertTrue("OutputStream as original", ArrayUtils.isEquals(jpg.toByteArray(), mockResponse.getMockServletOutputStream().getBytes())); } Code Sample 2: public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("�����ļ�ʧ�ܣ�Դ�ļ�" + srcFileName + "������!"); return false; } else if (!srcFile.isFile()) { System.out.println("�����ļ�ʧ�ܣ�" + srcFileName + "����һ���ļ�!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("Ŀ���ļ��Ѵ��ڣ�׼��ɾ��!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("ɾ��Ŀ���ļ�" + descFileName + "ʧ��!"); return false; } } else { System.out.println("�����ļ�ʧ�ܣ�Ŀ���ļ�" + descFileName + "�Ѵ���!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("Ŀ���ļ����ڵ�Ŀ¼�����ڣ�����Ŀ¼!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("����Ŀ���ļ����ڵ�Ŀ¼ʧ��!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("���Ƶ����ļ�" + srcFileName + "��" + descFileName + "�ɹ�!"); return true; } catch (Exception e) { System.out.println("�����ļ�ʧ�ܣ�" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } }
11
Code Sample 1: private void createWikiPages(WikiContext context) throws PluginException { OntologyWikiPageName owpn = new OntologyWikiPageName(omemo.getFormDataAlias().toUpperCase(), omemo.getFormDataVersionDate()); String wikiPageFullFileName = WikiPageName2FullFileName(context, owpn.toString()); String rdfFileNameWithPath = getWorkDir(context) + File.separator + owpn.toFileName(); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(wikiPageFullFileName); fis = new FileInputStream(rdfFileNameWithPath); InfoExtractor infoe = new InfoExtractor(fis, omemo.getFormDataNS(), omemo.getFormDataOntLang()); infoe.writePage(getWorkDir(context), owpn, Omemo.checksWikiPageName); fis.close(); fos.close(); } catch (Exception e) { log.error("Can not read local rdf file or can not write wiki page"); throw new PluginException("Error creating wiki pages. See logs"); } } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
11
Code Sample 1: private void copyReportFile(ServletRequest req, String reportName, Report report) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException, FileNotFoundException, IOException { String reportFileName = (String) Class.forName("org.eclipse.birt.report.utility.ParameterAccessor").getMethod("getReport", new Class[] { HttpServletRequest.class, String.class }).invoke(null, new Object[] { req, reportName }); ByteArrayInputStream bais = new ByteArrayInputStream(report.getReportContent()); FileOutputStream fos = new FileOutputStream(new File(reportFileName)); IOUtils.copy(bais, fos); bais.close(); fos.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void 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); } } Code Sample 2: private static String fetchUrl(String url, boolean keepLineEnds) throws IOException, MalformedURLException { URLConnection destConnection = (new URL(url)).openConnection(); BufferedReader br; String inputLine; StringBuffer doc = new StringBuffer(); String contentEncoding; destConnection.setRequestProperty("Accept-Encoding", "gzip"); if (proxyAuth != null) destConnection.setRequestProperty("Proxy-Authorization", proxyAuth); destConnection.connect(); contentEncoding = destConnection.getContentEncoding(); if ((contentEncoding != null) && contentEncoding.equals("gzip")) { br = new BufferedReader(new InputStreamReader(new GZIPInputStream(destConnection.getInputStream()))); } else { br = new BufferedReader(new InputStreamReader(destConnection.getInputStream())); } while ((inputLine = br.readLine()) != null) { if (keepLineEnds) doc.append(inputLine + "\n"); else doc.append(inputLine); } br.close(); return doc.toString(); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: public void testWriteThreadsNoCompression() throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.loadProfiles(CommandLineProcessorFactory.PROFILE.DB, CommandLineProcessorFactory.PROFILE.REST_CLIENT, CommandLineProcessorFactory.PROFILE.COLLECTOR); final LocalLogFileWriter writer = (LocalLogFileWriter) bootstrap.getBean(LogFileWriter.class); writer.init(); writer.setCompressionCodec(null); File fileInput = new File(baseDir, "testWriteOneFile/input"); fileInput.mkdirs(); File fileOutput = new File(baseDir, "testWriteOneFile/output"); fileOutput.mkdirs(); writer.setBaseDir(fileOutput); int fileCount = 100; int lineCount = 100; File[] inputFiles = createInput(fileInput, fileCount, lineCount); ExecutorService exec = Executors.newFixedThreadPool(fileCount); final CountDownLatch latch = new CountDownLatch(fileCount); for (int i = 0; i < fileCount; i++) { final File file = inputFiles[i]; final int count = i; exec.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { FileStatus.FileTrackingStatus status = FileStatus.FileTrackingStatus.newBuilder().setFileDate(System.currentTimeMillis()).setDate(System.currentTimeMillis()).setAgentName("agent1").setFileName(file.getName()).setFileSize(file.length()).setLogType("type1").build(); BufferedReader reader = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = reader.readLine()) != null) { writer.write(status, new ByteArrayInputStream((line + "\n").getBytes())); } } finally { IOUtils.closeQuietly(reader); } LOG.info("Thread[" + count + "] completed "); latch.countDown(); return true; } }); } latch.await(); exec.shutdown(); LOG.info("Shutdown thread service"); writer.close(); File[] outputFiles = fileOutput.listFiles(); assertNotNull(outputFiles); File testCombinedInput = new File(baseDir, "combinedInfile.txt"); testCombinedInput.createNewFile(); FileOutputStream testCombinedInputOutStream = new FileOutputStream(testCombinedInput); try { for (File file : inputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedInputOutStream); } } finally { testCombinedInputOutStream.close(); } File testCombinedOutput = new File(baseDir, "combinedOutfile.txt"); testCombinedOutput.createNewFile(); FileOutputStream testCombinedOutOutStream = new FileOutputStream(testCombinedOutput); try { System.out.println("----------------- " + testCombinedOutput.getAbsolutePath()); for (File file : outputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedOutOutStream); } } finally { testCombinedOutOutStream.close(); } FileUtils.contentEquals(testCombinedInput, testCombinedOutput); } Code Sample 2: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String contentType = req.getParameter("type"); String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing File Arg"); return; } File f = new File(arg); if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } if (contentType != null) { resp.setContentType(contentType); } log.debug("Requested File: " + f + " as type: " + contentType); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } }
00
Code Sample 1: public HttpEntity execute(final HttpRequestBase request) throws IOException, ClientProtocolException { final HttpResponse response = mClient.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK | statusCode == HttpStatus.SC_CREATED) { return response.getEntity(); } return null; } Code Sample 2: private static String loadUrlToString(String a_url) throws IOException { URL l_url1 = new URL(a_url); BufferedReader br = new BufferedReader(new InputStreamReader(l_url1.openStream())); String l_content = ""; String l_ligne = null; l_content = br.readLine(); while ((l_ligne = br.readLine()) != null) { l_content += AA.SL + l_ligne; } return l_content; }
11
Code Sample 1: 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(); } } Code Sample 2: public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: public void test() throws Exception { StringDocument doc = new StringDocument("Test", "UTF-8"); doc.open(); try { assertEquals("UTF-8", doc.getCharacterEncoding()); assertEquals("Test", doc.getText()); InputStream input = doc.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { writer.close(); } assertEquals("Test", writer.toString()); } finally { doc.close(); } } Code Sample 2: public static void copyFile(File srcFile, File destFolder) { try { File destFile = new File(destFolder, srcFile.getName()); if (destFile.exists()) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + " as " + destFile + " already exists"); } FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); destChannel = new FileOutputStream(destFile).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (destChannel != null) { destChannel.close(); } } destFile.setLastModified((srcFile.lastModified())); } catch (IOException e) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + ": " + e, e); } }
11
Code Sample 1: private String hashPassword(String password) { if (password != null && password.trim().length() > 0) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.trim().getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } } return null; } Code Sample 2: public byte[] computeMD5(String plainText) throws VHException { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new VHException("The MD5 hash algorithm is not available.", ex); } try { md.update(plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { throw new VHException("The UTF-8 encoding is not supported.", ex); } return md.digest(); }
00
Code Sample 1: public static XMLShowInfo NzbSearch(TVRageShowInfo tvrage, XMLShowInfo xmldata, int latestOrNext) { String newzbin_query = "", csvData = "", hellaQueueDir = "", newzbinUsr = "", newzbinPass = ""; String[] tmp; DateFormat tvRageDateFormat = new SimpleDateFormat("MMM/dd/yyyy"); DateFormat tvRageDateFormatFix = new SimpleDateFormat("yyyy-MM-dd"); newzbin_query = "?q=" + xmldata.showName + "+"; if (latestOrNext == 0) { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.latestSeasonNum + "x" + tvrage.latestEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.latestSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.latestAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.latestTitle; } else { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.nextSeasonNum + "x" + tvrage.nextEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.nextSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.nextAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.nextTitle; } newzbin_query += "&searchaction=Search"; newzbin_query += "&fpn=p"; newzbin_query += "&category=8category=11"; newzbin_query += "&area=-1"; newzbin_query += "&u_nfo_posts_only=0"; newzbin_query += "&u_url_posts_only=0"; newzbin_query += "&u_comment_posts_only=0"; newzbin_query += "&u_v3_retention=1209600"; newzbin_query += "&ps_rb_language=" + xmldata.language; newzbin_query += "&sort=ps_edit_date"; newzbin_query += "&order=desc"; newzbin_query += "&areadone=-1"; newzbin_query += "&feed=csv"; newzbin_query += "&ps_rb_video_format=" + xmldata.format; newzbin_query = newzbin_query.replaceAll(" ", "%20"); System.out.println("http://v3.newzbin.com/search/" + newzbin_query); try { URL url = new URL("http://v3.newzbin.com/search/" + newzbin_query); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); csvData = in.readLine(); if (csvData != null) { JavaNZB.searchCount++; if (searchCount == 6) { searchCount = 0; System.out.println("Sleeping for 60 seconds"); try { Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } tmp = csvData.split(","); tmp[2] = tmp[2].substring(1, tmp[2].length() - 1); tmp[3] = tmp[3].substring(1, tmp[3].length() - 1); Pattern p = Pattern.compile("[\\\\</:>?\\[|\\]\"]"); Matcher matcher = p.matcher(tmp[3]); tmp[3] = matcher.replaceAll(" "); tmp[3] = tmp[3].replaceAll("&", "and"); URLConnection urlConn; DataOutputStream printout; url = new URL("http://v3.newzbin.com/api/dnzb/"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String content = "username=" + JavaNZB.newzbinUsr + "&password=" + JavaNZB.newzbinPass + "&reportid=" + tmp[2]; printout.writeBytes(content); printout.flush(); printout.close(); BufferedReader nzbInput = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String format = ""; if (xmldata.format.equals("17")) format = " Xvid"; if (xmldata.format.equals("131072")) format = " x264"; if (xmldata.format.equals("2")) format = " DVD"; if (xmldata.format.equals("4")) format = " SVCD"; if (xmldata.format.equals("8")) format = " VCD"; if (xmldata.format.equals("32")) format = " HDts"; if (xmldata.format.equals("64")) format = " WMV"; if (xmldata.format.equals("128")) format = " Other"; if (xmldata.format.equals("256")) format = " ratDVD"; if (xmldata.format.equals("512")) format = " iPod"; if (xmldata.format.equals("1024")) format = " PSP"; File f = new File(JavaNZB.hellaQueueDir, tmp[3] + format + ".nzb"); BufferedWriter out = new BufferedWriter(new FileWriter(f)); String str; System.out.println("--Downloading " + tmp[3] + format + ".nzb" + " to queue directory--"); while (null != ((str = nzbInput.readLine()))) out.write(str); nzbInput.close(); out.close(); if (latestOrNext == 0) { xmldata.episode = tvrage.latestEpisodeNum; xmldata.season = tvrage.latestSeasonNum; } else { xmldata.episode = tvrage.nextEpisodeNum; xmldata.season = tvrage.nextSeasonNum; } } else System.out.println("No new episode posted"); System.out.println(); } catch (MalformedURLException e) { } catch (IOException e) { System.out.println("IO Exception from NzbSearch"); } return xmldata; } Code Sample 2: public static String encrypt32(String plainText) { String str = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } str = buf.toString(); System.out.println("result: " + buf.toString()); System.out.println("result: " + buf.toString().substring(8, 24)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return str; } return str; }
11
Code Sample 1: public static Properties parse() { try { String userHome = System.getProperty("user.home"); File dsigFolder = new File(userHome, ".dsig"); if (!dsigFolder.exists() && !dsigFolder.mkdir()) { throw new IOException("Could not create .dsig folder in user home directory"); } File settingsFile = new File(dsigFolder, "settings.properties"); if (!settingsFile.exists()) { InputStream is = UserHomeSettingsParser.class.getResourceAsStream("/defaultSettings.properties"); if (is != null) { IOUtils.copy(is, new FileOutputStream(settingsFile)); } } if (settingsFile.exists()) { Properties p = new Properties(); FileInputStream fis = new FileInputStream(settingsFile); p.load(fis); IOUtils.closeQuietly(fis); return p; } } catch (IOException e) { logger.warn("Error while initialize settings", e); } return null; } Code Sample 2: private static void copyFile(String src, String dest) throws IOException { File destFile = new File(dest); if (destFile.exists()) { destFile.delete(); } FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
11
Code Sample 1: protected void writePage(final CacheItem entry, final TranslationResponse response, ModifyTimes times) throws IOException { if (entry == null) { return; } Set<ResponseHeader> headers = new TreeSet<ResponseHeader>(); for (ResponseHeader h : entry.getHeaders()) { if (TranslationResponse.ETAG.equals(h.getName())) { if (!times.isFileLastModifiedKnown()) { headers.add(new ResponseHeaderImpl(h.getName(), doETagStripWeakMarker(h.getValues()))); } } else { headers.add(h); } } response.addHeaders(headers); if (!times.isFileLastModifiedKnown()) { response.setLastModified(entry.getLastModified()); } response.setTranslationCount(entry.getTranslationCount()); response.setFailCount(entry.getFailCount()); OutputStream output = response.getOutputStream(); try { InputStream input = entry.getContentAsStream(); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { response.setEndState(ResponseStateOk.getInstance()); } } Code Sample 2: public SWORDEntry ingestDepost(final DepositCollection pDeposit, final ServiceDocument pServiceDocument) throws SWORDException { try { ZipFileAccess tZipFile = new ZipFileAccess(super.getTempDir()); LOG.debug("copying file"); String tZipTempFileName = super.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tZipTempFileName)); Datastream tDatastream = new LocalDatastream(super.getGenericFileName(pDeposit), this.getContentType(), tZipTempFileName); _datastreamList.add(tDatastream); _datastreamList.addAll(tZipFile.getFiles(tZipTempFileName)); int i = 0; boolean found = false; for (i = 0; i < _datastreamList.size(); i++) { if (_datastreamList.get(i).getId().equalsIgnoreCase("mets")) { found = true; break; } } if (found) { SAXBuilder tBuilder = new SAXBuilder(); _mets = new METSObject(tBuilder.build(((LocalDatastream) _datastreamList.get(i)).getPath())); LocalDatastream tLocalMETSDS = (LocalDatastream) _datastreamList.remove(i); new File(tLocalMETSDS.getPath()).delete(); _datastreamList.add(_mets.getMETSDs()); _datastreamList.addAll(_mets.getMetadataDatastreams()); } else { throw new SWORDException("Couldn't find a METS document in the zip file, ensure it is named mets.xml or METS.xml"); } SWORDEntry tEntry = super.ingestDepost(pDeposit, pServiceDocument); tZipFile.removeLocalFiles(); return tEntry; } catch (IOException tIOExcpt) { String tMessage = "Couldn't retrieve METS from deposit: " + tIOExcpt.toString(); LOG.error(tMessage); tIOExcpt.printStackTrace(); throw new SWORDException(tMessage, tIOExcpt); } catch (JDOMException tJDOMExcpt) { String tMessage = "Couldn't build METS from deposit: " + tJDOMExcpt.toString(); LOG.error(tMessage); tJDOMExcpt.printStackTrace(); throw new SWORDException(tMessage, tJDOMExcpt); } }
11
Code Sample 1: protected void migrateOnDemand() { try { if (fso.fileExists(prefix + ".fat") && !fso.fileExists(prefix + EXTENSIONS[UBM_FILE])) { RandomAccessFile ubm, meta, ctr, rbm; InputStream inputStream; OutputStream outputStream; fso.renameFile(prefix + ".fat", prefix + EXTENSIONS[UBM_FILE]); ubm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); meta = fso.openFile(prefix + EXTENSIONS[MTD_FILE], "rw"); ctr = fso.openFile(prefix + EXTENSIONS[CTR_FILE], "rw"); ubm.seek(ubm.length() - 16); meta.writeInt(blockSize = ubm.readInt()); meta.writeInt(size = ubm.readInt()); ctr.setLength(ubm.readLong() + blockSize); ctr.close(); meta.close(); ubm.setLength(ubm.length() - 16); ubm.seek(0); rbm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); inputStream = new BufferedInputStream(new RandomAccessFileInputStream(ubm)); outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(rbm)); for (int b; (b = inputStream.read()) != -1; ) outputStream.write(b); outputStream.close(); inputStream.close(); rbm.close(); ubm.close(); } } catch (IOException ie) { throw new WrappingRuntimeException(ie); } } Code Sample 2: public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); }
00
Code Sample 1: public static void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true); fileInputStream.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private BoardPattern[] getBoardPatterns() { Resource[] resources = boardManager.getResources("boards"); BoardPattern[] boardPatterns = new BoardPattern[resources.length]; for (int i = 0; i < resources.length; i++) boardPatterns[i] = (BoardPattern) resources[i]; for (int i = 0; i < resources.length; i++) { for (int j = 0; j < resources.length - (i + 1); j++) { String name1 = boardPatterns[j].getName(); String name2 = boardPatterns[j + 1].getName(); if (name1.compareTo(name2) > 0) { BoardPattern tmp = boardPatterns[j]; boardPatterns[j] = boardPatterns[j + 1]; boardPatterns[j + 1] = tmp; } } } return boardPatterns; }
00
Code Sample 1: public static String loadUrl(URL url, String charset) throws MyException { try { URLConnection conn = url.openConnection(); InputStream urlin = conn.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(urlin, charset)); StringBuffer buff = new StringBuffer(); char[] cbuf = new char[1028]; int count; while ((count = in.read(cbuf)) != -1) { buff.append(new String(cbuf, 0, count)); } return buff.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); throw new MyException(MyException.ERROR_FILENOTFOUND, e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new MyException(MyException.ERROR_IO, e.getMessage()); } } Code Sample 2: 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); } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void convert(File file, String fromEncoding, String toEncoding) throws IOException { InputStream in = new FileInputStream(file); StringWriter cache = new StringWriter(); Reader reader = new InputStreamReader(in, fromEncoding); char[] buffer = new char[128]; int read; while ((read = reader.read(buffer)) > -1) { cache.write(buffer, 0, read); } reader.close(); in.close(); Log.warn(this, "read from file " + file + " (" + fromEncoding + "):" + cache); OutputStream out = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(out, toEncoding); writer.write(cache.toString()); cache.close(); writer.close(); out.close(); }
00
Code Sample 1: public synchronized String encrypt(final String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pPassword.getBytes("UTF-8")); final byte raw[] = md.digest(); return BASE64Encoder.encodeBuffer(raw); } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { File inputFile = src; File outputFile = dst; FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: private String postData(String requestUrl, String atom) throws AuthenticationException, IOException { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); String header; try { header = oauthAuthenticator.getHttpAuthorizationHeader(url.toString(), "POST", profile.getOAuthToken(), profile.getOAuthTokenSecret()); } catch (OAuthException e) { throw new AuthenticationException(e); } conn.setRequestProperty("Authorization", header); conn.setRequestProperty("Content-Type", "application/atom+xml"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); writer.write(atom); writer.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new AuthenticationException(); } InputStreamReader reader = new InputStreamReader(conn.getInputStream()); char[] buffer = new char[1024]; int bytesRead = 0; StringBuilder data = new StringBuilder(); while ((bytesRead = reader.read(buffer)) != -1) { data.append(buffer, 0, bytesRead); } reader.close(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage() + "\n" + data); } return data.toString(); } Code Sample 2: private int testAccesspoint(String s) throws IOException { HttpURLConnection connection = null; try { URL url = new URL(s); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK || responseCode >= 500) { return 100; } else { return 0; } } finally { if (connection != null) { connection.disconnect(); } } }
00
Code Sample 1: private static String calculateMD5(String s) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(s.getBytes()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException e) { throw new UndeclaredThrowableException(e); } } Code Sample 2: public static void batchInsertOrder(Order o) throws AppException { Connection conn = DBUtils.getDataConnection(); PreparedStatement pstmt = null; ResultSet rs = null; String sqlOrder = null; String sqlDetail = null; try { conn.setAutoCommit(false); sqlOrder = "insert into SO_SOMain (ID,cSOCode,dDate," + "cBusType,cCusCode,cCusName," + "cDepCode,cSTCode," + "iVTid,cMaker,cMemo) values (?,?,?,?,?,?,?,?,?,?,?)"; sqlDetail = "insert into SO_SODetails (ID,cSOCode,cInvCode,cInvName," + "iNum,iQuantity,iTaxUnitPrice,iSum,dPreDate,iSOsID,cFree1,cUnitID) values(?,?,?,?,?,?,?,?,?,?,?,?)"; pstmt = conn.prepareStatement(sqlOrder); long maxId = getMaxID(conn, pstmt, rs); maxId++; pstmt.setLong(1, maxId); Long l = maxId; o.setId(l.intValue()); String code = o.getCode(); long maxCSOCode = getMaxCSOCode(code, conn, pstmt, rs); String csOCode = getCSOCode(code, maxCSOCode); o.setCode(csOCode); pstmt.setString(2, csOCode); pstmt.setDate(3, DateUtil.getSqlDateFormUtilDate(o.getOrderDate())); pstmt.setString(4, o.getBusinessType()); pstmt.setString(5, o.getC().getId()); pstmt.setString(6, o.getC().getName()); pstmt.setString(7, o.getP().getDept().getId()); pstmt.setString(8, o.getSaleType().getId()); pstmt.setInt(9, o.getiVtid()); pstmt.setString(10, o.getP().getName()); pstmt.setString(11, o.getRemark()); pstmt.executeUpdate(); pstmt.clearParameters(); pstmt = conn.prepareStatement(sqlDetail); ArrayList<OrderDetail> ods = o.getOds(); long iSOsID = getiSOsID(conn, pstmt, rs); for (OrderDetail od : ods) { pstmt.setLong(1, maxId); pstmt.setString(2, csOCode); pstmt.setString(3, od.getInventory().getId()); pstmt.setString(4, od.getInventory().getName()); pstmt.setInt(5, od.getPiece()); pstmt.setBigDecimal(6, od.getCount()); pstmt.setBigDecimal(7, od.getPrice()); pstmt.setBigDecimal(8, od.getSum()); pstmt.setDate(9, DateUtil.getSqlDateFormUtilDate(od.getSendDate())); pstmt.setLong(10, ++iSOsID); pstmt.setString(11, od.getPacking().getcValue()); pstmt.setString(12, od.getInventory().getSAComUnitCode()); pstmt.executeUpdate(); pstmt.clearParameters(); } conn.commit(); } catch (SQLException sqle) { try { conn.rollback(); throw new AppException(sqle.getMessage()); } catch (SQLException ex) { Logger.getLogger(OrderDAO.class.getName()).log(Level.SEVERE, null, ex); throw new AppException(ex.getMessage()); } } finally { DBUtils.closeAll(rs, pstmt, conn); } }
00
Code Sample 1: private static void copy(File source, File target, byte[] buffer) throws FileNotFoundException, IOException { InputStream in = new FileInputStream(source); File parent = target.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } if (target.isDirectory()) { target = new File(target, source.getName()); } OutputStream out = new FileOutputStream(target); int read; try { while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch (IOException e) { throw e; } finally { in.close(); out.close(); } } Code Sample 2: public static void insertTableData(Connection dest, TableMetaData tableMetaData) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "INSERT INTO " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + ","; } sql = sql.substring(0, sql.length() - 1); sql += ") VALUES ("; for (String columnName : tableMetaData.getColumnsNames()) { sql += "?" + ","; } sql = sql.substring(0, sql.length() - 1); sql += ")"; IOHelper.writeInfo(sql); ps = dest.prepareStatement(sql); for (Row r : tableMetaData.getData()) { try { int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { IOHelper.writeInfo(columnName + " = " + r.getRowData().get(columnName)); ps.setObject(param, r.getRowData().get(columnName)); } param++; } if (ps.executeUpdate() != 1) { dest.rollback(); updateTableData(dest, tableMetaData, r); } } catch (Exception ex) { try { dest.rollback(); updateTableData(dest, tableMetaData, r); } catch (Exception ex2) { IOHelper.writeError("Error in update " + sql, ex2); } } ps.clearParameters(); } dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } }
00
Code Sample 1: private Document post(String location, String content) throws ApplicationException { Document doc = null; try { URL url = new URL(location); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setRequestMethod("POST"); uc.setRequestProperty("Content-Type", "application/xml"); uc.setRequestProperty("X-POST_DATA_FORMAT", "xml"); uc.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream()); out.write("<request>"); out.write("<token>" + configuration.getBackpackPassword() + "</token>"); if (content != null) { out.write("<item><content>" + content + "</content></item>"); } out.write("</request>"); out.close(); doc = XmlUtils.readDocumentFromInputStream(uc.getInputStream()); System.out.println(XmlUtils.toString(doc)); } catch (IOException e) { e.printStackTrace(); throw new ApplicationException(e); } return doc; } Code Sample 2: public void install(Session session) throws Exception { String cfgPath = ConfigurationFactory.getConfigSonInstance().getConfigurationPath(); File setupKson = new File(cfgPath, "setup.kson"); InputStream is = null; if (setupKson.exists()) { log.debug("Reagind kson from " + setupKson.getAbsolutePath()); is = new FileInputStream(setupKson); } else { String ksonCp = "/org/chon/cms/core/setup/setup.kson"; is = Setup.class.getResourceAsStream(ksonCp); log.info("Creating initial setup.kson in " + setupKson.getAbsolutePath()); IOUtils.copy(is, new FileOutputStream(setupKson)); is = new FileInputStream(setupKson); } BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); List<String> lines = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; lines.add(line); } List<NodeCreation> ncList = readKSon(lines.toArray(new String[lines.size()])); for (NodeCreation nc : ncList) { try { createNode(session, nc); } catch (Exception e) { System.err.println("error crating node " + nc.path + " -> " + e.getMessage()); } } session.save(); }
00
Code Sample 1: public Message[] expunge() throws MessagingException { Statement oStmt = null; CallableStatement oCall = null; PreparedStatement oUpdt = null; ResultSet oRSet; if (DebugFile.trace) { DebugFile.writeln("Begin DBFolder.expunge()"); DebugFile.incIdent(); } if (0 == (iOpenMode & READ_WRITE)) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open is READ_WRITE mode"); } if ((0 == (iOpenMode & MODE_MBOX)) && (0 == (iOpenMode & MODE_BLOB))) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open in MBOX nor BLOB mode"); } MboxFile oMBox = null; DBSubset oDeleted = new DBSubset(DB.k_mime_msgs, DB.gu_mimemsg + "," + DB.pg_message, DB.bo_deleted + "=1 AND " + DB.gu_category + "='" + oCatg.getString(DB.gu_category) + "'", 100); try { int iDeleted = oDeleted.load(getConnection()); File oFile = getFile(); if (oFile.exists() && iDeleted > 0) { oMBox = new MboxFile(oFile, MboxFile.READ_WRITE); int[] msgnums = new int[iDeleted]; for (int m = 0; m < iDeleted; m++) msgnums[m] = oDeleted.getInt(1, m); oMBox.purge(msgnums); oMBox.close(); } oStmt = oConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); oRSet = oStmt.executeQuery("SELECT p." + DB.file_name + " FROM " + DB.k_mime_parts + " p," + DB.k_mime_msgs + " m WHERE p." + DB.gu_mimemsg + "=m." + DB.gu_mimemsg + " AND m." + DB.id_disposition + "='reference' AND m." + DB.bo_deleted + "=1 AND m." + DB.gu_category + "='" + oCatg.getString(DB.gu_category) + "'"); while (oRSet.next()) { String sFileName = oRSet.getString(1); if (!oRSet.wasNull()) { try { File oRef = new File(sFileName); oRef.delete(); } catch (SecurityException se) { if (DebugFile.trace) DebugFile.writeln("SecurityException " + sFileName + " " + se.getMessage()); } } } oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; oFile = getFile(); oStmt = oConn.createStatement(); oStmt.executeUpdate("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + String.valueOf(oFile.length()) + " WHERE " + DB.gu_category + "='" + getCategory().getString(DB.gu_category) + "'"); oStmt.close(); oStmt = null; if (oConn.getDataBaseProduct() == JDCConnection.DBMS_POSTGRESQL) { oStmt = oConn.createStatement(); for (int d = 0; d < iDeleted; d++) oStmt.executeQuery("SELECT k_sp_del_mime_msg('" + oDeleted.getString(0, d) + "')"); oStmt.close(); oStmt = null; } else { oCall = oConn.prepareCall("{ call k_sp_del_mime_msg(?) }"); for (int d = 0; d < iDeleted; d++) { oCall.setString(1, oDeleted.getString(0, d)); oCall.execute(); } oCall.close(); oCall = null; } if (oFile.exists() && iDeleted > 0) { BigDecimal oUnit = new BigDecimal(1); oStmt = oConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); oRSet = oStmt.executeQuery("SELECT MAX(" + DB.pg_message + ") FROM " + DB.k_mime_msgs + " WHERE " + DB.gu_category + "='getCategory().getString(DB.gu_category)'"); oRSet.next(); BigDecimal oMaxPg = oRSet.getBigDecimal(1); if (oRSet.wasNull()) oMaxPg = new BigDecimal(0); oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; oMaxPg = oMaxPg.add(oUnit); oStmt = oConn.createStatement(); oStmt.executeUpdate("UPDATE " + DB.k_mime_msgs + " SET " + DB.pg_message + "=" + DB.pg_message + "+" + oMaxPg.toString() + " WHERE " + DB.gu_category + "='" + getCategory().getString(DB.gu_category) + "'"); oStmt.close(); oStmt = null; DBSubset oMsgSet = new DBSubset(DB.k_mime_msgs, DB.gu_mimemsg + "," + DB.pg_message, DB.gu_category + "='" + getCategory().getString(DB.gu_category) + "' ORDER BY " + DB.pg_message, 1000); int iMsgCount = oMsgSet.load(oConn); oMBox = new MboxFile(oFile, MboxFile.READ_ONLY); long[] aPositions = oMBox.getMessagePositions(); oMBox.close(); if (iMsgCount != aPositions.length) { throw new IOException("DBFolder.expunge() Message count of " + String.valueOf(aPositions.length) + " at MBOX file " + oFile.getName() + " does not match message count at database index of " + String.valueOf(iMsgCount)); } oMaxPg = new BigDecimal(0); oUpdt = oConn.prepareStatement("UPDATE " + DB.k_mime_msgs + " SET " + DB.pg_message + "=?," + DB.nu_position + "=? WHERE " + DB.gu_mimemsg + "=?"); for (int m = 0; m < iMsgCount; m++) { oUpdt.setBigDecimal(1, oMaxPg); oUpdt.setBigDecimal(2, new BigDecimal(aPositions[m])); oUpdt.setString(3, oMsgSet.getString(0, m)); oUpdt.executeUpdate(); oMaxPg = oMaxPg.add(oUnit); } oUpdt.close(); } oConn.commit(); } catch (SQLException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception e) { } try { if (oStmt != null) oStmt.close(); } catch (Exception e) { } try { if (oCall != null) oCall.close(); } catch (Exception e) { } try { if (oConn != null) oConn.rollback(); } catch (Exception e) { } throw new MessagingException(sqle.getMessage(), sqle); } catch (IOException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception e) { } try { if (oStmt != null) oStmt.close(); } catch (Exception e) { } try { if (oCall != null) oCall.close(); } catch (Exception e) { } try { if (oConn != null) oConn.rollback(); } catch (Exception e) { } throw new MessagingException(sqle.getMessage(), sqle); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBFolder.expunge()"); } return null; } Code Sample 2: public static void copyWithClose(InputStream is, OutputStream os) throws IOException { try { IOUtils.copy(is, os); } catch (IOException ioe) { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } }
11
Code Sample 1: private static String GetSHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return LoginHttpPostProcessor.ConvertToHex(sha1hash); } Code Sample 2: private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
11
Code Sample 1: public static boolean writeFile(HttpServletResponse resp, File reqFile) { boolean retVal = false; InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(reqFile)); IOUtils.copy(in, resp.getOutputStream()); logger.debug("File successful written to servlet response: " + reqFile.getAbsolutePath()); } catch (FileNotFoundException e) { logger.error("Resource not found: " + reqFile.getAbsolutePath()); } catch (IOException e) { logger.error(String.format("Error while rendering [%s]: %s", reqFile.getAbsolutePath(), e.getMessage()), e); } finally { IOUtils.closeQuietly(in); } return retVal; } Code Sample 2: public static final boolean copy(File source, File target, boolean overwrite) { if (!overwrite && target.exists()) { LOGGER.error("Target file exist and it not permitted to overwrite it !"); return false; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } finally { try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } } return true; }
11
Code Sample 1: public static void main(String[] args) throws Exception { PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n"); ConsoleAppender ca = new ConsoleAppender(pl); Logger.getRoot().addAppender(ca); Logger.getRoot().setLevel(Level.INFO); Options options = new Options(); options.addOption("p", "put", false, "put a file in the DHT overlay"); options.addOption("g", "get", false, "get a file from the DHT"); options.addOption("r", "remove", false, "remove a file from the DHT"); options.addOption("u", "update", false, "updates the lease"); options.addOption("j", "join", false, "join the DHT overlay"); options.addOption("c", "config", true, "the configuration file"); options.addOption("k", "key", true, "the key to read a file from"); options.addOption("f", "file", true, "the file to read or write"); options.addOption("a", "app", true, "the application ID"); options.addOption("s", "secret", true, "the secret used to hide data"); options.addOption("t", "ttl", true, "how long in seconds data should persist"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String configFile = null; String mode = null; String secretStr = null; int ttl = 9999; String keyStr = null; String file = null; int appId = 0; if (cmd.hasOption("j")) { mode = "join"; } if (cmd.hasOption("p")) { mode = "put"; } if (cmd.hasOption("g")) { mode = "get"; } if (cmd.hasOption("r")) { mode = "remove"; } if (cmd.hasOption("u")) { mode = "update"; } if (cmd.hasOption("c")) { configFile = cmd.getOptionValue("c"); } if (cmd.hasOption("k")) { keyStr = cmd.getOptionValue("k"); } if (cmd.hasOption("f")) { file = cmd.getOptionValue("f"); } if (cmd.hasOption("s")) { secretStr = cmd.getOptionValue("s"); } if (cmd.hasOption("t")) { ttl = Integer.parseInt(cmd.getOptionValue("t")); } if (cmd.hasOption("a")) { appId = Integer.parseInt(cmd.getOptionValue("a")); } if (mode == null) { System.err.println("ERROR: --put or --get or --remove or --join or --update is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (configFile == null) { System.err.println("ERROR: --config is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } Properties conf = new Properties(); conf.load(new FileInputStream(configFile)); DHT dht = new DHT(conf); if (mode.equals("join")) { dht.join(); } else if (mode.equals("put")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("putting file " + file); FileInputStream in = new FileInputStream(file); byte[] tmp = new byte[1000000]; int num = in.read(tmp); byte[] value = new byte[num]; System.arraycopy(tmp, 0, value, 0, num); in.close(); if (dht.put((short) appId, keyStr.getBytes(), value, ttl, secretStr.getBytes()) < 0) { logger.info("There was an error while putting a key-value."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("get")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("getting file " + file); ArrayList<byte[]> values = new ArrayList<byte[]>(); if (dht.get((short) appId, keyStr.getBytes(), Integer.MAX_VALUE, values) < 0) { logger.info("There was an error while getting a value."); System.exit(0); } if (values.size() == 0 || values == null) { System.out.println("No values returned."); System.exit(0); } FileOutputStream out = new FileOutputStream(file); System.out.println("Found " + values.size() + " values -- saving the first one only."); out.write(values.get(0)); out.close(); System.out.println("Ok!"); } else if (mode.equals("remove")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("removing <key,value> for key=" + keyStr); if (dht.remove((short) appId, keyStr.getBytes(), secretStr.getBytes()) < 0) { logger.info("There was an error while removing a key."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("update")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("updating <key,value> for key=" + keyStr); if (dht.updateLease((short) appId, keyStr.getBytes(), ttl) < 0) { logger.info("There was an error while updating data lease."); System.exit(0); } System.out.println("Ok!"); } DHT.getInstance().stop(); } Code Sample 2: public static void main(String[] args) { final String filePath1 = "e:\\mysite\\data\\up\\itsite"; final String filePath2 = "d:\\works\\itsite\\itsite"; IOUtils.listAllFilesNoRs(new File(filePath2), new FileFilter() { @Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; } }); }
00
Code Sample 1: public static void copy(File inputFile, File target) throws IOException { if (!inputFile.exists()) return; OutputStream output = new FileOutputStream(target); InputStream input = new BufferedInputStream(new FileInputStream(inputFile)); int b; while ((b = input.read()) != -1) output.write(b); output.close(); input.close(); } Code Sample 2: public boolean createUser(String username, String password, String name) throws Exception { boolean user_created = false; try { statement = connect.prepareStatement("SELECT COUNT(*) from toepen.users WHERE username = ? LIMIT 1"); statement.setString(1, username); resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); long ctime = System.currentTimeMillis() / 1000; statement = connect.prepareStatement("INSERT INTO toepen.users " + "(username, password, name, ctime) " + "VALUES (?, ?, ?, ?)"); statement.setString(1, username); statement.setString(2, password_hash); statement.setString(3, name); statement.setLong(4, ctime); if (statement.executeUpdate() > 0) { user_created = true; } } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_created; } }
00
Code Sample 1: private DataFileType[] getDataFiles(Collection<ContentToSend> contentsToSend) { DataFileType[] files = new DataFileType[contentsToSend.size()]; int fileIndex = 0; for (ContentToSend contentToSend : contentsToSend) { DataFileType dataFile = DataFileType.Factory.newInstance(); dataFile.setFilename(contentToSend.getFileName()); dataFile.setId("D" + fileIndex); dataFile.setMimeType(contentToSend.getMimeType()); dataFile.setContentType(DataFileType.ContentType.EMBEDDED_BASE_64); final StringWriter stringWriter = new StringWriter(); final OutputStream encodeStream = Base64.newEncoder(stringWriter, 0, null); final InputStream is = contentToSend.getInputStream(); try { long sizeCopied = IOUtils.copyLarge(is, encodeStream); dataFile.setSize(BigDecimal.valueOf(sizeCopied)); } catch (IOException e) { throw new RuntimeException("Failed to get input to the file to be sent", e); } finally { IOUtils.closeQuietly(encodeStream); IOUtils.closeQuietly(is); } dataFile.setStringValue(stringWriter.toString()); files[fileIndex++] = dataFile; } return files; } Code Sample 2: private static long writeVMDKFile(String absoluteFile, String urlString) throws Exception { URL urlCon = new URL(urlString); HttpsURLConnection conn = (HttpsURLConnection) urlCon.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); List cookies = (List) headers.get("Set-cookie"); cookieValue = (String) cookies.get(0); StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";"); cookieValue = tokenizer.nextToken(); String path = "$" + tokenizer.nextToken(); String cookie = "$Version=\"1\"; " + cookieValue + "; " + path; Map map = new HashMap(); map.put("Cookie", Collections.singletonList(cookie)); ((BindingProvider) vimPort).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, map); conn.setRequestProperty("Cookie", cookie); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestProperty("Expect", "100-continue"); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Length", "1024"); InputStream in = conn.getInputStream(); String localpath = localPath + "/" + absoluteFile; OutputStream out = new FileOutputStream(new File(localpath)); byte[] buf = new byte[102400]; int len = 0; long written = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); written = written + len; } System.out.println(" Exported File " + absoluteFile + " : " + written); in.close(); out.close(); return written; }
00
Code Sample 1: private boolean saveNodeData(NodeInfo info) { boolean rCode = false; String query = mServer + "save.php" + ("?id=" + info.getId()); try { URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); String contentType = info.getMIMEType().toString(); byte[] body = info.getData(); conn.setAllowUserInteraction(false); conn.setRequestMethod("PUT"); if (contentType.equals("")) { contentType = "application/octet-stream"; } System.out.println("contentType: " + contentType); conn.setRequestProperty("Content-Type", contentType); setCredentials(conn); conn.setDoOutput(true); conn.getOutputStream().write(body); rCode = saveNode(info, conn); } catch (Exception ex) { System.out.println("Exception: " + ex.toString()); } return rCode; } Code Sample 2: private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); ServletContext ctx = getServletContext(); RequestDispatcher rd = ctx.getRequestDispatcher(SETUP_JSP); HttpSession session = request.getSession(false); if (session == null) { session = request.getSession(true); session.setAttribute(ERROR_TAG, "You need to have run the Sniffer before running " + "the Grinder. Go to <a href=\"/index.jsp\">the start page</a> " + " to run the Sniffer."); rd = ctx.getRequestDispatcher(ERROR_JSP); } else { session.setMaxInactiveInterval(-1); String pValue = request.getParameter(ACTION_TAG); if (pValue != null && pValue.equals(START_TAG)) { rd = ctx.getRequestDispatcher(WAIT_JSP); int p = 1; int t = 1; int c = 1; try { p = Integer.parseInt(request.getParameter("procs")); p = p > MAX_PROCS ? MAX_PROCS : p; } catch (NumberFormatException e) { } try { t = Integer.parseInt(request.getParameter("threads")); t = t > MAX_THREADS ? MAX_THREADS : t; } catch (NumberFormatException e) { } try { c = Integer.parseInt(request.getParameter("cycles")); c = c > MAX_CYCLES ? MAX_CYCLES : c; } catch (NumberFormatException e) { } try { String dirname = (String) session.getAttribute(OUTPUT_TAG); File workdir = new File(dirname); (new File(dirname + File.separator + LOG_DIR)).mkdir(); FileInputStream gpin = new FileInputStream(GPROPS); FileOutputStream gpout = new FileOutputStream(dirname + File.separator + GPROPS); copyBytes(gpin, gpout); gpin.close(); InitialContext ictx = new InitialContext(); Boolean isSecure = (Boolean) session.getAttribute(SECURE_TAG); if (isSecure.booleanValue()) { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpsPlugin" + "\n").getBytes()); String certificate = (String) ictx.lookup(CERTIFICATE); String password = (String) ictx.lookup(PASSWORD); gpout.write(("grinder.plugin.parameter.clientCert=" + certificate + "\n").getBytes()); gpout.write(("grinder.plugin.parameter.clientCertPassword=" + password + "\n").getBytes()); } else { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpPlugin\n").getBytes()); } gpout.write(("grinder.processes=" + p + "\n").getBytes()); gpout.write(("grinder.threads=" + t + "\n").getBytes()); gpout.write(("grinder.cycles=" + c + "\n").getBytes()); gpin = new FileInputStream(dirname + File.separator + SNIFFOUT); copyBytes(gpin, gpout); gpin.close(); gpout.close(); String classpath = (String) ictx.lookup(CLASSPATH); String cmd[] = new String[JAVA_PROCESS.length + 1 + GRINDER_PROCESS.length]; int i = 0; int n = JAVA_PROCESS.length; System.arraycopy(JAVA_PROCESS, 0, cmd, i, n); cmd[n] = classpath; i = n + 1; n = GRINDER_PROCESS.length; System.arraycopy(GRINDER_PROCESS, 0, cmd, i, n); for (int j = 0; j < cmd.length; ++j) { System.out.print(cmd[j] + " "); } Process proc = Runtime.getRuntime().exec(cmd, null, workdir); session.setAttribute(PROCESS_TAG, proc); } catch (NamingException e) { e.printStackTrace(); session.setAttribute(ERROR_MSG_TAG, e.toString()); session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(ERROR_JSP); } catch (Throwable e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } else if (pValue != null && pValue.equals(CHECK_TAG)) { boolean finished = true; try { Process p = (Process) session.getAttribute(PROCESS_TAG); int result = p.exitValue(); } catch (IllegalThreadStateException e) { finished = false; } if (finished) { session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(RESULTS_JSP); } else { rd = ctx.getRequestDispatcher(WAIT_JSP); } } try { rd.forward(request, response); } catch (ServletException e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } }
00
Code Sample 1: private int saveToTempTable(ArrayList cons, String tempTableName, boolean truncateFirst) throws SQLException { if (truncateFirst) { this.executeUpdate("TRUNCATE TABLE " + tempTableName); Categories.dataDb().debug("TABLE " + tempTableName + " TRUNCATED."); } PreparedStatement ps = null; int rows = 0; try { String insert = "INSERT INTO " + tempTableName + " VALUES (?)"; ps = this.conn.prepareStatement(insert); for (int i = 0; i < cons.size(); i++) { ps.setLong(1, ((Long) cons.get(i)).longValue()); rows = ps.executeUpdate(); if ((i % 500) == 0) { this.conn.commit(); } } this.conn.commit(); } catch (SQLException sqle) { this.conn.rollback(); throw sqle; } finally { if (ps != null) { ps.close(); } } return rows; } Code Sample 2: public String getDocumentAt(String urlString) { StringBuffer document = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) document.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("Unable to connect to URL: " + urlString); } catch (IOException e) { System.out.println("IOException when connecting to URL: " + urlString); } return document.toString(); }
00
Code Sample 1: private static List<CountryEntry> retrieveCountries() throws IOException { URL url = new URL("http://" + ISO_3166_HOST + ISO_3166_TXT_FILE_PATH); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); List<CountryEntry> countries = new LinkedList<CountryEntry>(); boolean parsing = false; int trCount = 0; int tdCount = 0; CountryEntry current = new CountryEntry(); String nextLine = input.readLine(); while (nextLine != null) { if (nextLine.startsWith("<table")) { parsing = true; } if (nextLine.startsWith("</table>")) { break; } if (parsing) { if (nextLine.startsWith("<tr")) { trCount++; } else { if ((trCount > 1 && nextLine.startsWith("<td"))) { tdCount++; String data = pullData(nextLine); switch(tdCount) { case 1: current.setName(getCountryName(data)); break; case 2: current.setNumber(data); break; case 3: current.setAlpha3(data); break; case 4: current.setAlpha2(data); break; case 5: countries.add(current); current = new CountryEntry(); tdCount = 0; break; default: String msg = "Parsing error. Unexpected column: [" + data + "]"; throw new IllegalStateException(msg); } } } } nextLine = input.readLine(); } input.close(); return countries; } Code Sample 2: public static File insertFileInto(File zipFile, File toInsert, String targetPath) { Zip64File zip64File = null; try { boolean compress = false; zip64File = new Zip64File(zipFile); FileEntry testEntry = getFileEntry(zip64File, targetPath); if (testEntry != null && testEntry.getMethod() == FileEntry.iMETHOD_DEFLATED) { compress = true; } processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath, toInsert), compress); if (testEntry != null) { log.info("[insertFileInto] Entry exists: " + testEntry.getName()); log.info("[insertFileInto] Will delete this entry before inserting: " + toInsert.getName()); if (!testEntry.isDirectory()) { zip64File.delete(testEntry.getName()); } else { log.info("[insertFileInto] Entry is a directory. " + "Will delete all files contained in this entry and insert " + toInsert.getName() + "and all nested files."); if (!targetPath.contains("/")) { targetPath = targetPath + "/"; } deleteFileEntry(zip64File, testEntry); log.info("[insertFileInto] Entry successfully deleted."); } log.info("[insertFileInto] Writing new Entry: " + targetPath); EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } else { EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } log.info("[insertFileInto] Done! Added " + toInsert.getName() + " to zip."); zip64File.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new File(zip64File.getDiskFile().getFileName()); }
00
Code Sample 1: public static byte[] wrapBMP(Image image) throws IOException { if (image.getOriginalType() != Image.ORIGINAL_BMP) throw new IOException("Only BMP can be wrapped in WMF."); InputStream imgIn; byte data[] = null; if (image.getOriginalData() == null) { imgIn = image.url().openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int b = 0; while ((b = imgIn.read()) != -1) out.write(b); imgIn.close(); data = out.toByteArray(); } else data = image.getOriginalData(); int sizeBmpWords = (data.length - 14 + 1) >>> 1; ByteArrayOutputStream os = new ByteArrayOutputStream(); writeWord(os, 1); writeWord(os, 9); writeWord(os, 0x0300); writeDWord(os, 9 + 4 + 5 + 5 + (13 + sizeBmpWords) + 3); writeWord(os, 1); writeDWord(os, 14 + sizeBmpWords); writeWord(os, 0); writeDWord(os, 4); writeWord(os, META_SETMAPMODE); writeWord(os, 8); writeDWord(os, 5); writeWord(os, META_SETWINDOWORG); writeWord(os, 0); writeWord(os, 0); writeDWord(os, 5); writeWord(os, META_SETWINDOWEXT); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeDWord(os, 13 + sizeBmpWords); writeWord(os, META_DIBSTRETCHBLT); writeDWord(os, 0x00cc0020); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeWord(os, 0); writeWord(os, 0); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeWord(os, 0); writeWord(os, 0); os.write(data, 14, data.length - 14); if ((data.length & 1) == 1) os.write(0); writeDWord(os, 3); writeWord(os, 0); os.close(); return os.toByteArray(); } Code Sample 2: public String accessURL_Post(String url, String postStr, String encoding) throws Throwable { StringEntity entity = new StringEntity(postStr, encoding); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entity); HttpResponse response = client.execute(httpPost); String entuity = EntityUtils.toString(response.getEntity()); handleHeaders(response.getAllHeaders()); return entuity; }
11
Code Sample 1: public void testConvert() throws IOException, ConverterException { InputStreamReader reader = new InputStreamReader(new FileInputStream("test" + File.separator + "input" + File.separator + "A0851ohneex.dat"), CharsetUtil.forName("x-PICA")); FileWriter writer = new FileWriter("test" + File.separator + "output" + File.separator + "ddbInterToMarcxmlTest.out"); Converter c = context.getConverter("ddb-intern", "MARC21-xml", "x-PICA", "UTF-8"); ConversionParameters params = new ConversionParameters(); params.setSourceCharset("x-PICA"); params.setTargetCharset("UTF-8"); params.setAddCollectionHeader(true); params.setAddCollectionFooter(true); c.convert(reader, writer, params); } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: public List<DemandeChargement> getArtistToLoadFromWiki() throws Exception { URL fileURL = new URL("http://beastchild.free.fr/wiki/doku.php?id=music"); URLConnection urlConnection = fileURL.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); String ligne; List<DemandeChargement> dem = new ArrayList<DemandeChargement>(); while ((ligne = br.readLine()) != null) { if (ligne.indexOf("&lt;@@@&gt;") != -1) { String maidS = ligne.substring(ligne.indexOf("&lt;@@@&gt;") + 11, ligne.indexOf("&lt;/@@@&gt;")).trim(); try { long maid = Long.parseLong(maidS); log.info("MAID to load : " + maid); dem.add(new DemandeChargement(maid)); } catch (Exception e) { log.error("Impossible de recuperer le MAID : " + maidS); } } } br.close(); httpStream.close(); return dem; } Code Sample 2: public static File createTempFile(InputStream contentStream, String ext) throws IOException { ExceptionUtils.throwIfNull(contentStream, "contentStream"); File file = File.createTempFile("test", ext); FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copy(contentStream, fos, false); } finally { fos.close(); } return file; }
11
Code Sample 1: private static void copy(String sourceName, String destName) throws IOException { File source = new File(sourceName); File dest = new File(destName); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: @Override protected String getRawPage(String url) throws IOException { HttpClient httpClient = new HttpClient(); String proxyHost = config.getString("proxy.host"), proxyPortString = config.getString("proxy.port"); if (proxyHost != null && proxyPortString != null) { int proxyPort = -1; try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException e) { } if (proxyPort != -1) { httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); } } GetMethod urlGet = new GetMethod(url); urlGet.setRequestHeader("Accept-Encoding", ""); urlGet.setRequestHeader("User-Agent", "Mozilla/5.0"); int retCode; if ((retCode = httpClient.executeMethod(urlGet)) != HttpStatus.SC_OK) { throw new RuntimeException("Unexpected HTTP code: " + retCode); } String encoding = null; Header contentType = urlGet.getResponseHeader("Content-Type"); if (contentType != null) { String contentTypeString = contentType.toString(); int i = contentTypeString.indexOf("charset="); if (i != -1) { encoding = contentTypeString.substring(i + "charset=".length()).trim(); } } boolean gzipped = false; Header contentEncoding = urlGet.getResponseHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { gzipped = true; } byte[] htmlData; try { InputStream in = gzipped ? new GZIPInputStream(urlGet.getResponseBodyAsStream()) : urlGet.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); htmlData = out.toByteArray(); in.close(); } finally { urlGet.releaseConnection(); } if (encoding == null) { Matcher m = Pattern.compile("(?i)<meta[^>]*charset=(([^\"]+\")|(\"[^\"]+\"))").matcher(new String(htmlData)); if (m.find()) { encoding = m.group(1).trim().replace("\"", ""); } } if (encoding == null) { encoding = "UTF-8"; } return new String(htmlData, encoding); }
11
Code Sample 1: public static int gunzipFile(File file_input, File dir_output) { GZIPInputStream gzip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); gzip_in_stream = new GZIPInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } String file_input_name = file_input.getName(); String file_output_name = file_input_name.substring(0, file_input_name.length() - 3); File output_file = new File(dir_output, file_output_name); byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = gzip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } try { gzip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: public he3Decode(String in_file) { try { File out = new File(in_file + extension); File in = new File(in_file); int file_size = (int) in.length(); FileInputStream in_stream = new FileInputStream(in_file); out.createNewFile(); FileOutputStream out_stream = new FileOutputStream(out.getName()); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; int buff_size = byte_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + "decoding: " + in_file + "\n" + "decoding to: " + in_file + extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = in_stream.read(byte_arr, 0, buff_size); if (_chars_read == -1) break; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\ndecoding: "); out_stream.write(_decode((ByteArrayOutputStream) os)); System.out.print("complete\n\n"); } catch (java.io.FileNotFoundException fnfEx) { System.err.println("Exception: " + fnfEx.getMessage()); } catch (java.io.IOException ioEx) { System.err.println("Exception: " + ioEx.getMessage()); } }
11
Code Sample 1: static void copyFile(File file, File destDir) { File destFile = new File(destDir, file.getName()); if (destFile.exists() && (!destFile.canWrite())) { throw new SyncException("Cannot overwrite " + destFile + " because " + "it is read-only"); } try { FileInputStream in = new FileInputStream(file); try { FileOutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new SyncException("I/O error copying " + file + " to " + destDir + " (message: " + e.getMessage() + ")", e); } if (!destFile.setLastModified(file.lastModified())) { throw new SyncException("Could not set last modified timestamp " + "of " + destFile); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private boolean passwordMatches(String user, String plainPassword, String scrambledPassword) { MessageDigest md; byte[] temp_digest, pass_digest; byte[] hex_digest = new byte[35]; byte[] scrambled = scrambledPassword.getBytes(); try { md = MessageDigest.getInstance("MD5"); md.update(plainPassword.getBytes("US-ASCII")); md.update(user.getBytes("US-ASCII")); temp_digest = md.digest(); Utils.bytesToHex(temp_digest, hex_digest, 0); md.update(hex_digest, 0, 32); md.update(salt.getBytes()); pass_digest = md.digest(); Utils.bytesToHex(pass_digest, hex_digest, 3); hex_digest[0] = (byte) 'm'; hex_digest[1] = (byte) 'd'; hex_digest[2] = (byte) '5'; for (int i = 0; i < hex_digest.length; i++) { if (scrambled[i] != hex_digest[i]) { return false; } } } catch (Exception e) { logger.error(e); } return true; } Code Sample 2: public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { } return ""; }
11
Code Sample 1: @Test public void testWrite() throws Exception { MrstkXmlFileReader reader = new MrstkXmlFileReader(); reader.setFileName("..//data//MrstkXML//prototype3.xml"); reader.read(); SpectrumArray sp = reader.getOutput(); File tmp = File.createTempFile("mrstktest", ".xml"); System.out.println("Writing temp file: " + tmp.getAbsolutePath()); MrstkXmlFileWriter writer = new MrstkXmlFileWriter(sp); writer.setFile(tmp); writer.write(); MrstkXmlFileReader reader2 = new MrstkXmlFileReader(); reader2.setFileName(writer.getFile().getAbsolutePath()); reader2.read(); SpectrumArray sp2 = reader2.getOutput(); assertTrue(sp.equals(sp2)); } Code Sample 2: public static boolean copy(File from, File to, Override override) throws IOException { FileInputStream in = null; FileOutputStream out = null; FileChannel srcChannel = null; FileChannel destChannel = null; if (override == null) override = Override.NEWER; switch(override) { case NEVER: if (to.isFile()) return false; break; case NEWER: if (to.isFile() && (from.lastModified() - LASTMODIFIED_DIFF_MILLIS) < to.lastModified()) return false; break; } to.getParentFile().mkdirs(); try { in = new FileInputStream(from); out = new FileOutputStream(to); srcChannel = in.getChannel(); destChannel = out.getChannel(); long position = 0L; long count = srcChannel.size(); while (position < count) { long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); position += destChannel.transferFrom(srcChannel, position, chunk); } to.setLastModified(from.lastModified()); return true; } finally { CommonUtils.close(srcChannel); CommonUtils.close(destChannel); CommonUtils.close(out); CommonUtils.close(in); } }
11
Code Sample 1: protected static String getURLandWriteToDisk(String url, Model retModel) throws MalformedURLException, IOException { String path = null; URL ontURL = new URL(url); InputStream ins = ontURL.openStream(); InputStreamReader bufRead; OutputStreamWriter bufWrite; int offset = 0, read = 0; initModelHash(); if (System.getProperty("user.dir") != null) { String delimiter; path = System.getProperty("user.dir"); if (path.contains("/")) { delimiter = "/"; } else { delimiter = "\\"; } char c = path.charAt(path.length() - 1); if (c == '/' || c == '\\') { path = path.substring(0, path.length() - 2); } path = path.substring(0, path.lastIndexOf(delimiter) + 1); path = path.concat("ontologies" + delimiter + "downloaded"); (new File(path)).mkdir(); path = path.concat(delimiter); path = createFullPath(url, path); bufWrite = new OutputStreamWriter(new FileOutputStream(path)); bufRead = new InputStreamReader(ins); read = bufRead.read(); while (read != -1) { bufWrite.write(read); offset += read; read = bufRead.read(); } bufRead.close(); bufWrite.close(); ins.close(); FileInputStream fs = new FileInputStream(path); retModel.read(fs, ""); } return path; } Code Sample 2: private static void reconfigureDebug() { useFile = false; logValue = 0; String methodString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.method']/@value"); String levelString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.level']/@value"); String quietString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.quiet']/@value"); String fileString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.file']/@value"); String filemodeString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.filemode']/@value"); String calltraceString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.calltrace']/@value"); String rotateTimeoutString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatetimeout']/@value"); String rotateDestString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedest']/@value"); String rotateCompressString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatecompress']/@value"); String rotateDaysString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedays']/@value"); String rotateArchiveString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatearchive']/@value"); String rotateDeleteString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedelete']/@value"); String dirName = "."; if (rotateTimeoutString != null) { rotateTimeout = Integer.parseInt(rotateTimeoutString); } if (rotateDestString != null) { rotateDest = rotateDestString; } if (rotateCompressString != null && rotateCompressString.equalsIgnoreCase("true")) { rotateCompress = true; } if (rotateDaysString != null) { rotateDays = Integer.parseInt(rotateDaysString); } if (rotateArchiveString != null) { rotateArchive = rotateArchiveString; } if (rotateDeleteString != null && rotateDeleteString.equalsIgnoreCase("true")) { rotateDelete = true; } if (fileString != null && fileString.indexOf("/") != -1) { dirName = fileString.substring(0, fileString.lastIndexOf("/")); (new File(dirName)).mkdirs(); } if (methodString != null) { logMethod = methodString; } else { logMethod = "file"; } if (levelString != null) { logValue = Integer.parseInt(levelString); } else { logValue = 0; } if (calltraceString != null && calltraceString.equalsIgnoreCase("true")) { calltrace = true; } else { calltrace = false; } if (logMethod == null) { logMethod = "file"; } if (quietString != null) { if (quietString.equalsIgnoreCase("true")) { beQuiet = true; } } if (logMethod != null) { if (logMethod.equalsIgnoreCase("file")) { if (fileString != null) { logFile = fileString; } else { logFile = "log.txt"; } useFile = true; } } else { System.err.println("*** A debugging method (debug.method) is required in properties file!"); System.err.println("*** Please refer to configuration documentation."); System.exit(-1); } timesRepeated = 0; lastMessage = null; if (useFile) { logfile = new File(logFile); try { if (filemodeString != null && filemodeString.equalsIgnoreCase("append")) { ps = new PrintStream(new FileOutputStream(logfile, true)); } else { ps = new PrintStream(new FileOutputStream(logfile)); } isFile = true; Calendar calendar = new GregorianCalendar(); Date date = calendar.getTime(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); ps.println(); ps.println("--- Log file opened " + format1.format(date) + " ---"); } catch (FileNotFoundException e) { System.out.println("Debug: Unable to instantiate debugger: " + e.getMessage()); System.exit(-1); } catch (Exception e) { System.out.println("Debug: Unable to instantiate debugger - internal error: " + e.getMessage()); System.exit(-1); } } if (!registeredSchedule) { registeredSchedule = true; if (Server.getScheduler() != null) { Server.getScheduler().register("Log File Rotator for '" + logFile + "'", new SchedulerInterface() { public int getScheduleRate() { if (rotateTimeout != 0) { return rotateTimeout / 10; } return 0; } public void handle() { FileChannel srcChannel, destChannel; String destOutFile = logFile + "." + System.currentTimeMillis(); String destOutFileCompressed = logFile + "." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(logFile); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate log file '" + logFile + "': " + e); } } else { try { srcChannel = new FileInputStream(logFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to read log file '" + logFile + "': " + e.getMessage()); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate log file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFile + "'"); } if (rotateDelete && isFile) { try { ps.close(); } catch (Exception e) { } isFile = false; ps = null; (new File(logFile)).delete(); reconfigureDebug(); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(logFile + ".") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } } public String identString() { return "Debug Rotator for logs"; } }); } } }
00
Code Sample 1: public void removeUserFromRealm(final List<NewUser> users) { try { connection.setAutoCommit(false); final List<Integer> removeFromNullRealm = (List<Integer>) new ProcessEnvelope().executeObject(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public Object executeProcessReturnObject() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realm.removeUser")); Iterator<NewUser> iter = users.iterator(); NewUser user; int realmId; Iterator<Integer> iter2; List<Integer> removeFromNullRealm = new ArrayList<Integer>(); while (iter.hasNext()) { user = iter.next(); psImpl.setInt(1, user.userId); iter2 = user.realmIds.iterator(); while (iter2.hasNext()) { realmId = iter2.next(); if (realmId == 0) { removeFromNullRealm.add(user.userId); continue; } psImpl.setInt(2, realmId); psImpl.executeUpdate(); } cmDB.removeUser(user.userId); } return removeFromNullRealm; } }); if (!removeFromNullRealm.isEmpty()) { new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realm.removeUserFromNullRealm")); Iterator<Integer> iter2 = removeFromNullRealm.iterator(); while (iter2.hasNext()) { psImpl.setInt(1, iter2.next()); psImpl.executeUpdate(); } } }); } connection.commit(); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } Code Sample 2: private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0 && !stopped) outFile.write(buf, 0, read); inFile.close(); }
00
Code Sample 1: private void createUser(AddEditUserForm addform, HttpServletRequest request, ActionMapping mapping) throws Exception { MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone(); md.update(addform.getPassword().getBytes("UTF-8")); byte[] pd = md.digest(); StringBuffer app = new StringBuffer(); for (int i = 0; i < pd.length; i++) { String s2 = Integer.toHexString(pd[i] & 0xFF); app.append((s2.length() == 1) ? "0" + s2 : s2); } Session hbsession = HibernateUtil.currentSession(); try { Transaction tx = hbsession.beginTransaction(); NvUsers user = new NvUsers(); user.setLogin(addform.getLogin()); user.setPassword(app.toString()); hbsession.save(user); hbsession.flush(); if (!hbsession.connection().getAutoCommit()) { tx.commit(); } } finally { HibernateUtil.closeSession(); } } Code Sample 2: public static boolean copy(File from, File to, Override override) throws IOException { FileInputStream in = null; FileOutputStream out = null; FileChannel srcChannel = null; FileChannel destChannel = null; if (override == null) override = Override.NEWER; switch(override) { case NEVER: if (to.isFile()) return false; break; case NEWER: if (to.isFile() && (from.lastModified() - LASTMODIFIED_DIFF_MILLIS) < to.lastModified()) return false; break; } to.getParentFile().mkdirs(); try { in = new FileInputStream(from); out = new FileOutputStream(to); srcChannel = in.getChannel(); destChannel = out.getChannel(); long position = 0L; long count = srcChannel.size(); while (position < count) { long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); position += destChannel.transferFrom(srcChannel, position, chunk); } to.setLastModified(from.lastModified()); return true; } finally { CommonUtils.close(srcChannel); CommonUtils.close(destChannel); CommonUtils.close(out); CommonUtils.close(in); } }
11
Code Sample 1: public static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public static void copyFile(String source, String destination) throws IOException { File srcDir = new File(source); File[] files = srcDir.listFiles(); FileChannel in = null; FileChannel out = null; for (File file : files) { try { in = new FileInputStream(file).getChannel(); File outFile = new File(destination, file.getName()); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } }
00
Code Sample 1: protected boolean process(final TranscodeJobImpl job) { TranscodePipe pipe = null; current_job = job; DeviceImpl device = job.getDevice(); device.setTranscoding(true); try { job.starts(); TranscodeProvider provider = job.getProfile().getProvider(); final TranscodeException[] error = { null }; TranscodeProfile profile = job.getProfile(); final TranscodeFileImpl transcode_file = job.getTranscodeFile(); TranscodeProviderAnalysis provider_analysis; boolean xcode_required; if (provider == null) { xcode_required = false; provider_analysis = null; } else { provider_analysis = analyse(job); xcode_required = provider_analysis.getBooleanProperty(TranscodeProviderAnalysis.PT_TRANSCODE_REQUIRED); int tt_req; if (job.isStream()) { tt_req = TranscodeTarget.TRANSCODE_ALWAYS; } else { tt_req = job.getTranscodeRequirement(); if (device instanceof TranscodeTarget) { if (provider_analysis.getLongProperty(TranscodeProviderAnalysis.PT_VIDEO_HEIGHT) == 0) { if (((TranscodeTarget) device).isAudioCompatible(transcode_file)) { tt_req = TranscodeTarget.TRANSCODE_NEVER; } } } } if (tt_req == TranscodeTarget.TRANSCODE_NEVER) { xcode_required = false; } else if (tt_req == TranscodeTarget.TRANSCODE_ALWAYS) { xcode_required = true; provider_analysis.setBooleanProperty(TranscodeProviderAnalysis.PT_FORCE_TRANSCODE, true); } } if (xcode_required) { final AESemaphore xcode_sem = new AESemaphore("xcode:proc"); final TranscodeProviderJob[] provider_job = { null }; TranscodeProviderAdapter xcode_adapter = new TranscodeProviderAdapter() { private boolean resolution_updated; private final int ETA_AVERAGE_SIZE = 10; private int last_eta; private int eta_samples; private Average eta_average = AverageFactory.MovingAverage(ETA_AVERAGE_SIZE); private int last_percent; public void updateProgress(int percent, int eta_secs, int new_width, int new_height) { last_eta = eta_secs; last_percent = percent; TranscodeProviderJob prov_job = provider_job[0]; if (prov_job == null) { return; } int job_state = job.getState(); if (job_state == TranscodeJob.ST_CANCELLED || job_state == TranscodeJob.ST_REMOVED) { prov_job.cancel(); } else if (paused || job_state == TranscodeJob.ST_PAUSED) { prov_job.pause(); } else { if (job_state == TranscodeJob.ST_RUNNING) { prov_job.resume(); } job.updateProgress(percent, eta_secs); prov_job.setMaxBytesPerSecond(max_bytes_per_sec); if (!resolution_updated) { if (new_width > 0 && new_height > 0) { transcode_file.setResolution(new_width, new_height); resolution_updated = true; } } } } public void streamStats(long connect_rate, long write_speed) { if (Constants.isOSX && job.getEnableAutoRetry() && job.canUseDirectInput() && job.getAutoRetryCount() == 0) { if (connect_rate > 5 && last_percent < 100) { long eta = (long) eta_average.update(last_eta); eta_samples++; if (eta_samples >= ETA_AVERAGE_SIZE) { long total_time = (eta * 100) / (100 - last_percent); long total_write = total_time * write_speed; DiskManagerFileInfo file = job.getFile(); long length = file.getLength(); if (length > 0) { double over_write = ((double) total_write) / length; if (over_write > 5.0) { failed(new TranscodeException("Overwrite limit exceeded, abandoning transcode")); provider_job[0].cancel(); } } } } else { eta_samples = 0; } } } public void failed(TranscodeException e) { if (error[0] == null) { error[0] = e; } xcode_sem.release(); } public void complete() { xcode_sem.release(); } }; boolean direct_input = job.useDirectInput(); if (job.isStream()) { pipe = new TranscodePipeStreamSource2(new TranscodePipeStreamSource2.streamListener() { public void gotStream(InputStream is) { job.setStream(is); } }); provider_job[0] = provider.transcode(xcode_adapter, provider_analysis, direct_input, job.getFile(), profile, new URL("tcp://127.0.0.1:" + pipe.getPort())); } else { File output_file = transcode_file.getCacheFile(); provider_job[0] = provider.transcode(xcode_adapter, provider_analysis, direct_input, job.getFile(), profile, output_file.toURI().toURL()); } provider_job[0].setMaxBytesPerSecond(max_bytes_per_sec); TranscodeQueueListener listener = new TranscodeQueueListener() { public void jobAdded(TranscodeJob job) { } public void jobChanged(TranscodeJob changed_job) { if (changed_job == job) { int state = job.getState(); if (state == TranscodeJob.ST_PAUSED) { provider_job[0].pause(); } else if (state == TranscodeJob.ST_RUNNING) { provider_job[0].resume(); } else if (state == TranscodeJob.ST_CANCELLED || state == TranscodeJob.ST_STOPPED) { provider_job[0].cancel(); } } } public void jobRemoved(TranscodeJob removed_job) { if (removed_job == job) { provider_job[0].cancel(); } } }; try { addListener(listener); xcode_sem.reserve(); } finally { removeListener(listener); } if (error[0] != null) { throw (error[0]); } } else { DiskManagerFileInfo source = job.getFile(); transcode_file.setTranscodeRequired(false); if (job.isStream()) { PluginInterface av_pi = PluginInitializer.getDefaultInterface().getPluginManager().getPluginInterfaceByID("azupnpav"); if (av_pi == null) { throw (new TranscodeException("Media Server plugin not found")); } IPCInterface av_ipc = av_pi.getIPC(); String url_str = (String) av_ipc.invoke("getContentURL", new Object[] { source }); if (url_str == null || url_str.length() == 0) { File source_file = source.getFile(); if (source_file.exists()) { job.setStream(new BufferedInputStream(new FileInputStream(source_file))); } else { throw (new TranscodeException("No UPnPAV URL and file doesn't exist")); } } else { URL source_url = new URL(url_str); job.setStream(source_url.openConnection().getInputStream()); } } else { if (device.getAlwaysCacheFiles()) { PluginInterface av_pi = PluginInitializer.getDefaultInterface().getPluginManager().getPluginInterfaceByID("azupnpav"); if (av_pi == null) { throw (new TranscodeException("Media Server plugin not found")); } IPCInterface av_ipc = av_pi.getIPC(); String url_str = (String) av_ipc.invoke("getContentURL", new Object[] { source }); InputStream is; long length; if (url_str == null || url_str.length() == 0) { File source_file = source.getFile(); if (source_file.exists()) { is = new BufferedInputStream(new FileInputStream(source_file)); length = source_file.length(); } else { throw (new TranscodeException("No UPnPAV URL and file doesn't exist")); } } else { URL source_url = new URL(url_str); URLConnection connection = source_url.openConnection(); is = source_url.openConnection().getInputStream(); String s = connection.getHeaderField("content-length"); if (s != null) { length = Long.parseLong(s); } else { length = -1; } } OutputStream os = null; final boolean[] cancel_copy = { false }; TranscodeQueueListener copy_listener = new TranscodeQueueListener() { public void jobAdded(TranscodeJob job) { } public void jobChanged(TranscodeJob changed_job) { if (changed_job == job) { int state = job.getState(); if (state == TranscodeJob.ST_PAUSED) { } else if (state == TranscodeJob.ST_RUNNING) { } else if (state == TranscodeJob.ST_CANCELLED || state == TranscodeJob.ST_STOPPED) { cancel_copy[0] = true; } } } public void jobRemoved(TranscodeJob removed_job) { if (removed_job == job) { cancel_copy[0] = true; } } }; try { addListener(copy_listener); os = new FileOutputStream(transcode_file.getCacheFile()); long total_copied = 0; byte[] buffer = new byte[128 * 1024]; while (true) { if (cancel_copy[0]) { throw (new TranscodeException("Copy cancelled")); } int len = is.read(buffer); if (len <= 0) { break; } os.write(buffer, 0, len); total_copied += len; if (length > 0) { job.updateProgress((int) (total_copied * 100 / length), -1); } total_copied += len; } } finally { try { is.close(); } catch (Throwable e) { Debug.out(e); } try { if (os != null) { os.close(); } } catch (Throwable e) { Debug.out(e); } removeListener(copy_listener); } } } } job.complete(); return (true); } catch (Throwable e) { job.failed(e); e.printStackTrace(); if (!job.isStream() && job.getEnableAutoRetry() && job.getAutoRetryCount() == 0 && job.canUseDirectInput() && !job.useDirectInput()) { log("Auto-retrying transcode with direct input"); job.setUseDirectInput(); job.setAutoRetry(true); queue_sem.release(); } return (false); } finally { if (pipe != null) { pipe.destroy(); } device.setTranscoding(false); current_job = null; } } Code Sample 2: @Test @Ignore public void testToJson() throws IOException { JsonSerializer js = new StreamingJsonSerializer(new ObjectMapper()); BulkOperation op = js.createBulkOperation(createTestData(10000), false); IOUtils.copy(op.getData(), System.out); }
00
Code Sample 1: private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } } Code Sample 2: public static InputStream openRemoteFile(URL urlParam) throws KExceptionClass { InputStream result = null; try { result = urlParam.openStream(); } catch (IOException error) { String message = new String(); message = "No se puede abrir el recurso ["; message += urlParam.toString(); message += "]["; message += error.toString(); message += "]"; throw new KExceptionClass(message, error); } ; return (result); }
11
Code Sample 1: public static void kopirujSoubor(File vstup, File vystup) throws IOException { FileChannel sourceChannel = new FileInputStream(vstup).getChannel(); FileChannel destinationChannel = new FileOutputStream(vystup).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static void main(String[] args) throws IOException { String zipPath = "C:\\test.zip"; CZipInputStream zip_in = null; try { byte[] c = new byte[1024]; int slen; zip_in = new CZipInputStream(new FileInputStream(zipPath), "utf-8"); do { ZipEntry file = zip_in.getNextEntry(); if (file == null) break; String fileName = file.getName(); System.out.println(fileName); String ext = fileName.substring(fileName.lastIndexOf(".")); long seed = new Date(System.currentTimeMillis()).getTime(); String newFileName = Long.toString(seed) + ext; FileOutputStream out = new FileOutputStream(newFileName); while ((slen = zip_in.read(c, 0, c.length)) != -1) out.write(c, 0, slen); out.close(); } while (true); } catch (ZipException zipe) { zipe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { zip_in.close(); } }
11
Code Sample 1: private final boolean copy_to_file_nio(File src, File dst) throws IOException { FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(src).getChannel(); dstChannel = new FileOutputStream(dst).getChannel(); { int safe_max = (64 * 1024 * 1024) / 4; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, safe_max, dstChannel); } } return true; } finally { try { if (srcChannel != null) srcChannel.close(); } catch (IOException e) { Debug.debug(e); } try { if (dstChannel != null) dstChannel.close(); } catch (IOException e) { Debug.debug(e); } } } Code Sample 2: public static FileChannel getFileChannel(Object o) throws IOException { Class c = o.getClass(); try { Method m = c.getMethod("getChannel", null); return (FileChannel) m.invoke(o, null); } catch (IllegalAccessException x) { } catch (NoSuchMethodException x) { } catch (InvocationTargetException x) { if (x.getTargetException() instanceof IOException) throw (IOException) x.getTargetException(); } if (o instanceof FileInputStream) return new MyFileChannelImpl((FileInputStream) o); if (o instanceof FileOutputStream) return new MyFileChannelImpl((FileOutputStream) o); if (o instanceof RandomAccessFile) return new MyFileChannelImpl((RandomAccessFile) o); Assert.UNREACHABLE(o.getClass().toString()); 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]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); } Code Sample 2: private byte[] hash(String data, HashAlg alg) { try { MessageDigest digest = MessageDigest.getInstance(alg.toString()); digest.update(data.getBytes()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { } return null; }
11
Code Sample 1: @Override public boolean identification(String username, String password) { this.getLogger().info(DbUserServiceImpl.class, ">>>identification " + username + "<<<"); try { IFeelerUser user = this.getDbServ().queryFeelerUser(username); if (user == null) { return false; } MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); if (user.getPassword().equals(new String(md5.digest()))) { if (!this.localUUIDList.contains(user.getUuid())) { this.localUUIDList.add(user.getUuid()); } return true; } else { return false; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public boolean check(Object credentials) { String password = (credentials instanceof String) ? (String) credentials : credentials.toString(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] ha1; if (credentials instanceof Credential.MD5) { ha1 = ((Credential.MD5) credentials).getDigest(); } else { md.update(username.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(realm.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(password.getBytes(StringUtil.__ISO_8859_1)); ha1 = md.digest(); } md.reset(); md.update(method.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(uri.getBytes(StringUtil.__ISO_8859_1)); byte[] ha2 = md.digest(); md.update(TypeUtil.toString(ha1, 16).getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(nonce.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(nc.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(cnonce.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(qop.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(TypeUtil.toString(ha2, 16).getBytes(StringUtil.__ISO_8859_1)); byte[] digest = md.digest(); return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response)); } catch (Exception e) { Log.warn(e); } return false; }
00
Code Sample 1: public static boolean insereCapitulo(final Connection con, Capitulo cap, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodCapitulo(con, cap); String text = desc.getTexto().replaceAll("[']", "\""); String titulo = cap.getTitulo().replaceAll("['\"]", ""); String coment = cap.getComentario().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + text + "')"); smt.executeUpdate("INSERT INTO capitulo VALUES(" + cap.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO cap_aut VALUES(" + cap.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "CAPITULO: Database error", JOptionPane.ERROR_MESSAGE); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } } Code Sample 2: @Override public InputStream getInputStream() { String url = resourceURL_; try { return new URL(url).openStream(); } catch (Exception e) { } try { return new FileInputStream("/" + url); } catch (Exception e) { e.printStackTrace(); } return null; }
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 copyFromOffset(long offset, File exe, File cab) throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(exe)); FileOutputStream out = new FileOutputStream(cab); byte[] buffer = new byte[4096]; int bytes_read; in.skipBytes((int) offset); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); in = null; out = null; }
00
Code Sample 1: public void setFlag(Flags.Flag oFlg, boolean bFlg) throws MessagingException { String sColunm; super.setFlag(oFlg, bFlg); if (oFlg.equals(Flags.Flag.ANSWERED)) sColunm = DB.bo_answered; else if (oFlg.equals(Flags.Flag.DELETED)) sColunm = DB.bo_deleted; else if (oFlg.equals(Flags.Flag.DRAFT)) sColunm = DB.bo_draft; else if (oFlg.equals(Flags.Flag.FLAGGED)) sColunm = DB.bo_flagged; else if (oFlg.equals(Flags.Flag.RECENT)) sColunm = DB.bo_recent; else if (oFlg.equals(Flags.Flag.SEEN)) sColunm = DB.bo_seen; else sColunm = null; if (null != sColunm && oFolder instanceof DBFolder) { JDCConnection oConn = null; PreparedStatement oUpdt = null; try { oConn = ((DBFolder) oFolder).getConnection(); String sSQL = "UPDATE " + DB.k_mime_msgs + " SET " + sColunm + "=" + (bFlg ? "1" : "0") + " WHERE " + DB.gu_mimemsg + "='" + getMessageGuid() + "'"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); oUpdt = oConn.prepareStatement(sSQL); oUpdt.executeUpdate(); oUpdt.close(); oUpdt = null; oConn.commit(); oConn = null; } catch (SQLException e) { if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } if (null != oUpdt) { try { oUpdt.close(); } catch (Exception ignore) { } } if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException(e.getMessage(), e); } } } Code Sample 2: public void load(String filename) throws VisbardException { String defaultFilename = VisbardMain.getSettingsDir() + File.separator + DEFAULT_SETTINGS_FILE; File defaultFile = new File(defaultFilename); InputStream settingsInStreamFromFile = null; try { sLogger.info("Loading settings from : " + defaultFilename); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (FileNotFoundException fnf) { sLogger.info("Unable to load custom settings from user's settings directory (" + fnf.getMessage() + "); reverting to default settings"); try { InputStream settingsInStreamFromJar = VisbardMain.class.getClassLoader().getResourceAsStream(filename); FileOutputStream settingsOutStream = new FileOutputStream(defaultFile); int c; while ((c = settingsInStreamFromJar.read()) != -1) settingsOutStream.write(c); settingsInStreamFromJar.close(); settingsOutStream.close(); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (IOException ioe) { sLogger.warn("Unable to copy default settings to user's settings directory (" + ioe.getMessage() + "); using default settings from ViSBARD distribution package"); settingsInStreamFromFile = VisbardMain.class.getClassLoader().getResourceAsStream(filename); } } this.processSettingsFile(settingsInStreamFromFile, filename); }
00
Code Sample 1: public boolean verify(String digest, String password) throws NoSuchAlgorithmException { String alg = null; int size = 0; if (digest.regionMatches(true, 0, "{CRYPT}", 0, 7)) { digest = digest.substring(7); return UnixCrypt.matches(digest, password); } else if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) { digest = digest.substring(5); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) { digest = digest.substring(6); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) { digest = digest.substring(5); alg = "MD5"; size = 16; } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) { digest = digest.substring(6); alg = "MD5"; size = 16; } MessageDigest msgDigest = MessageDigest.getInstance(alg); byte[][] hs = split(Base64.decode(digest.toCharArray()), size); byte[] hash = hs[0]; byte[] salt = hs[1]; msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); return msgDigest.isEqual(hash, pwhash); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } Code Sample 2: public static String getWikiPage(String city) throws MalformedURLException, IOException, ParserConfigurationException, SAXException { String url = "http://api.geonames.org/wikipediaSearch?q=" + city + "&maxRows=1&lang=it&username=lorenzo.abram"; URLConnection conn = new URL(url).openConnection(); InputStream response = conn.getInputStream(); GeonamesHandler handler = new GeonamesHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(response, handler); return handler.getUrl(); }
00
Code Sample 1: @Override public void onClick(View v) { GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation(); int cid = gcl.getCid(); int lac = gcl.getLac(); int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3)); int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5)); try { JSONObject holder = new JSONObject(); holder.put("version", "1.1.0"); holder.put("host", "maps.google.com"); holder.put("request_address", true); JSONArray array = new JSONArray(); JSONObject data = new JSONObject(); data.put("cell_id", cid); data.put("location_area_code", lac); data.put("mobile_country_code", mcc); data.put("mobile_network_code", mnc); array.put(data); holder.put("cell_towers", array); DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.google.com/loc/json"); StringEntity se = new StringEntity(holder.toString()); post.setEntity(se); HttpResponse resp = client.execute(post); HttpEntity entity = resp.getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuffer sb = new StringBuffer(); String result = br.readLine(); while (result != null) { sb.append(result); result = br.readLine(); } JSONObject jsonObject = new JSONObject(sb.toString()); JSONObject jsonObject1 = new JSONObject(jsonObject.getString("location")); getAddress(jsonObject1.getString("latitude"), jsonObject1.getString("longitude")); } catch (Exception e) { } } Code Sample 2: public static void copyFile(File destFile, File src) throws IOException { File destDir = destFile.getParentFile(); File tempFile = new File(destFile + "_tmp"); destDir.mkdirs(); InputStream is = new FileInputStream(src); try { FileOutputStream os = new FileOutputStream(tempFile); try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); } finally { os.close(); } } finally { is.close(); } destFile.delete(); if (!tempFile.renameTo(destFile)) throw new IOException("Unable to rename " + tempFile + " to " + destFile); }
00
Code Sample 1: private String grabInformationFromWeb(String query, String infoName) throws Exception { String result = ""; URL url = new URL(query); HttpURLConnection request = null; request = (HttpURLConnection) url.openConnection(); if (request != null) { InputStream in = url.openStream(); int c = 0; StringBuilder sb = new StringBuilder(); while ((c = in.read()) != -1) { sb = sb.append((char) c); } String s = sb.toString(); result = Utils.getTagValue(s, "<" + infoName + ">", "</" + infoName + ">"); in.close(); } return result; } Code Sample 2: public ClientDTO changePassword(String pMail, String pMdp) { Client vClientBean = null; ClientDTO vClientDTO = null; vClientBean = mClientDao.getClient(pMail); if (vClientBean != null) { MessageDigest vMd5Instance; try { vMd5Instance = MessageDigest.getInstance("MD5"); vMd5Instance.reset(); vMd5Instance.update(pMdp.getBytes()); byte[] vDigest = vMd5Instance.digest(); BigInteger vBigInt = new BigInteger(1, vDigest); String vHashPassword = vBigInt.toString(16); vClientBean.setMdp(vHashPassword); vClientDTO = BeanToDTO.getInstance().createClientDTO(vClientBean); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return vClientDTO; }
11
Code Sample 1: private void downloadResults() { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(System.currentTimeMillis()); String filename = String.format("%s%sresult_%tF.xml", vysledky, File.separator, cal); String EOL = "" + (char) 0x0D + (char) 0x0A; try { LogManager.getInstance().log("Stahuji soubor result.xml a ukl�d�m do vysledky ..."); File f = new File(filename); FileWriter fw = new FileWriter(f); URL url = new URL(Konfigurace.getInstance().getURLvysledkuValidatoru()); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; while ((line = br.readLine()) != null) { fw.write(line + EOL); } fw.write("</vysledky>" + EOL); br.close(); fw.close(); LogManager.getInstance().changeLog("Stahuji soubor result.xml a ukl�d�m do slo�ky vysledky ... OK"); } catch (IOException e) { e.printStackTrace(); LogManager.getInstance().changeLog("Stahuji soubor result.xml a ukl�d�m do slo�ky vysledky ... X"); } } Code Sample 2: private ArrayList<String> loadProperties(String filename) throws DevFailed, IOException { java.net.URL url = getClass().getResource(filename); if (url == null) { Except.throw_exception("LOAD_PROPERTY_FAILED", "URL for property file (" + filename + ") is null !", "PogoProperty.loadProperties()"); return null; } InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ArrayList<String> vs = new ArrayList<String>(); String str; while ((str = br.readLine()) != null) { str = str.trim(); if (!str.startsWith("#")) if (str.length() > 0) vs.add(str); } br.close(); return vs; }
11
Code Sample 1: public void copy(String original, String copy) throws SQLException { try { OutputStream out = openFileOutputStream(copy, false); InputStream in = openFileInputStream(original); IOUtils.copyAndClose(in, out); } catch (IOException e) { throw Message.convertIOException(e, "Can not copy " + original + " to " + copy); } } Code Sample 2: private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; }
11
Code Sample 1: public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } } Code Sample 2: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: @Test public void testGetJarInformation() throws Exception { final URL url1 = getClass().getResource("/fakejars/something"); final URL url2 = getClass().getResource("/fakejars/something-else"); final URL url3 = getClass().getResource("/fakejars/another-thing"); final Map<String, Date> paths = new HashMap<String, Date>(); paths.put(SOMETHING_JAR, new Date(url1.openConnection().getLastModified())); paths.put(SOMETHING_ELSE_JAR, new Date(url2.openConnection().getLastModified())); paths.put(ANOTHER_THING_JAR, new Date(url3.openConnection().getLastModified())); paths.put(NOT_A_JAR, null); context.checking(new Expectations() { { one(servletContext).getResourcePaths(WEB_INF_LIB_PATH); will(returnValue(paths.keySet())); one(servletContext).getResource(SOMETHING_JAR); will(returnValue(url1)); one(servletContext).getResource(SOMETHING_ELSE_JAR); will(returnValue(url2)); one(servletContext).getResource(ANOTHER_THING_JAR); will(returnValue(url3)); } }); final Map<URL, Date> output = new ModulesImpl(servletContext, null, new LoggerProvider()).getJarInformation(); assertThat(output.size(), is(3)); for (final URL url : output.keySet()) { final String jarName = url.toString(); final String key = WEB_INF_LIB_PATH + jarName.substring(jarName.lastIndexOf("/") + 1) + ".jar"; assertThat(output.get(url), is(paths.get(key))); } } Code Sample 2: public static void invokeServlet(String op, String user) throws Exception { boolean isSayHi = true; try { if (!"sayHi".equals(op)) { isSayHi = false; } URL url = new URL("http://localhost:9080/helloworld/*.do"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); out.write("Operation=" + op); if (!isSayHi) { out.write("&User=" + user); } out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); boolean correctReturn = false; String response; if (isSayHi) { while ((response = in.readLine()) != null) { if (response.contains("Bonjour")) { System.out.println(" sayHi server return: Bonjour"); correctReturn = true; break; } } } else { while ((response = in.readLine()) != null) { if (response.contains("Hello CXF")) { System.out.println(" greetMe server return: Hello CXF"); correctReturn = true; break; } } } if (!correctReturn) { System.out.println("Can't got correct return from server."); } in.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: @Test public final void testImportODS() throws Exception { URL url = ODSTableImporterTest.class.getResource("/Messages.ods"); InputStream in = url.openStream(); ODSTableImporter b = new ODSTableImporter(); b.importODS(in, null); assertMessagesOds(b); } Code Sample 2: public static String getUserPass(String user) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(user.getBytes()); byte[] hash = digest.digest(); System.out.println("Returning user pass:" + hash); return hash.toString(); }
11
Code Sample 1: private void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static boolean copyFile(File from, File to) { try { FileChannel fromChannel = new FileInputStream(from).getChannel(); FileChannel toChannel = new FileOutputStream(to).getChannel(); toChannel.transferFrom(fromChannel, 0, fromChannel.size()); fromChannel.close(); toChannel.close(); } catch (IOException e) { log.error("failed to copy " + from.getAbsolutePath() + " to " + to.getAbsolutePath() + ": caught exception", e); return false; } return true; }
00
Code Sample 1: public static void bubble_sort(int[] objects, int len) { for (int i = len; --i >= 0; ) { boolean flipped = false; for (int j = 0; j < i; j++) { if (objects[j + 1] < objects[j]) { int tmp = objects[j]; objects[j] = objects[j + 1]; objects[j + 1] = tmp; flipped = true; } } if (!flipped) return; } } Code Sample 2: public void access() { Authenticator.setDefault(new MyAuthenticator()); try { URL url = new URL("http://localhost/ws/test"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
00
Code Sample 1: @Test public void testWriteAndReadBigger() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwrite.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[body.length()]; int readCount = in.read(buffer); in.close(); assertEquals(body.length(), readCount); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } } 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(); } }
11
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]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); } Code Sample 2: private void copyFile(File s, File d) throws IOException { d.getParentFile().mkdirs(); FileChannel inChannel = new FileInputStream(s).getChannel(); FileChannel outChannel = new FileOutputStream(d).getChannel(); int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } inChannel.close(); outChannel.close(); d.setLastModified(s.lastModified()); }
11
Code Sample 1: public String md5(String password) { MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } m.update(password.getBytes(), 0, password.length()); return new BigInteger(1, m.digest()).toString(16); } Code Sample 2: public void createVendorSignature() { byte b; try { _vendorMessageDigest = MessageDigest.getInstance("MD5"); _vendorSig = Signature.getInstance("MD5/RSA/PKCS#1"); _vendorSig.initSign((PrivateKey) _vendorPrivateKey); _vendorMessageDigest.update(getBankString().getBytes()); _vendorMessageDigestBytes = _vendorMessageDigest.digest(); _vendorSig.update(_vendorMessageDigestBytes); _vendorSignatureBytes = _vendorSig.sign(); } catch (Exception e) { } ; }
11
Code Sample 1: public static KUID createRandomID() { MessageDigestInput randomNumbers = new MessageDigestInput() { public void update(MessageDigest md) { byte[] random = new byte[LENGTH * 2]; GENERATOR.nextBytes(random); md.update(random); } }; MessageDigestInput properties = new MessageDigestInput() { public void update(MessageDigest md) { Properties props = System.getProperties(); try { for (Entry entry : props.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); md.update(key.getBytes("UTF-8")); md.update(value.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }; MessageDigestInput millis = new MessageDigestInput() { public void update(MessageDigest md) { long millis = System.currentTimeMillis(); md.update((byte) ((millis >> 56L) & 0xFFL)); md.update((byte) ((millis >> 48L) & 0xFFL)); md.update((byte) ((millis >> 40L) & 0xFFL)); md.update((byte) ((millis >> 32L) & 0xFFL)); md.update((byte) ((millis >> 24L) & 0xFFL)); md.update((byte) ((millis >> 16L) & 0xFFL)); md.update((byte) ((millis >> 8L) & 0xFFL)); md.update((byte) ((millis) & 0xFFL)); } }; MessageDigestInput nanos = new MessageDigestInput() { public void update(MessageDigest md) { long nanos = System.nanoTime(); md.update((byte) ((nanos >> 56L) & 0xFFL)); md.update((byte) ((nanos >> 48L) & 0xFFL)); md.update((byte) ((nanos >> 40L) & 0xFFL)); md.update((byte) ((nanos >> 32L) & 0xFFL)); md.update((byte) ((nanos >> 24L) & 0xFFL)); md.update((byte) ((nanos >> 16L) & 0xFFL)); md.update((byte) ((nanos >> 8L) & 0xFFL)); md.update((byte) ((nanos) & 0xFFL)); } }; MessageDigestInput[] input = { properties, randomNumbers, millis, nanos }; Arrays.sort(input); try { MessageDigest md = MessageDigest.getInstance("SHA1"); for (MessageDigestInput mdi : input) { mdi.update(md); int hashCode = System.identityHashCode(mdi); md.update((byte) ((hashCode >> 24) & 0xFF)); md.update((byte) ((hashCode >> 16) & 0xFF)); md.update((byte) ((hashCode >> 8) & 0xFF)); md.update((byte) ((hashCode) & 0xFF)); md.update((byte) ((mdi.rnd >> 24) & 0xFF)); md.update((byte) ((mdi.rnd >> 16) & 0xFF)); md.update((byte) ((mdi.rnd >> 8) & 0xFF)); md.update((byte) ((mdi.rnd) & 0xFF)); } return new KUID(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } Code Sample 2: public static String hash(String plaintext) { if (plaintext == null) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); md.update(plaintext.getBytes("UTF-8")); } catch (Exception e) { } return new String(Base64.encodeBase64(md.digest())); }
00
Code Sample 1: private static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); } Code Sample 2: private void readHomePage(ITestThread testThread) throws IOException { if (null == testThread) { throw new IllegalArgumentException("Test thread may not be null."); } final InputStream urlIn = new URL(testUrl).openStream(); final int availableBytes = urlIn.available(); if (0 == availableBytes) { throw new IllegalStateException("Zero bytes on target host."); } in = new BufferedReader(new InputStreamReader(urlIn)); String line; while (null != in && null != (line = in.readLine())) { page.append(line); page.append('\n'); if (0 != lineDelay) { OS.sleep(lineDelay); } if (testThread.isActionStopped()) { break; } } }
00
Code Sample 1: private void updateService(int nodeID, String interfaceIP, int serviceID, String notifyFlag) throws ServletException { Connection connection = null; final DBUtils d = new DBUtils(getClass()); try { connection = Vault.getDbConnection(); d.watch(connection); PreparedStatement stmt = connection.prepareStatement(UPDATE_SERVICE); d.watch(stmt); stmt.setString(1, notifyFlag); stmt.setInt(2, nodeID); stmt.setString(3, interfaceIP); stmt.setInt(4, serviceID); stmt.executeUpdate(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException sqlEx) { throw new ServletException("Couldn't roll back update to service " + serviceID + " on interface " + interfaceIP + " notify as " + notifyFlag + " in the database.", sqlEx); } throw new ServletException("Error when updating to service " + serviceID + " on interface " + interfaceIP + " notify as " + notifyFlag + " in the database.", e); } finally { d.cleanUp(); } } Code Sample 2: @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getJarFileURL", args = { }) public void test_getJarFileURL() throws Exception { URL u = createContent("lf.jar", "plus.bmp"); URL fileURL = new URL(u.getPath().substring(0, u.getPath().indexOf("!"))); juc = (JarURLConnection) u.openConnection(); assertTrue("Returned incorrect file URL", juc.getJarFileURL().equals(fileURL)); URL url = new URL("jar:file:///bar.jar!/foo.jar!/Bugs/HelloWorld.class"); assertEquals("file:/bar.jar", ((JarURLConnection) url.openConnection()).getJarFileURL().toString()); }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(128); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(32); for (int j = 0; j < array.length; ++j) { int b = array[j] & TWO_BYTES; if (b < PAD_BELOW) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { } } Code Sample 2: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: private static void download(String urlString) throws IOException { URL url = new URL(urlString); url = handleRedirectUrl(url); URLConnection cn = url.openConnection(); Utils.setHeader(cn); long fileLength = cn.getContentLength(); Statics.getInstance().setFileLength(fileLength); long packageLength = fileLength / THREAD_COUNT; long leftLength = fileLength % THREAD_COUNT; String fileName = Utils.decodeURLFileName(url); RandomAccessFile file = new RandomAccessFile(fileName, "rw"); System.out.println("File: " + fileName + ", Size: " + Utils.calSize(fileLength)); CountDownLatch latch = new CountDownLatch(THREAD_COUNT + 1); long pos = 0; for (int i = 0; i < THREAD_COUNT; i++) { long endPos = pos + packageLength; if (leftLength > 0) { endPos++; leftLength--; } new Thread(new DownloadThread(latch, url, file, pos, endPos)).start(); pos = endPos; } new Thread(new MoniterThread(latch)).start(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } Code Sample 2: @Test public void testXMLDBURLStreamHandler() { System.out.println("testXMLDBURLStreamHandler"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { URL url = new URL(XMLDB_URL_1); InputStream is = url.openStream(); copyDocument(is, baos); is.close(); } catch (Exception ex) { ex.printStackTrace(); LOG.error(ex); fail(ex.getMessage()); } }
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: public static final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } }
11
Code Sample 1: public static void makeLPKFile(String[] srcFilePath, String makeFilePath, LPKHeader header) { FileOutputStream os = null; DataOutputStream dos = null; try { LPKTable[] fileTable = new LPKTable[srcFilePath.length]; long fileOffset = outputOffset(header); for (int i = 0; i < srcFilePath.length; i++) { String sourceFileName = FileUtils.getFileName(srcFilePath[i]); long sourceFileSize = FileUtils.getFileSize(srcFilePath[i]); LPKTable ft = makeLPKTable(sourceFileName, sourceFileSize, fileOffset); fileOffset = outputNextOffset(sourceFileSize, fileOffset); fileTable[i] = ft; } File file = new File(makeFilePath); if (!file.exists()) { FileUtils.makedirs(file); } os = new FileOutputStream(file); dos = new DataOutputStream(os); dos.writeInt(header.getPAKIdentity()); writeByteArray(header.getPassword(), dos); dos.writeFloat(header.getVersion()); dos.writeLong(header.getTables()); for (int i = 0; i < fileTable.length; i++) { writeByteArray(fileTable[i].getFileName(), dos); dos.writeLong(fileTable[i].getFileSize()); dos.writeLong(fileTable[i].getOffSet()); } for (int i = 0; i < fileTable.length; i++) { File ftFile = new File(srcFilePath[i]); FileInputStream ftFis = new FileInputStream(ftFile); DataInputStream ftDis = new DataInputStream(ftFis); byte[] buff = new byte[256]; int readLength = 0; while ((readLength = ftDis.read(buff)) != -1) { makeBuffer(buff, readLength); dos.write(buff, 0, readLength); } ftDis.close(); ftFis.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (dos != null) { try { dos.close(); dos = null; } catch (IOException e) { } } } } Code Sample 2: private static File createTempWebXml(Class portletClass, File portletDir, String appName, String portletName) throws IOException, FileNotFoundException { File pathToWebInf = new File(portletDir, "WEB-INF"); File tempWebXml = File.createTempFile("web", ".xml", pathToWebInf); tempWebXml.deleteOnExit(); OutputStream webOutputStream = new FileOutputStream(tempWebXml); PortletUnitWebXmlStream streamSource = WEB_XML_STREAM_FACTORY; IOUtils.copy(streamSource.createStream(portletClass, appName, portletName), webOutputStream); webOutputStream.close(); return tempWebXml; }
11
Code Sample 1: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (destFile.getParentFile() != null && !destFile.getParentFile().mkdirs()) { LOG.error("GeneralHelper.copyFile(): Cannot create parent directories from " + destFile); } FileInputStream fIn = null; FileOutputStream fOut = null; FileChannel source = null; FileChannel destination = null; try { fIn = new FileInputStream(sourceFile); source = fIn.getChannel(); fOut = new FileOutputStream(destFile); destination = fOut.getChannel(); long transfered = 0; final long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } } finally { if (source != null) { source.close(); } else if (fIn != null) { fIn.close(); } if (destination != null) { destination.close(); } else if (fOut != null) { fOut.close(); } } } Code Sample 2: public String getClass(EmeraldjbBean eb) throws EmeraldjbException { Entity entity = (Entity) eb; StringBuffer sb = new StringBuffer(); String myPackage = getPackageName(eb); sb.append("package " + myPackage + ";\n"); sb.append("\n"); DaoValuesGenerator valgen = new DaoValuesGenerator(); String values_class_name = valgen.getClassName(entity); sb.append("\n"); List importList = new Vector(); importList.add("java.io.FileOutputStream;"); importList.add("java.io.FileInputStream;"); importList.add("java.io.DataInputStream;"); importList.add("java.io.DataOutputStream;"); importList.add("java.io.IOException;"); importList.add("java.sql.Date;"); importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";"); Iterator it = importList.iterator(); while (it.hasNext()) { String importName = (String) it.next(); sb.append("import " + importName + "\n"); } sb.append("\n"); String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1"); String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + "\n"); sb.append("{" + "\n public static final int PROTO_VERSION=" + proto_version + ";"); sb.append("\n\n"); StringBuffer f_writer = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); while (it.hasNext()) { Member member = (Member) it.next(); String nm = member.getName(); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()")); f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter)); } String reader_vars = ""; sb.append("\n public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileOutputStream fos = new FileOutputStream(file_nm);" + "\n DataOutputStream dos = new DataOutputStream(fos);" + "\n writeStream(dos, obj);" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n {" + "\n if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n FileInputStream fis = new FileInputStream(file_nm);" + "\n DataInputStream dis = new DataInputStream(fis);" + "\n readStream(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n dos.writeByte(PROTO_VERSION);" + "\n " + f_writer + "\n } // end of writeStream" + "\n" + "\n public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + "\n int proto_version = din.readByte();" + "\n if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n } // end of readStream" + "\n" + "\n public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n {" + reader_vars + f_reader + "\n } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"); return sb.toString(); }
11
Code Sample 1: public static byte[] SHA1byte(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return sha1hash; } Code Sample 2: private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
00
Code Sample 1: public void connect(String method, String data, String urlString, Properties properties, boolean allowredirect) throws Exception { if (urlString != null) { try { url_ = new URL(url_, urlString); } catch (Exception e) { throw new Exception("Invalid URL"); } } try { httpURLConnection_ = (HttpURLConnection) url_.openConnection(siteThread_.getProxy()); httpURLConnection_.setDoInput(true); httpURLConnection_.setDoOutput(true); httpURLConnection_.setUseCaches(false); httpURLConnection_.setRequestMethod(method); httpURLConnection_.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); httpURLConnection_.setInstanceFollowRedirects(allowredirect); if (properties != null) { for (Object propertyKey : properties.keySet()) { String propertyValue = properties.getProperty((String) propertyKey); if (propertyValue.equalsIgnoreCase("Content-Length")) { httpURLConnection_.setFixedLengthStreamingMode(0); } httpURLConnection_.setRequestProperty((String) propertyKey, propertyValue); } } int connectTimeout = httpURLConnection_.getConnectTimeout(); if (data != null) { post(data); } httpURLConnection_.connect(); } catch (Exception e) { throw new Exception("Connection failed with url " + url_); } } Code Sample 2: public ChatClient registerPlayer(int playerId, String playerLogin) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(playerLogin.getBytes("UTF-8"), 0, playerLogin.length()); byte[] accountToken = md.digest(); byte[] token = generateToken(accountToken); ChatClient chatClient = new ChatClient(playerId, token); players.put(playerId, chatClient); return chatClient; }
00
Code Sample 1: private synchronized void persist() { Connection conn = null; try { PoolManager pm = PoolManager.getInstance(); conn = pm.getConnection(JukeXTrackStore.DB_NAME); conn.setAutoCommit(false); Statement state = conn.createStatement(); state.executeUpdate("DELETE FROM PlaylistEntry WHERE playlistid=" + this.id); if (this.size() > 0) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO PlaylistEntry ( playlistid , trackid , position ) VALUES "); int location = 0; Iterator i = ll.iterator(); while (i.hasNext()) { long currTrackID = ((DatabaseObject) i.next()).getId(); sql.append('(').append(this.id).append(',').append(currTrackID).append(',').append(location++).append(')'); if (i.hasNext()) sql.append(','); } state.executeUpdate(sql.toString()); } conn.commit(); conn.setAutoCommit(true); state.close(); } catch (SQLException se) { try { conn.rollback(); } catch (SQLException ignore) { } log.error("Encountered an error persisting a playlist", se); } finally { try { conn.close(); } catch (SQLException ignore) { } } } Code Sample 2: public static final String getContent(String address) { String content = ""; OutputStream out = null; URLConnection conn = null; InputStream in = null; try { URL url = new URL(address); out = new ByteArrayOutputStream(); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); } content = out.toString(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } return content; }
11
Code Sample 1: public static String getStringFromInputStream(InputStream in) throws Exception { CachedOutputStream bos = new CachedOutputStream(); IOUtils.copy(in, bos); in.close(); bos.close(); return bos.getOut().toString(); } Code Sample 2: public void getFile(OutputStream output, Fragment fragment) throws Exception { Assert.Arg.notNull(output, "output"); Assert.Arg.notNull(fragment, "fragment"); Assert.Arg.notNull(fragment.getId(), "fragment.getId()"); if (this.delegate != null) { this.delegate.getFile(output, fragment); return; } ensureBaseDirectoryCreated(); File filePath = getFragmentFilePath(fragment); InputStream input = FileUtils.openInputStream(filePath); try { IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(input); } }
11
Code Sample 1: public void covertFile(File file) throws IOException { if (!file.isFile()) { return; } Reader reader = null; OutputStream os = null; File newfile = null; String filename = file.getName(); boolean succeed = false; try { newfile = new File(file.getParentFile(), filename + ".bak"); reader = new InputStreamReader(new FileInputStream(file), fromEncoding); os = new FileOutputStream(newfile); IOUtils.copy(reader, os, toEncoding); } catch (Exception e) { e.printStackTrace(); throw new IOException("Encoding error for file [" + file.getAbsolutePath() + "]"); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (Exception e) { e.printStackTrace(); } } } try { file.delete(); succeed = newfile.renameTo(file); } catch (Exception e) { throw new IOException("Clear bak error for file [" + file.getAbsolutePath() + "]"); } if (succeed) { System.out.println("Changed encoding for file [" + file.getAbsolutePath() + "]"); } } Code Sample 2: private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } }
11
Code Sample 1: private String encode(String arg) { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(arg.getBytes()); byte[] md5sum = digest.digest(); final BigInteger bigInt = new BigInteger(1, md5sum); final String output = bigInt.toString(16); return output; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 required: " + e.getMessage(), e); } } Code Sample 2: public static String getDigest(String seed, byte[] code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } }
11
Code Sample 1: public void copyTo(String newname) throws IOException { FileChannel srcChannel = new FileInputStream(dosname).getChannel(); FileChannel dstChannel = new FileOutputStream(newname).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public static void main(String args[]) throws IOException, TrimmerException, DataStoreException { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("ace", "path to ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("phd", "path to phd file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("out", "path to new ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("min_sanger", "min sanger end coveage default =" + DEFAULT_MIN_SANGER_END_CLONE_CVG).build()); options.addOption(new CommandLineOptionBuilder("min_biDriection", "min bi directional end coveage default =" + DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE).build()); options.addOption(new CommandLineOptionBuilder("ignore_threshold", "min end coveage threshold to stop trying to trim default =" + DEFAULT_IGNORE_END_CVG_THRESHOLD).build()); CommandLine commandLine; PhdDataStore phdDataStore = null; AceContigDataStore datastore = null; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int minSangerEndCloneCoverage = commandLine.hasOption("min_sanger") ? Integer.parseInt(commandLine.getOptionValue("min_sanger")) : DEFAULT_MIN_SANGER_END_CLONE_CVG; int minBiDirectionalEndCoverage = commandLine.hasOption("min_biDriection") ? Integer.parseInt(commandLine.getOptionValue("min_biDriection")) : DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE; int ignoreThresholdEndCoverage = commandLine.hasOption("ignore_threshold") ? Integer.parseInt(commandLine.getOptionValue("ignore_threshold")) : DEFAULT_IGNORE_END_CVG_THRESHOLD; AceContigTrimmer trimmer = new NextGenClosureAceContigTrimmer(minSangerEndCloneCoverage, minBiDirectionalEndCoverage, ignoreThresholdEndCoverage); File aceFile = new File(commandLine.getOptionValue("ace")); File phdFile = new File(commandLine.getOptionValue("phd")); phdDataStore = new DefaultPhdFileDataStore(phdFile); datastore = new IndexedAceFileDataStore(aceFile); File tempFile = File.createTempFile("nextGenClosureAceTrimmer", ".ace"); tempFile.deleteOnExit(); OutputStream tempOut = new FileOutputStream(tempFile); int numberOfContigs = 0; int numberOfTotalReads = 0; for (AceContig contig : datastore) { AceContig trimmedAceContig = trimmer.trimContig(contig); if (trimmedAceContig != null) { numberOfContigs++; numberOfTotalReads += trimmedAceContig.getNumberOfReads(); AceFileWriter.writeAceFile(trimmedAceContig, phdDataStore, tempOut); } } IOUtil.closeAndIgnoreErrors(tempOut); OutputStream masterAceOut = new FileOutputStream(new File(commandLine.getOptionValue("out"))); masterAceOut.write(String.format("AS %d %d%n", numberOfContigs, numberOfTotalReads).getBytes()); InputStream tempInput = new FileInputStream(tempFile); IOUtils.copy(tempInput, masterAceOut); } catch (ParseException e) { System.err.println(e.getMessage()); printHelp(options); } finally { IOUtil.closeAndIgnoreErrors(phdDataStore, datastore); } }
00
Code Sample 1: public static void copy(String a, String b) throws IOException { File inputFile = new File(a); File outputFile = new File(b); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public static String rename_tag(String sessionid, String originalTag, String newTagName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_tag"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_tag")); nameValuePairs.add(new BasicNameValuePair("new_tag_name", newTagName)); nameValuePairs.add(new BasicNameValuePair("absolute_tag", originalTag)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
11
Code Sample 1: private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; } Code Sample 2: protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { Session session = HibernateUtil.getInstance().getSession(); response.setBufferSize(65536); ServletOutputStream outStream = response.getOutputStream(); File file = null; FileData fileData = null; try { String fileParameter = request.getParameter("file"); String disposition = request.getParameter("disposition"); if (fileParameter == null || fileParameter.equals("")) { String pi = request.getPathInfo(); int lastSlashIndex = pi.lastIndexOf("/") + 1; fileParameter = pi.substring(lastSlashIndex, pi.indexOf("_", pi.lastIndexOf("/"))); } if (fileParameter == null || fileParameter.equals("")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.flushBuffer(); Logger.log("file parameter not specified"); return; } if (disposition == null || disposition.equals("")) { String pi = request.getPathInfo(); String filename = pi.substring(pi.lastIndexOf("/") + 1); int underscoreIndex = filename.indexOf("_") + 1; disposition = filename.substring(underscoreIndex, filename.indexOf("_", underscoreIndex)); } file = (File) session.load(File.class, new Long(fileParameter)); Logger.log("Content requested=" + file.getName() + ":" + fileParameter + " Referral: " + request.getParameter("referer")); long ifModifiedSince = request.getDateHeader("If-Modified-Since"); long fileDate = file.getLastModifiedDate() - (file.getLastModifiedDate() % 1000); if (fileDate <= ifModifiedSince) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } response.setContentType(file.getContentType()); response.setHeader("Content-Description", file.getName()); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); response.flushBuffer(); Logger.log("Conditional GET: " + file.getName()); return; } User authUser = baseService.getAuthenticatedUser(session, request, response); if (!SecurityHelper.doesUserHavePermission(session, authUser, file, Permission.PERM.READ)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.flushBuffer(); Logger.log("Forbidden content requested: " + fileParameter); return; } String contentType = file.getContentType(); response.setContentType(contentType); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } String name = file.getName(); response.setHeader("Content-Description", name); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); java.io.File possibleDataFile = new java.io.File(BaseSystem.getTempDir() + file.getNameOnDisk()); if (possibleDataFile.exists()) { Logger.log("File exists in " + BaseSystem.getTempDir() + " pulling " + possibleDataFile.getName()); FileInputStream fileInputStream = new FileInputStream(possibleDataFile); try { IOUtils.copy(fileInputStream, outStream); } finally { try { fileInputStream.close(); } catch (Throwable t) { } } } else { List<FileData> fileDataList = HibernateUtil.getInstance().executeQuery(session, "from " + FileData.class.getSimpleName() + " where permissibleObject.id = " + file.getId()); if (fileDataList.size() == 0) { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); Logger.log("Requested content not found: " + fileParameter); response.flushBuffer(); return; } fileData = (FileData) fileDataList.get(0); FileOutputStream fileOutputStream = null; try { java.io.File tmpDir = new java.io.File(BaseSystem.getTempDir()); tmpDir.mkdirs(); fileOutputStream = new FileOutputStream(possibleDataFile); IOUtils.write(fileData.getData(), fileOutputStream); } catch (Throwable t) { Logger.log(t); } finally { try { fileOutputStream.close(); } catch (Throwable t) { } } IOUtils.write(fileData.getData(), outStream); } } catch (Throwable t) { Logger.log(t); try { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.flushBuffer(); } catch (Throwable tt) { } try { response.reset(); response.resetBuffer(); } catch (Throwable tt) { } } finally { file = null; fileData = null; try { outStream.flush(); } catch (Throwable t) { } try { outStream.close(); } catch (Throwable t) { } try { session.close(); } catch (Throwable t) { } } }
11
Code Sample 1: public static void unzipFile(File zipFile, File destFile, boolean removeSrcFile) throws Exception { ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipentry = zipinputstream.getNextEntry(); int BUFFER_SIZE = 4096; while (zipentry != null) { String entryName = zipentry.getName(); log.info("<<<<<< ZipUtility.unzipFile - Extracting: " + zipentry.getName()); File newFile = null; if (destFile.isDirectory()) newFile = new File(destFile, entryName); else newFile = destFile; if (zipentry.isDirectory() || entryName.endsWith(File.separator + ".")) { newFile.mkdirs(); } else { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); byte[] bufferArray = buffer.array(); FileUtilities.createDirectory(newFile.getParentFile()); FileChannel destinationChannel = new FileOutputStream(newFile).getChannel(); while (true) { buffer.clear(); int lim = zipinputstream.read(bufferArray); if (lim == -1) break; buffer.flip(); buffer.limit(lim); destinationChannel.write(buffer); } destinationChannel.close(); zipinputstream.closeEntry(); } zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); if (removeSrcFile) { if (zipFile.exists()) zipFile.delete(); } } Code Sample 2: public void covertFile(File file) throws IOException { if (!file.isFile()) { return; } Reader reader = null; OutputStream os = null; File newfile = null; String filename = file.getName(); boolean succeed = false; try { newfile = new File(file.getParentFile(), filename + ".bak"); reader = new InputStreamReader(new FileInputStream(file), fromEncoding); os = new FileOutputStream(newfile); IOUtils.copy(reader, os, toEncoding); } catch (Exception e) { e.printStackTrace(); throw new IOException("Encoding error for file [" + file.getAbsolutePath() + "]"); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (Exception e) { e.printStackTrace(); } } } try { file.delete(); succeed = newfile.renameTo(file); } catch (Exception e) { throw new IOException("Clear bak error for file [" + file.getAbsolutePath() + "]"); } if (succeed) { System.out.println("Changed encoding for file [" + file.getAbsolutePath() + "]"); } }
00
Code Sample 1: private byte[] getMergedContent(List names, ServletContext servletContext) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (Iterator iterator = names.iterator(); iterator.hasNext(); ) { String path = (String) iterator.next(); if (!path.startsWith("/")) path = "/" + path; URL url = servletContext.getResource(path); if (url == null) url = getClass().getResource(path); if (url == null) throw new IOException("The resources '" + path + "' could not be found neither in the webapp folder nor in a jar"); log.debug("Merging content of group : " + getName()); InputStream inputStream = url.openStream(); InputStreamReader r = new InputStreamReader(inputStream); IOUtils.copy(r, baos, "ASCII"); baos.write((byte) '\n'); inputStream.close(); } baos.close(); return baos.toByteArray(); } Code Sample 2: public void run() { counter = 0; Log.debug("Fetching news"); Session session = botService.getSession(); if (session == null) { Log.warn("No current IRC session"); return; } final List<Channel> channels = session.getChannels(); if (channels.isEmpty()) { Log.warn("No channel for the current IRC session"); return; } if (StringUtils.isEmpty(feedURL)) { Log.warn("No feed provided"); return; } Log.debug("Creating feedListener"); FeedParserListener feedParserListener = new DefaultFeedParserListener() { public void onChannel(FeedParserState state, String title, String link, String description) throws FeedParserException { Log.debug("onChannel:" + title + "," + link + "," + description); } public void onItem(FeedParserState state, String title, String link, String description, String permalink) throws FeedParserException { if (counter >= MAX_FEEDS) { throw new FeedPollerCancelException("Maximum number of items reached"); } boolean canAnnounce = false; try { if (lastDigest == null) { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); lastDigest = md.digest(); canAnnounce = true; } else { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); byte[] currentDigest = md.digest(); if (!MessageDigest.isEqual(currentDigest, lastDigest)) { lastDigest = currentDigest; canAnnounce = true; } } if (canAnnounce) { String shortTitle = title; if (shortTitle.length() > TITLE_MAX_LEN) { shortTitle = shortTitle.substring(0, TITLE_MAX_LEN) + " ..."; } String shortLink = IOUtil.getTinyUrl(link); Log.debug("Link:" + shortLink); for (Channel channel : channels) { channel.say(String.format("%s, %s", shortTitle, shortLink)); } } } catch (Exception e) { throw new FeedParserException(e); } counter++; } public void onCreated(FeedParserState state, Date date) throws FeedParserException { } }; if (parser != null) { InputStream is = null; try { Log.debug("Reading feedURL"); is = new URL(feedURL).openStream(); parser.parse(feedParserListener, is, feedURL); Log.debug("Parsing done"); } catch (IOException ioe) { Log.error(ioe.getMessage(), ioe); } catch (FeedPollerCancelException fpce) { } catch (FeedParserException e) { for (Channel channel : channels) { channel.say(e.getMessage()); } } finally { IOUtil.closeQuietly(is); } } else { Log.warn("Wasn't able to create feed parser"); } }
11
Code Sample 1: public static String getPasswordHash(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes()); byte[] byteData = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { logger.log(Level.SEVERE, "Unknow error in hashing password", e); return "Unknow error, check system log"; } } Code Sample 2: private String md5(String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
11
Code Sample 1: private boolean writeResource(PluginProxy eclipseInstallPlugin, ResourceProxy translation, LocaleProxy locale) throws Exception { String translationResourceName = determineTranslatedResourceName(translation, locale); String pluginNameInDirFormat = eclipseInstallPlugin.getName().replace(Messages.getString("Characters_period"), File.separator); if (translation.getRelativePath().contains(pluginNameInDirFormat)) { return writeResourceToBundleClasspath(translation, locale); } else if (translationResourceName.contains(File.separator)) { String resourcePath = translationResourceName.substring(0, translationResourceName.lastIndexOf(File.separatorChar)); File resourcePathDirectory = new File(directory.getPath() + File.separatorChar + resourcePath); resourcePathDirectory.mkdirs(); } File fragmentResource = new File(directory.getPath() + File.separatorChar + translationResourceName); File translatedResource = new File(translation.getFileResource().getAbsolutePath()); FileChannel inputChannel = new FileInputStream(translatedResource).getChannel(); FileChannel outputChannel = new FileOutputStream(fragmentResource).getChannel(); inputChannel.transferTo(0, inputChannel.size(), outputChannel); inputChannel.close(); outputChannel.close(); return true; } Code Sample 2: @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String fileName = request.getParameter("tegsoftFileName"); if (fileName.startsWith("Tegsoft_BACKUP_")) { fileName = fileName.substring("Tegsoft_BACKUP_".length()); String targetFileName = "/home/customer/" + fileName; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTMODULES")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTMODULES.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (fileName.equals("Tegsoft_ASTSBIN")) { String targetFileName = tobeHome + "/setup/Tegsoft_ASTSBIN.tgz"; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(targetFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); return; } if (!fileName.startsWith("Tegsoft_")) { return; } if (!fileName.endsWith(".zip")) { return; } if (fileName.indexOf("_") < 0) { return; } fileName = fileName.substring(fileName.indexOf("_") + 1); if (fileName.indexOf("_") < 0) { return; } String fileType = fileName.substring(0, fileName.indexOf("_")); String destinationFileName = tobeHome + "/setup/Tegsoft_" + fileName; if (!new File(destinationFileName).exists()) { if ("FORMS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/forms", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("IMAGES".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/image", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("VIDEOS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/videos", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("TEGSOFTJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tegsoft", "jar"); } else if ("TOBEJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName, "Tobe", "jar"); } else if ("ALLJARS".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/WEB-INF/lib/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("DB".equals(fileType)) { FileUtil.createZipPackage(tobeHome + "/sql", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGSERVICE".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/init.d/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGSCRIPTS".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/root/", tobeHome + "/setup/Tegsoft_" + fileName, "tegsoft", null); } else if ("CONFIGFOP".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/fop/", tobeHome + "/setup/Tegsoft_" + fileName); } else if ("CONFIGASTERISK".equals(fileType)) { FileUtil.createZipPackage("/tegsoft/src/java/TegsoftTelecom/configFiles/asterisk/", tobeHome + "/setup/Tegsoft_" + fileName); } } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); FileInputStream is = new FileInputStream(destinationFileName); IOUtils.copy(is, response.getOutputStream()); is.close(); } catch (Exception ex) { ex.printStackTrace(); } }
00
Code Sample 1: public static String convertToSha1(final String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: private InputStream getInputStream(final String pUrlStr) throws IOException { URL url; int responseCode; String encoding; url = new URL(pUrlStr); myActiveConnection = (HttpURLConnection) url.openConnection(); myActiveConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); responseCode = myActiveConnection.getResponseCode(); if (responseCode != RESPONSECODE_OK) { String message; String apiErrorMessage; apiErrorMessage = myActiveConnection.getHeaderField("Error"); if (apiErrorMessage != null) { message = "Received API HTTP response code " + responseCode + " with message \"" + apiErrorMessage + "\" for URL \"" + pUrlStr + "\"."; } else { message = "Received API HTTP response code " + responseCode + " for URL \"" + pUrlStr + "\"."; } throw new OsmosisRuntimeException(message); } myActiveConnection.setConnectTimeout(TIMEOUT); encoding = myActiveConnection.getContentEncoding(); responseStream = myActiveConnection.getInputStream(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { responseStream = new GZIPInputStream(responseStream); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { responseStream = new InflaterInputStream(responseStream, new Inflater(true)); } return responseStream; }
00
Code Sample 1: public static InputStream getResourceAsStream(String resourceName) { try { URL url = getEmbeddedFileUrl(WS_SEP + resourceName); if (url != null) { return url.openStream(); } } catch (MalformedURLException e) { GdtAndroidPlugin.getLogger().logError(e, "Failed to read stream '%s'", resourceName); } catch (IOException e) { GdtAndroidPlugin.getLogger().logError(e, "Failed to read stream '%s'", resourceName); } return null; } Code Sample 2: public GeocodeResponse getGKCoordinateFromAddress(SearchAddressRequest searchAddressRequest) { GeocodeResponse result = null; String adress = null; if (searchAddressRequest.getAdressTextField() != null) adress = searchAddressRequest.getAdressTextField().getText(); if (adress == null || adress.length() == 0) adress = " "; String postRequest = ""; postRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" + "<xls:XLS xmlns:xls=\"http://www.opengis.net/xls\" xmlns:sch=\"http://www.ascc.net/xml/schematron\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/xls \n" + "http://gdi3d.giub.uni-bonn.de:8080/openls-lus/schemas/LocationUtilityService.xsd\" version=\"1.1\"> \n" + " <xls:RequestHeader srsName=\"EPSG:" + Navigator.getEpsg_code() + "\"/> \n" + " <xls:Request methodName=\"GeocodeRequest\" requestID=\"123456789\" version=\"1.1\"> \n" + " <xls:GeocodeRequest> \n" + " <xls:Address countryCode=\"DE\"> \n" + " <xls:freeFormAddress>" + adress + "</xls:freeFormAddress> \n" + " </xls:Address> \n" + " </xls:GeocodeRequest> \n" + " </xls:Request> \n" + "</xls:XLS> \n"; if (Navigator.isVerbose()) { System.out.println("OpenLSGeocoder postRequest " + postRequest); } String errorMessage = ""; try { System.out.println("contacting " + serviceEndPoint); URL u = new URL(serviceEndPoint); HttpURLConnection urlc = (HttpURLConnection) u.openConnection(); urlc.setReadTimeout(Navigator.TIME_OUT); urlc.setAllowUserInteraction(false); urlc.setRequestMethod("POST"); urlc.setRequestProperty("Content-Type", "application/xml"); urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); PrintWriter xmlOut = null; xmlOut = new java.io.PrintWriter(urlc.getOutputStream()); xmlOut.write(postRequest); xmlOut.flush(); xmlOut.close(); InputStream is = urlc.getInputStream(); result = new GeocodeResponse(); XLSDocument xlsResponse = XLSDocument.Factory.parse(is); XLSType xlsTypeResponse = xlsResponse.getXLS(); Node node0 = xlsTypeResponse.getDomNode(); NodeList nodes1 = node0.getChildNodes(); for (int i = 0; i < nodes1.getLength(); i++) { Node node1 = nodes1.item(i); NodeList nodes2 = node1.getChildNodes(); for (int j = 0; j < nodes2.getLength(); j++) { Node node2 = nodes2.item(j); NodeList nodes3 = node2.getChildNodes(); for (int k = 0; k < nodes3.getLength(); k++) { Node node3 = nodes3.item(k); String nodeName = node3.getNodeName(); if (nodeName.equalsIgnoreCase("xls:GeocodeResponseList")) { net.opengis.xls.GeocodeResponseListDocument gcrld = net.opengis.xls.GeocodeResponseListDocument.Factory.parse(node3); net.opengis.xls.GeocodeResponseListType geocodeResponseList = gcrld.getGeocodeResponseList(); result.setGeocodeResponseList(geocodeResponseList); } } } } is.close(); } catch (java.net.ConnectException ce) { JOptionPane.showMessageDialog(null, "no connection to geocoder", "Connection Error", JOptionPane.ERROR_MESSAGE); } catch (SocketTimeoutException ste) { ste.printStackTrace(); errorMessage += "<p>Time Out Exception, Server is not responding</p>"; } catch (IOException ioe) { ioe.printStackTrace(); errorMessage += "<p>IO Exception</p>"; } catch (XmlException xmle) { xmle.printStackTrace(); errorMessage += "<p>Error occured during parsing the XML response</p>"; } if (!errorMessage.equals("")) { System.out.println("\nerrorMessage: " + errorMessage + "\n\n"); JLabel label1 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: bold;}--></style></head><body><span class=\"Stil2\">Geocoder Error</span></body></html>"); JLabel label2 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + "<br>" + errorMessage + "<br>" + "<p>please check Java console. If problem persits, please report to system manager</p>" + "</span></body></html>"); Object[] objects = { label1, label2 }; JOptionPane.showMessageDialog(null, objects, "Error Message", JOptionPane.ERROR_MESSAGE); return null; } return result; }
11
Code Sample 1: public static void unzipModel(String filename, String tempdir) throws Exception { try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(filename); int BUFFER = 2048; ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(tempdir + entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); } zis.close(); } catch (Exception e) { e.printStackTrace(); throw new Exception("Can not expand model in \"" + tempdir + "\" because:\n" + e.getMessage()); } } Code Sample 2: private boolean exportPKC(String keystoreLocation, String pw) { boolean created = false; KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when exporting PKC: " + e.getMessage()); } return false; } Certificate cert = null; try { cert = ks.getCertificate("saws"); } catch (KeyStoreException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from keystore file when exporting PKC: " + e.getMessage()); } return false; } try { StringBuffer sb = new StringBuffer("-----BEGIN CERTIFICATE-----\n"); sb.append(new String(Base64.encode(cert.getEncoded()))); sb.append("\n-----END CERTIFICATE-----\n"); OutputStreamWriter wr = new OutputStreamWriter(new FileOutputStream("sawsSigningPKC.crt")); wr.write(new String(sb)); wr.flush(); wr.close(); created = true; } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error exporting PKC file: " + e.getMessage()); } return false; } return created; }
00
Code Sample 1: public void testReceiveMessageWithHttpPost() throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://192.167.131.126/hotel/sms/create.htm"); String receipt = "2#12345:source:079456345:200:xxx:1234567809:userfred:"; String message = "11796 book owner2 password 238 12.09.2008 3 testname surname"; HttpParams params = new BasicHttpParams(); params.setParameter("TextMessage", message); httpPost.setParams(params); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); } Code Sample 2: public void sendPOIGpxLocation() { this.myloc = new Position(45.56, 5.9); this.left = myloc.getY() - 0.025; this.right = myloc.getY() + 0.025; this.top = myloc.getX() + 0.03; this.bottom = myloc.getX() - 0.03; assertEquals("left test", left, (5.9 - 0.025)); assertEquals("right test", right, (5.9 + 0.025)); assertEquals("top test", top, (45.56 - 0.025)); assertEquals("bottom test", left, (45.56 + 0.025)); this.poisCheck.add("amenity"); try { if (this.poisCheck.get(0).compareTo("None") == 0) { model.setPointsOfInterest(new Items()); } else { this.url = new URL("http://www.informationfreeway.org/api/0.6/node[" + poisCheck.get(0) + "=*][bbox=" + left + "," + bottom + "," + right + "," + top + "]"); assertEquals("url informationfreeway.org test", url, "http://www.informationfreeway.org/api/0.6/node[amenity=*]" + "[bbox=" + left + "," + bottom + "," + right + "," + top + "]"); SAXParser pars = null; ParsePoiGpx gpxHandler = new ParsePoiGpx(poisCheck, this.model.getContext()); pars = SAXParserFactory.newInstance().newSAXParser(); pars.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true); pars.parse(url.openStream(), gpxHandler); this.pois = gpxHandler.getPOIResultsItems(); assertTrue("there is some pois", !this.pois.equals(0)); assertFalse("there is some pois", this.pois.equals(0)); } } catch (Exception e) { e.printStackTrace(); assertFalse(!e.getCause().equals(null)); } }
11
Code Sample 1: private void copyImage(ProjectElement e) throws Exception { String fn = e.getName(); if (!fn.toLowerCase().endsWith(".png")) { if (fn.contains(".")) { fn = fn.substring(0, fn.lastIndexOf('.')) + ".png"; } else { fn += ".png"; } } File img = new File(resFolder, fn); File imgz = new File(resoutFolder.getAbsolutePath(), fn + ".zlib"); boolean copy = true; if (img.exists() && config.containsKey(img.getName())) { long modified = Long.parseLong(config.get(img.getName())); if (modified >= img.lastModified()) { copy = false; } } if (copy) { convertImage(e.getFile(), img); config.put(img.getName(), String.valueOf(img.lastModified())); } DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(imgz))); BufferedInputStream in = new BufferedInputStream(new FileInputStream(img)); int read; while ((read = in.read()) != -1) { out.write(read); } out.close(); in.close(); imageFiles.add(imgz); imageNames.put(imgz, e.getName()); } Code Sample 2: private void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: protected Source getStylesheetSource(Resource stylesheetLocation) throws ApplicationContextException { if (logger.isDebugEnabled()) { logger.debug("Loading XSLT stylesheet from " + stylesheetLocation); } try { URL url = stylesheetLocation.getURL(); String urlPath = url.toString(); String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1); return new StreamSource(url.openStream(), systemId); } catch (IOException ex) { throw new ApplicationContextException("Can't load XSLT stylesheet from " + stylesheetLocation, ex); } } Code Sample 2: private String fetch(String urlstring) { String content = ""; try { URL url = new URL(urlstring); InputStream is = url.openStream(); BufferedReader d = new BufferedReader(new InputStreamReader(is)); String s; while (null != (s = d.readLine())) { content = content + s + "\n"; } is.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return content; }
11
Code Sample 1: public synchronized String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } catch (UnsupportedEncodingException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: private static String encode(String str, String method) { MessageDigest md = null; String dstr = null; try { md = MessageDigest.getInstance(method); md.update(str.getBytes()); dstr = new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return dstr; }
11
Code Sample 1: public static void copyFile(File oldFile, File newFile) throws Exception { newFile.getParentFile().mkdirs(); newFile.createNewFile(); FileChannel srcChannel = new FileInputStream(oldFile).getChannel(); FileChannel dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void execute() throws MojoExecutionException, MojoFailureException { try { this.getLog().info("copy source web.xml - " + this.getWebXml() + " to build dir (source web.xml required if mergewebxml execution is enabled)"); File destination = new File(this.getBuildDir(), "web.xml"); if (!destination.exists()) { destination.getParentFile().mkdirs(); destination.createNewFile(); } FileIOUtils.copyFile(this.getWebXml(), destination); for (int i = 0; i < this.getCompileTarget().length; i++) { File moduleFile = null; for (Iterator it = this.getProject().getCompileSourceRoots().iterator(); it.hasNext() && moduleFile == null; ) { File check = new File(it.next().toString() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } for (Iterator it = this.getProject().getResources().iterator(); it.hasNext(); ) { Resource r = (Resource) it.next(); File check = new File(r.getDirectory() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } ClassLoader loader = this.fixThreadClasspath(); if (moduleFile == null) { try { String classpath = "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"; InputStream is = loader.getResourceAsStream(classpath); System.out.println("Looking for classpath: " + classpath + "(" + (is != null) + ")"); if (is != null) { File temp = new File(this.getBuildDir(), this.getCompileTarget()[i].concat(".gwt.xml")); FileOutputStream fos = new FileOutputStream(temp); FileIOUtils.copyStream(is, fos); moduleFile = temp; } } catch (IOException e) { this.getLog().info(e); } } GwtWebInfProcessor processor = null; try { if (moduleFile != null) { getLog().info("Module file: " + moduleFile.getAbsolutePath()); processor = new GwtWebInfProcessor(this.getCompileTarget()[i], moduleFile, destination.getAbsolutePath(), destination.getAbsolutePath(), this.isWebXmlServletPathAsIs()); processor.process(); } else { throw new MojoExecutionException("module file null"); } } catch (ExitException e) { this.getLog().info(e.getMessage()); } } } catch (Exception e) { throw new MojoExecutionException("Unable to merge web.xml", e); } } Code Sample 2: public boolean restore(File directory) { log.debug("restore file from directory " + directory.getAbsolutePath()); try { if (!directory.exists()) return false; String[] operationFileNames = directory.list(); if (operationFileNames.length < 6) { log.error("Only " + operationFileNames.length + " files found in directory " + directory.getAbsolutePath()); return false; } int fileCount = 0; for (int i = 0; i < operationFileNames.length; i++) { if (!operationFileNames[i].toUpperCase().endsWith(".XML")) continue; log.debug("found file: " + operationFileNames[i]); fileCount++; File filein = new File(directory.getAbsolutePath() + File.separator + operationFileNames[i]); File fileout = new File(operationsDirectory + File.separator + operationFileNames[i]); FileReader in = new FileReader(filein); FileWriter out = new FileWriter(fileout); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } if (fileCount < 6) return false; return true; } catch (Exception e) { log.error("Exception while restoring operations files, may not be complete: " + e); return false; } }