label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
private void deleteProject(String uid, String home, HttpServletRequest request, HttpServletResponse response) throws Exception { String project = request.getParameter("project"); String line; response.setContentType("text/html"); PrintWriter out = response.getWriter(); htmlHeader(out, "Project Status", ""); try { synchronized (Class.forName("com.sun.gep.SunTCP")) { Vector list = new Vector(); String directory = home; Runtime.getRuntime().exec("/usr/bin/rm -rf " + directory + project); FilePermission perm = new FilePermission(directory + SUNTCP_LIST, "read,write,execute"); File listfile = new File(directory + SUNTCP_LIST); BufferedReader read = new BufferedReader(new FileReader(listfile)); while ((line = read.readLine()) != null) { if (!((new StringTokenizer(line, "\t")).nextToken().equals(project))) { list.addElement(line); } } read.close(); if (list.size() > 0) { PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter(listfile))); for (int i = 0; i < list.size(); i++) { write.println((String) list.get(i)); } write.close(); } else { listfile.delete(); } out.println("The project was successfully deleted."); } } catch (Exception e) { out.println("Error accessing this project."); } out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>"); htmlFooter(out); }
Code Sample 2:
@Test public void testStandardTee() throws Exception { final byte[] test = "test".getBytes(); final InputStream source = new ByteArrayInputStream(test); final ByteArrayOutputStream destination1 = new ByteArrayOutputStream(); final ByteArrayOutputStream destination2 = new ByteArrayOutputStream(); final TeeOutputStream tee = new TeeOutputStream(destination1, destination2); org.apache.commons.io.IOUtils.copy(source, tee); tee.close(); assertArrayEquals("the two arrays are equals", test, destination1.toByteArray()); assertArrayEquals("the two arrays are equals", test, destination2.toByteArray()); assertEquals("byte count", test.length, tee.getSize()); }
|
11
|
Code Sample 1:
public static void reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, out); writer.setPdfVersion(PdfWriter.VERSION_1_3); writer.setFullCompression(); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STRENGTH128BITS, password, null, securityType); } final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } else if (base_url != null) { document.addTitle(base_url); } final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } else { document.addCreator(IHtmlToPdfTransformer.VERSION); } final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.addProducer(sproducer); } else { document.addProducer(IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer); } document.open(); } PdfImportedPage page; for (int j = 0; j < n; ) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } } document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext(); ) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i).replaceAll("<pagecount>", "" + n); final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } else { reader = new PdfReader(tmp2.getAbsolutePath()); } final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STRENGTH128BITS, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } if (reason != null) { sap.setReason(reason); } if (location != null) { sap.setLocation(location); } stp.close(); oldOut.flush(); } } catch (final Exception e) { throw new CConvertException("ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } finally { try { tmp.delete(); } catch (final Exception ignore) { } try { tmp2.delete(); } catch (final Exception ignore) { } } }
Code Sample 2:
@Override protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (beforeServingFile(req, resp)) { String pathInfo = req.getPathInfo(); Validate.notNull(pathInfo, "the path info is null -> the sevlet should be mapped with /<mapping>/*"); String resurouce = pathInfo.substring(1); if (log.isDebugEnabled()) { log.debug("resource to expose: " + resurouce); } String extension = resurouce.substring(resurouce.lastIndexOf('.') + 1); MimeType mimeType = MimeTypeRegistry.getByExtension(extension); Validate.notNull(mimeType, "no mimetype found for extension: " + extension); if (log.isDebugEnabled()) { log.debug("the mime type to set: " + mimeType.getMimeType()); } File f = new File(mappedFolder, resurouce); Validate.isTrue(f.exists(), "file: " + f + " does not exist"); Validate.isTrue(f.canRead(), "can not read the file: " + f); if (log.isDebugEnabled()) { log.debug("exposing the file: " + f); } resp.setContentType(mimeType.getMimeType()); FileInputStream fis = new FileInputStream(f); ServletOutputStream os = resp.getOutputStream(); IOUtils.copy(fis, os); os.flush(); IOUtils.closeQuietly(fis); IOUtils.closeQuietly(os); } }
|
11
|
Code Sample 1:
private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } }
Code Sample 2:
public static void copyFile(File inputFile, File outputFile) throws IOException { BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[8192]; int n; while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n); fr.close(); fw.close(); }
|
00
|
Code Sample 1:
protected synchronized Class findClass(String className) { LOG.info("FIND class:" + className); String urlName = className.replace('.', '/'); byte buf[]; Class currentClass; SecurityManager sm = System.getSecurityManager(); if (sm != null) { int i = className.lastIndexOf('.'); if (i >= 0) sm.checkPackageDefinition(className.substring(0, i)); } buf = cache.get(urlName); if (buf != null) { LOG.info("Get class from cache:" + className); currentClass = defineClass(className, buf, 0, buf.length, (CodeSource) null); return currentClass; } try { URL url = new URL(urlBase, urlName + ".class"); LOG.info("Loading " + url); InputStream is = url.openConnection().getInputStream(); buf = getClassBytes(is); currentClass = defineClass(className, buf, 0, buf.length, (CodeSource) null); return currentClass; } catch (MalformedURLException mE) { LOG.warn("Bad url detected", mE); return null; } catch (IOException e) { buf = downloadClass(className); if (buf != null) { return defineClass(className, buf, 0, buf.length); } else { LOG.warn("no class found: " + className); return null; } } }
Code Sample 2:
private String createVisadFile(String fileName) throws FileNotFoundException, IOException { ArrayList<String> columnNames = new ArrayList<String>(); String visadFile = fileName + ".visad"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); String firstLine = buf.readLine().replace('"', ' '); StringTokenizer st = new StringTokenizer(firstLine, ","); while (st.hasMoreTokens()) columnNames.add(st.nextToken()); StringBuilder headerBuilder = new StringBuilder(); headerBuilder.append("(").append(columnNames.get(0)).append("->("); for (int i = 1; i < columnNames.size(); i++) { headerBuilder.append(columnNames.get(i)); if (i < columnNames.size() - 1) headerBuilder.append(","); } headerBuilder.append("))"); BufferedWriter out = new BufferedWriter(new FileWriter(visadFile)); out.write(headerBuilder.toString() + "\n"); out.write(firstLine + "\n"); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return visadFile; }
|
00
|
Code Sample 1:
public void handle() { FileChannel srcChannel, destChannel; String destOutFile = databaseName + ".script." + System.currentTimeMillis(); String destOutFileCompressed = databaseName + ".script." + 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(databaseName + ".script"); 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 database file '" + databaseName + ".script' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate database file '" + databaseName + ".script': " + e); } } else { try { srcChannel = new FileInputStream(databaseName + ".script").getChannel(); } catch (IOException e) { Debug.debug("Unable to read file '" + databaseName + ".script' for database rotation."); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate 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 database file '" + databaseName + ".script' to '" + destOutFile + "'"); } 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(".script.") != -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; } }
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 void uploadFile(String localPath, String hostname, String username, String password, String remotePath) { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(hostname); int reply = ftpClient.getReplyCode(); boolean success = false; if (FTPReply.isPositiveCompletion(reply)) { success = ftpClient.login(username, password); if (!success) { Output.error("Failed to login with username/password " + username + "/" + password); return; } ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.ASCII_FILE_TYPE); } FileInputStream in = new FileInputStream(localPath); boolean result = ftpClient.storeFile(remotePath, in); if (!result) { Output.error("Logged in but failed to upload " + localPath + " to " + remotePath + "\nPerhaps one of the paths was wrong."); } in.close(); ftpClient.disconnect(); } catch (IOException ioe) { Output.error("Error ftp'ing using " + "\nlocalPath: " + localPath + "\nhostname: " + hostname + "\nusername: " + username + "\npassword: " + password + "\nremotePath: " + remotePath, ioe); } }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; final StringBuilder sbValueBeforeMD5 = new StringBuilder(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.fatal("", e); return; } try { final long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(sId); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuilder sb = new StringBuilder(); for (int j = 0; j < array.length; ++j) { final int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { logger.fatal("", e); } }
|
00
|
Code Sample 1:
public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setFileView(new ImageFileView()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName(); String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); } catch (IOException ex) { ex.printStackTrace(); } imagen.setImagenURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL())); } else { } }
Code Sample 2:
private static String md5(String input) { String res = ""; try { MessageDigest cript = MessageDigest.getInstance("MD5"); cript.reset(); cript.update(input.getBytes()); byte[] md5 = cript.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { Log4k.error(pdfPrinter.class.getName(), ex.getMessage()); } return res; }
|
00
|
Code Sample 1:
public static InputStream call(String serviceUrl, Map parameters) throws IOException, RestException { StringBuffer urlString = new StringBuffer(serviceUrl); String query = RestClient.buildQueryString(parameters); HttpURLConnection conn; if ((urlString.length() + query.length() + 1) > MAX_URI_LENGTH_FOR_GET) { URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.getOutputStream().write(query.getBytes()); } else { if (query.length() > 0) { urlString.append("?").append(query); } URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("GET"); } int responseCode = conn.getResponseCode(); if (HttpURLConnection.HTTP_OK != responseCode) { ByteArrayOutputStream errorBuffer = new ByteArrayOutputStream(); int read; byte[] readBuffer = new byte[ERROR_READ_BUFFER_SIZE]; InputStream errorStream = conn.getErrorStream(); while (-1 != (read = errorStream.read(readBuffer))) { errorBuffer.write(readBuffer, 0, read); } throw new RestException("Request failed, HTTP " + responseCode + ": " + conn.getResponseMessage(), errorBuffer.toByteArray()); } return conn.getInputStream(); }
Code Sample 2:
private void processHTTPRequest(Status status) { String httpRequest = null; Document xmlDoc = null; httpRequest = this.smsGW.getUrl(); if (this.smsGW.getFrom() != null) httpRequest += "from=" + this.smsGW.getFrom(); if (this.smsGW.getTo() != null) httpRequest += "&to=" + this.smsGW.getTo(); if (this.smsGW.getTxt() != null) httpRequest += "&txt=" + this.smsGW.getTxt(); httpRequest += "&id=" + this.smsGW.getId() + "&pwd=" + this.smsGW.getPwd(); if (this.smsGW.getFlash() != null) httpRequest += "&flash=" + this.smsGW.getFlash(); if (this.smsGW.getRoute() != null) httpRequest += "&route=" + this.smsGW.getRoute(); if (this.smsGW.getAutoroute() != null) httpRequest += "&autoroute=" + this.smsGW.getAutoroute(); if (this.smsGW.getStatus() != null) httpRequest += "&status=" + this.smsGW.getStatus(); if (this.smsGW.getSim() != null) httpRequest += "&sim=" + this.smsGW.getSim(); if (this.smsGW.getTyp() != null) httpRequest += "&typ=" + this.smsGW.getTyp(); if (this.smsGW.getUser() != null) httpRequest += "&user=" + this.smsGW.getUser(); logger.debug("HTTP2SMS request: " + httpRequest); InputStream is = null; try { URL url = new URL(httpRequest); is = url.openStream(); logger.debug("HTTP request sent!"); xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is); } catch (Exception ex2) { logger.error("Exception Message: " + ex2.toString()); status.setErrorCause("Exception Message: " + ex2.toString()); status.setResult(ErrorCodes.EXTERNALNOTIFICATION_ERROR_RESPONSE_FROM_SMS_GATEWAY.ordinal()); } finally { if (is != null) try { is.close(); } catch (IOException ex3) { logger.error("Exception Message: " + ex3.toString()); } } NodeList nl = xmlDoc.getElementsByTagName("response"); Node nd = nl.item(0); NodeList nl2 = nd.getChildNodes(); String responseResult = nl2.item(1).getTextContent(); String responseDesc = nl2.item(3).getTextContent(); String responseId = nl2.item(5).getTextContent(); int responseRes = Integer.parseInt(responseResult); if (responseRes == 0) { logger.debug("HTTP2SMS response: result: " + responseResult + "; desc: " + responseDesc + "; ID: " + responseId); } else { logger.error("HTTP2SMS response: result: " + responseResult + "; desc: " + responseDesc + "; ID: " + responseId); } if (responseRes == 0) { logger.info("SMS with id " + responseId + " successfully sent to number " + this.smsGW.getTo()); status.setErrorCause("SMS with id " + responseId + " successfully sent to number " + this.smsGW.getTo()); status.setResult(ErrorCodes.EXTERNALNOTIFICATION_OK.ordinal()); } else if (responseRes == 1) { logger.error("System error in external SMS gateway! HTTP request: " + httpRequest); status.setErrorCause("System error in external SMS gateway! HTTP request: " + httpRequest); status.setResult(ErrorCodes.EXTERNALNOTIFICATION_ERROR_SYSTEM_ERROR_IN_SMS_GATEWAY.ordinal()); } else if (responseRes == 2) { logger.error("Sending error in external SMS gateway! HTTP request: " + httpRequest); logger.error("SMS2HTTP Gateway Response: ResultCode:" + responseResult + "; ErrorDescription:" + responseDesc + "; TransactionID:" + responseId); status.setErrorCause("Sending error in external SMS gateway! ErrorDescription:" + responseDesc); status.setResult(ErrorCodes.EXTERNALNOTIFICATION_ERROR_SENDING_ERROR_IN_SMS_GATEWAY.ordinal()); } else if (responseRes >= 10 && responseRes <= 19) { logger.error("SMS gateway says: Parameter error in HTTP request: " + httpRequest); logger.error("SMS2HTTP Gateway Response: ResultCode:" + responseResult + "; ErrorDescription:" + responseDesc + "; TransactionID:" + responseId); status.setErrorCause("SMS gateway says: Parameter error in HTTP request! ErrorDescription:" + responseDesc); status.setResult(ErrorCodes.EXTERNALNOTIFICATION_ERROR_PARAMETER_ERROR_IN_SMS_GATEWAY.ordinal()); } else if (responseRes >= 20 && responseRes <= 29) { logger.error("Limit reached at external SMS gateway!"); logger.error("SMS2HTTP Gateway Response: ResultCode:" + responseResult + "; ErrorDescription:" + responseDesc + "; TransactionID:" + responseId); status.setErrorCause("Limit reached at external SMS gateway!"); status.setResult(ErrorCodes.EXTERNALNOTIFICATION_ERROR_LIMIT_REACHED_IN_SMS_GATEWAY.ordinal()); } else { logger.error("Undefined error from external SMS gateway!"); logger.error("SMS2HTTP Gateway Response: ResultCode:" + responseResult + "; ErrorDescription:" + responseDesc + "; TransactionID:" + responseId); status.setErrorCause("Undefined error from external SMS gateway! ErrorDescription:" + responseDesc); status.setResult(ErrorCodes.EXTERNALNOTIFICATION_ERROR_UNDEFINED_ERROR_IN_SMS_GATEWAY.ordinal()); } }
|
00
|
Code Sample 1:
public static String encryptPassword(String username, String realm, String password) throws GeneralSecurityException { MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update(":".getBytes()); md.update(realm.getBytes()); md.update(":".getBytes()); md.update(password.getBytes()); byte[] hash = md.digest(); return toHex(hash, hash.length); }
Code Sample 2:
public void processSaveHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "UPDATE WM_LIST_HOLDING " + "SET " + " full_name_HOLDING=?, " + " NAME_HOLDING=? " + "WHERE ID_HOLDING = ? and ID_HOLDING in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedHoldingId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_ROAD from v$_read_list_road z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setString(num++, holdingBean.getName()); ps.setString(num++, holdingBean.getShortName()); RsetTools.setLong(ps, num++, holdingBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); processDeleteRelatedCompany(dbDyn, holdingBean, authSession); processInsertRelatedCompany(dbDyn, holdingBean, authSession); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
|
00
|
Code Sample 1:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
Code Sample 2:
protected byte[] bytesFromJar(String path) throws IOException { URL url = new URL(path); InputStream is = url.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int n; while ((n = is.read(buffer)) >= 0) baos.write(buffer, 0, n); is.close(); return baos.toByteArray(); }
|
11
|
Code Sample 1:
protected static URL[] createUrls(URL jarUrls[]) { ArrayList<URL> additionalUrls = new ArrayList<URL>(Arrays.asList(jarUrls)); for (URL ju : jarUrls) { try { JarFile jar = new JarFile(ju.getFile()); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry j = entries.nextElement(); if (j.isDirectory()) continue; if (j.getName().startsWith("lib/") && j.getName().endsWith(".jar")) { URL url = new URL("jar:" + ju.getProtocol() + ":" + ju.getFile() + "!/" + j.getName()); InputStream is = url.openStream(); File tmpFile = File.createTempFile("SCDeploy", ".jar"); FileOutputStream fos = new FileOutputStream(tmpFile); IOUtils.copy(is, fos); is.close(); fos.close(); additionalUrls.add(new URL("file://" + tmpFile.getAbsolutePath())); } } } catch (IOException e) { } } return additionalUrls.toArray(new URL[] {}); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
private File downloadPDB(String pdbId) { File tempFile = new File(path + "/" + pdbId + ".pdb.gz"); File pdbHome = new File(path); if (!pdbHome.canWrite()) { System.err.println("can not write to " + pdbHome); return null; } String ftp = String.format("ftp://ftp.ebi.ac.uk/pub/databases/msd/pdb_uncompressed/pdb%s.ent", pdbId.toLowerCase()); System.out.println("Fetching " + ftp); try { URL url = new URL(ftp); InputStream conn = url.openStream(); System.out.println("writing to " + tempFile); FileOutputStream outPut = new FileOutputStream(tempFile); GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut); PrintWriter pw = new PrintWriter(gzOutPut); BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn)); String line; while ((line = fileBuffer.readLine()) != null) { pw.println(line); } pw.flush(); pw.close(); outPut.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); return null; } return tempFile; }
Code Sample 2:
public List<String> makeQuery(String query) { List<String> result = new ArrayList<String>(); try { query = URLUTF8Encoder.encode(query); URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=" + query); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", "http://poo.sk"); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } String response = builder.toString(); JSONObject json = new JSONObject(response); Long count = Long.decode(json.getJSONObject("responseData").getJSONObject("cursor").getString("estimatedResultCount")); LOG.info("Found " + count + " potential pages"); JSONArray ja = json.getJSONObject("responseData").getJSONArray("results"); for (int i = 0; i < ja.length(); i++) { JSONObject j = ja.getJSONObject(i); result.add(j.getString("url")); } } catch (Exception e) { LOG.error("Couldnt query Google for some reason check exception below"); e.printStackTrace(); } return result; }
|
11
|
Code Sample 1:
public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
Code Sample 2:
static void cleanFile(File file) { final Counter cnt = new Counter(); final File out = new File(FileUtils.appendToFileName(file.getAbsolutePath(), ".cleaned")); final SAMFileReader reader = new SAMFileReader(file); final SAMRecordIterator it = reader.iterator(); final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, out); if (!it.hasNext()) return; log.info("Cleaning file " + file + " to " + out.getName()); SAMRecord last = it.next(); writer.addAlignment(last); while (it.hasNext()) { final SAMRecord now = it.next(); final int start1 = last.getAlignmentStart(); final int start2 = now.getAlignmentStart(); final int end1 = last.getAlignmentEnd(); final int end2 = now.getAlignmentEnd(); if (start1 == start2 && end1 == end2) { log.debug("Discarding record " + now.toString()); cnt.count(); continue; } writer.addAlignment(now); last = now; } writer.close(); reader.close(); log.info(file + " done, discarded " + cnt.getCount() + " reads"); exe.shutdown(); }
|
00
|
Code Sample 1:
public static String calcHA1(String algorithm, String username, String realm, String password, String nonce, String cnonce) throws FatalException, MD5DigestException { MD5Encoder encoder = new MD5Encoder(); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new FatalException(e); } if (username == null || realm == null) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "username or realm"); } if (password == null) { System.err.println("No password has been provided"); throw new IllegalStateException(); } if (algorithm != null && algorithm.equals("MD5-sess") && (nonce == null || cnonce == null)) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "nonce or cnonce"); } md5.update((username + ":" + realm + ":" + password).getBytes()); if (algorithm != null && algorithm.equals("MD5-sess")) { md5.update((":" + nonce + ":" + cnonce).getBytes()); } return encoder.encode(md5.digest()); }
Code Sample 2:
public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException, WrongFormatException, URISyntaxException { System.out.println(new URI("google.com.ua.css").toString()); Scanner scc = new Scanner(System.in); System.err.print(scc.nextLine().substring(1)); ServerSocket s = new ServerSocket(5354); while (true) { Socket client = s.accept(); InputStream iStream = client.getInputStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(iStream)); String line = ""; while (!(line = bf.readLine()).equals("")) { System.out.println(line); } System.out.println("end of request"); new PrintWriter(client.getOutputStream()).println("hi"); bf.close(); } }
Code Sample 2:
public static void unZip(String unZipfileName, String outputDirectory) throws IOException, FileNotFoundException { FileOutputStream fileOut; File file; ZipEntry zipEntry; ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)), encoder); while ((zipEntry = zipIn.getNextEntry()) != null) { file = new File(outputDirectory + File.separator + zipEntry.getName()); if (zipEntry.isDirectory()) { createDirectory(file.getPath(), ""); } else { File parent = file.getParentFile(); if (!parent.exists()) { createDirectory(parent.getPath(), ""); } fileOut = new FileOutputStream(file); int readedBytes; while ((readedBytes = zipIn.read(buf)) > 0) { fileOut.write(buf, 0, readedBytes); } fileOut.close(); } zipIn.closeEntry(); } }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static String encrypt(String text) { final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; String result = ""; MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes()); byte[] hash = digest.digest(); char buffer[] = new char[hash.length * 2]; for (int i = 0, x = 0; i < hash.length; i++) { buffer[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf]; buffer[x++] = HEX_CHARS[hash[i] & 0xf]; } result = new String(buffer); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
|
11
|
Code Sample 1:
private String generateHash(String key, String data) throws ChiropteraException { try { MessageDigest md = MessageDigest.getInstance(Constants.Connection.Auth.MD5); md.update(key.getBytes()); byte[] raw = md.digest(); String s = toHexString(raw); SecretKey skey = new SecretKeySpec(s.getBytes(), Constants.Connection.Auth.HMACMD5); Mac mac = Mac.getInstance(skey.getAlgorithm()); mac.init(skey); byte digest[] = mac.doFinal(data.getBytes()); String digestB64 = BaculaBase64.binToBase64(digest); return digestB64.substring(0, digestB64.length()); } catch (NoSuchAlgorithmException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } catch (InvalidKeyException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } }
Code Sample 2:
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
|
00
|
Code Sample 1:
public void copyFileToFileWithPaths(String sourcePath, String destinPath) throws Exception { BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File file1 = new File(sourcePath); if (file1.exists() && (file1.isFile())) { File file2 = new File(destinPath); if (file2.exists()) { file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(sourcePath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(destinPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); } out.flush(); in.close(); out.close(); } else { throw new Exception("Source file not exist ! sourcePath = (" + sourcePath + ")"); } }
Code Sample 2:
public RespID(PublicKey key) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance("SHA1"); ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString keyHash = new DEROctetString(digest.digest()); this.id = new ResponderID(keyHash); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } }
|
11
|
Code Sample 1:
public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); }
Code Sample 2:
JcrFile createBody(Part part) throws IOException, MessagingException { JcrFile body = new JcrFile(); body.setName("part"); ByteArrayOutputStream pout = new ByteArrayOutputStream(); IOUtils.copy(part.getInputStream(), pout); body.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray())); body.setMimeType(part.getContentType()); body.setLastModified(java.util.Calendar.getInstance()); return body; }
|
11
|
Code Sample 1:
private void createJarArchive(File archiveFile, List<File> filesToBeJared, File base) throws Exception { FileOutputStream stream = new FileOutputStream(archiveFile); JarOutputStream out = new JarOutputStream(stream); for (File tobeJared : filesToBeJared) { if (tobeJared == null || !tobeJared.exists() || tobeJared.isDirectory()) continue; String entryName = tobeJared.getAbsolutePath().substring(base.getAbsolutePath().length() + 1).replace("\\", "/"); JarEntry jarEntry = new JarEntry(entryName); jarEntry.setTime(tobeJared.lastModified()); out.putNextEntry(jarEntry); FileInputStream in = new FileInputStream(tobeJared); IOUtils.copy(in, out); IOUtils.closeQuietly(in); out.closeEntry(); } out.close(); stream.close(); System.out.println("Generated file: " + archiveFile); }
Code Sample 2:
private void copy(File fin, File fout) throws IOException { FileOutputStream out = null; FileInputStream in = null; try { out = new FileOutputStream(fout); in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } } catch (IOException _e) { throw _e; } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { String urlString = "http://php.tech.sina.com.cn/download/d_load.php?d_id=7877&down_id=151542"; urlString = EncodeUtils.encodeURL(urlString); URL url = new URL(urlString); System.out.println("第一次:" + url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); Map req = conn.getRequestProperties(); System.out.println("第一次请求头:"); printMap(req); conn.connect(); System.out.println("第一次响应:"); System.out.println(conn.getResponseMessage()); int code = conn.getResponseCode(); System.out.println("第一次code:" + code); printMap(conn.getHeaderFields()); System.out.println(conn.getURL().getFile()); if (code == 404 && !(conn.getURL() + "").equals(urlString)) { System.out.println(conn.getURL()); String tmp = URLEncoder.encode(conn.getURL().toString(), "gbk"); System.out.println(URLEncoder.encode("在线音乐播放脚本", "GBK")); System.out.println(tmp); url = new URL(tmp); System.out.println("第二次:" + url); conn = (HttpURLConnection) url.openConnection(); System.out.println("第二次响应:"); System.out.println("code:" + code); printMap(conn.getHeaderFields()); } }
Code Sample 2:
public static String downloadWebpage3(String address) throws ClientProtocolException, IOException { HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(address); HttpResponse response = client.execute(request); BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line; String page = ""; while((line = br.readLine()) != null) { page += line + "\n"; } br.close(); return page; }
|
11
|
Code Sample 1:
public static final synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { System.err.println("Failed to load the MD5 MessageDigest. " + "We will be unable to function normally."); nsae.printStackTrace(); } } digest.update(data.getBytes()); return encodeHex(digest.digest()); }
Code Sample 2:
public static byte[] encrypt(String x) throws NoSuchAlgorithmException { MessageDigest d = null; d = MessageDigest.getInstance("SHA-1"); d.reset(); d.update(x.getBytes()); return d.digest(); }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
@Test public void testTransactWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwritetrans.txt"); RFileOutputStream out = new RFileOutputStream(file, WriteMode.TRANSACTED, false, 1); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
|
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:
public static void unzip(String destDir, String zipPath) { PrintWriter stdout = new PrintWriter(System.out, true); int read = 0; byte[] data = new byte[1024]; ZipEntry entry; try { ZipInputStream in = new ZipInputStream(new FileInputStream(zipPath)); stdout.println(zipPath); while ((entry = in.getNextEntry()) != null) { if (entry.getMethod() == ZipEntry.DEFLATED) { stdout.println(" Inflating: " + entry.getName()); } else { stdout.println(" Extracting: " + entry.getName()); } FileOutputStream out = new FileOutputStream(destDir + File.separator + entry.getName()); while ((read = in.read(data, 0, 1024)) != -1) { out.write(data, 0, read); } out.close(); } in.close(); stdout.println(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void unzipAndRemove(final String file) { String destination = file.substring(0, file.length() - 3); InputStream is = null; OutputStream os = null; try { is = new GZIPInputStream(new FileInputStream(file)); os = new FileOutputStream(destination); byte[] buffer = new byte[8192]; for (int length; (length = is.read(buffer)) != -1; ) os.write(buffer, 0, length); } catch (IOException e) { System.err.println("Fehler: Kann nicht entpacken " + file); } finally { if (os != null) try { os.close(); } catch (IOException e) { } if (is != null) try { is.close(); } catch (IOException e) { } } deleteFile(file); }
Code Sample 2:
@Override public void run() { try { FileChannel in = new FileInputStream(inputfile).getChannel(); long pos = 0; for (int i = 1; i <= noofparts; i++) { FileChannel out = new FileOutputStream(outputfile.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Rozdělovač: Rozděluji část " + i + ".."); in.transferTo(pos, splitsize, out); pos += splitsize; remainingsize -= splitsize; if (remainingsize < splitsize) in.transferTo(pos, remainingsize, out); pb.setValue(100 * i / noofparts); out.close(); } in.close(); if (deleteOnFinish) new File(inputfile + "").delete(); status.setText("Rozdělovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Rozděleno!", "Rozdělovač", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { } }
|
00
|
Code Sample 1:
private void serializeWithClass(Class theClass, int count, String comment) { for (int c = 0; c < 10; c++) { if (c == 9) { beginAction(1, "persistence write/read", count, comment); } String tempFile = ".tmp.archive"; SerializeClassInterface theInstance = null; try { theInstance = (SerializeClassInterface) theClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } if (theInstance == null) { System.err.println("error: Couldn't initialize class to " + "be serialized!"); return; } reset(); for (int i = 0; i < count; i++) { try { FileOutputStream fout = new FileOutputStream(tempFile); BufferedOutputStream bout = new BufferedOutputStream(fout); ObjectOutputStream oout = new ObjectOutputStream(bout); oout.writeObject(theInstance); oout.flush(); oout.close(); } catch (IOException ioe) { System.err.println("serializing: " + tempFile + ":" + ioe.toString()); } try { FileInputStream fin = new FileInputStream(tempFile); BufferedInputStream bin = new BufferedInputStream(fin); ObjectInputStream oin = new ObjectInputStream(bin); theInstance = (SerializeClassInterface) oin.readObject(); oin.close(); } catch (Exception e) { System.err.println("deserializing: " + tempFile + ":" + e.toString()); break; } proceed(); } reset(); if (c == 9) { endAction(); } } }
Code Sample 2:
@Test public void lookingUpResources() throws IOException { StickyEmbedder b = new StickyEmbedder("--debug", "--trace") { @Override protected File deriveApplicationFile() { return new File("src/test/samples/sticky-deployer-sample-2jar-1.2-sample.jar"); } }; b.initialise(); assertThat(b.getLibraries()).hasSize(2); assertThat(b.getLibraries().iterator().next().getClasses()).hasSize(1); assertThat(b.getLibraries().iterator().next().getResources()).hasSize(8); URL url = b.getClassLoader().findResource("net/stickycode/deploy/sample/babysteps/run.properties"); assertThat(url).isNotNull(); InputStream i = url.openStream(); assertThat(i).isNotNull(); assertThat(new BufferedReader(new InputStreamReader(i)).readLine()).isEqualTo("run=running is step 3"); Enumeration<URL> e = b.getClassLoader().findResources("net/stickycode/deploy/sample/babysteps/run.properties"); assertThat(e.hasMoreElements()).isTrue(); assertThat(e.nextElement()).isNotNull(); assertThat(e.hasMoreElements()).isFalse(); Enumeration<URL> manifests = b.getClassLoader().findResources("net/stickycode/deploy/sample/duplicate.properties"); assertThat(manifests.hasMoreElements()).isTrue(); assertThat(manifests.nextElement()).isNotNull(); assertThat(manifests.hasMoreElements()).isTrue(); assertThat(manifests.nextElement()).isNotNull(); assertThat(manifests.hasMoreElements()).isFalse(); }
|
00
|
Code Sample 1:
public static boolean verify(String password, String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } byte[] data = Base64.decode(base64.toCharArray()); byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); }
Code Sample 2:
@Test public void testWrite() { System.out.println("write"); final File[] files = { new File(sharePath) }; System.out.println("Creating hash..."); String initHash = MD5File.MD5Directory(files[0]); System.out.println("Hash: " + initHash); Share readShare = ShareUtility.createShare(files, "TestShare"); System.out.println("Creating shares..."); final ShareFolder[] readers = ShareUtility.cropShareToParts(readShare, PARTS); System.out.println("Reading and writing shares..."); done = 0; for (int i = 0; i < PARTS; i++) { final int j = i; new Thread() { public void run() { ShareFolder part = (ShareFolder) ObjectClone.clone(readers[j]); ShareFileReader reader = new ShareFileReader(readers[j], files[0]); ShareFileWriter writer = new ShareFileWriter(part, new File("Downloads/" + readers[j].getName())); long tot = 0; byte[] b = new byte[(int) (Math.random() * 10000)]; while (tot < readers[j].getSize()) { reader.read(b); byte[] bwrite = new byte[(int) (Math.random() * 10000) + b.length]; System.arraycopy(b, 0, bwrite, 0, b.length); writer.write(bwrite, b.length); tot += b.length; } done++; System.out.println((int) (done * 100.0 / PARTS) + "% Complete"); } }.start(); } while (done < PARTS) { Thread.yield(); } File resultFile = new File("Downloads/" + readShare.getName()); System.out.println("Creating hash of written share..."); String resultHash = MD5File.MD5Directory(resultFile); System.out.println("Init hash: " + initHash); System.out.println("Result hash: " + resultHash); assertEquals(initHash, resultHash); }
|
00
|
Code Sample 1:
public FlatFileFrame() { super("Specify Your Flat File Data"); try { Class transferAgentClass = this.getStorageTransferAgentClass(); if (transferAgentClass == null) { throw new RuntimeException("Transfer agent class can not be null."); } Class[] parameterTypes = new Class[] { RepositoryStorage.class }; Constructor constr = transferAgentClass.getConstructor(parameterTypes); Object[] actualValues = new Object[] { this }; this.transferAgent = (RepositoryStorageTransferAgent) constr.newInstance(actualValues); } catch (Exception err) { throw new RuntimeException("Unable to instantiate transfer agent.", err); } this.fmtlistener = new FormatTableModelListener(); this.map = new HashMap(); this.NoCallbackChangeMode = false; this.setSize(new Dimension(1000, 400)); this.setLayout(new GridLayout(1, 1)); this.Config = new FlatFileToolsConfig(); this.Config.initialize(); this.connectionHandler = new RepositoryConnectionHandler(this.Config); this.Connection = (FlatFileStorageConnectivity) this.connectionHandler.getConnection("default"); this.Prefs = new FlatFileToolsPrefs(); this.Prefs.initialize(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String formatted_date = formatter.format(new Date()); this.createdOnText = new JTextField(formatted_date); this.createdByText = new JTextField(this.Prefs.getConfigValue("createdby")); this.reposListeners = new Vector(); this.removeFormatButton = new JButton("Remove"); this.previewPanel = new DataSetPanel(new DataSet()); this.previewPanel.setEditable(false); this.chooser = new JFileChooser(); this.chooser.setMultiSelectionEnabled(true); this.enabledRadio = new JRadioButton("Enabled:"); this.enabledRadio.setSelected(true); this.editPrefsButton = new JButton("Preferences..."); this.editPrefsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { System.out.println("Making visible"); prefsEditor.setVisible(true); } }); this.commentTextArea = new JTextArea(20, 8); this.commentTextArea.setText("No comment."); this.commentTextArea.setToolTipText("A detailed (possibly formatted) description including guidance to future developers of this set."); this.iconServer = new IconServer(); this.iconServer.setConfigFile(this.Prefs.getConfigValue("default", "iconmapfile")); this.nicknameText = new IconifiedDomainNameTextField(new FlatFileFindNameDialog(Config, iconServer), this.iconServer); this.nicknameText.setPreferredSize(new Dimension(200, 25)); this.nicknameText.setText(this.Prefs.getConfigValue("default", "domainname") + "."); this.nicknameText.setNameTextToolTipText("Right click to search the database."); this.uploadButton = new JButton("Upload"); this.uploadButton.setToolTipText("Uploads current state to repository."); this.uploadButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { System.out.println("Trying to upload flat file spec..."); try { String expname = getNickname(); int split = expname.lastIndexOf('.'); String domain = ""; String name = ""; String usersdomain = Prefs.getConfigValue("default", "domainname"); if (split > 0) { domain = expname.substring(0, split); name = expname.substring(split + 1, expname.length()); } else { name = expname; } name = name.trim(); if (name.equals("")) { JOptionPane.showMessageDialog(null, "Cowardly refusing to upload with an empty flat file name..."); return; } if (!domain.equals(usersdomain)) { int s = JOptionPane.showConfirmDialog(null, "If you are not the original author, you may wish to switch the current domain name " + domain + " to \nyour domain name " + usersdomain + ". Would you like to do this?\n (If you'll be using this domain often, you may want to set it in your preferences.)", "Potential WWW name-space clash!", JOptionPane.YES_NO_CANCEL_OPTION); if (s == JOptionPane.YES_OPTION) { setNickname(usersdomain + "." + name); executeTransfer(); } if (s == JOptionPane.NO_OPTION) { executeTransfer(); } } else { executeTransfer(); } } catch (Exception err) { throw new RuntimeException("Problem uploading storage.", err); } } }); this.repositoryView = new JButton("default"); this.repositoryView.addActionListener(new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { repositoryEditor.setCurrentRepository(repositoryView.getText()); repositoryEditor.setVisible(true); } }); this.prefsEditor = new PrefsConfigFrame(this.Prefs); this.prefsEditor.setVisible(false); this.prefsEditor.addCloseListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { prefsEditor.setVisible(false); } }); this.prefsEditor.addSelectListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { prefsEditor.setVisible(false); } }); this.repositoryEditor = new ReposConfigFrame(this.Config); this.repositoryEditor.setVisible(false); this.repositoryEditor.addSelectListener(new SelectListener()); this.repositoryEditor.addCloseListener(new CloseListener()); this.addSources = new JButton("Source from file..."); this.preview = new JButton("Preview"); this.leastcolumn = new JSpinner(); this.columns2show = new JSpinner(); this.leastrow = new JSpinner(); this.rows2show = new JSpinner(); int rowCount = 10; JLabel sourceLabel = new JLabel("File Source"); this.flatfilesource = new JTextField(); this.flatfilesource.setPreferredSize(new Dimension(200, 25)); this.flatfilesource.setMinimumSize(new Dimension(200, 25)); this.flatfilesource.setMaximumSize(new Dimension(200, 25)); this.isURLButton = new JRadioButton("URL"); Box scrollBox = Box.createVerticalBox(); Box srcBox = Box.createHorizontalBox(); srcBox.add(this.addSources); srcBox.add(sourceLabel); srcBox.add(this.flatfilesource); srcBox.add(this.isURLButton); srcBox.add(this.preview); scrollBox.add(srcBox); Box detailsPanel = Box.createVerticalBox(); Box detailsBox = Box.createVerticalBox(); JLabel label; Box jointBox; jointBox = Box.createHorizontalBox(); label = new JLabel("Pre-Header Lines:"); this.preheaderlines = new JSpinner(); jointBox.add(label); jointBox.add(this.preheaderlines); detailsBox.add(jointBox); this.preheaderlines.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ev) { int selectedRow = fileselector.getSelectedRow(); if (selectedRow >= 0) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); if (fn != null) { updateDetailsFor(fn); } } } }); jointBox = Box.createHorizontalBox(); label = new JLabel("Has Header Line:"); this.hasHeaderLineBox = new JCheckBox(); jointBox.add(label); jointBox.add(this.hasHeaderLineBox); detailsBox.add(jointBox); this.hasHeaderLineBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int selectedRow = fileselector.getSelectedRow(); if (selectedRow >= 0) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } } }); jointBox = Box.createHorizontalBox(); label = new JLabel("Post-Header Lines:"); this.postheaderlines = new JSpinner(); jointBox.add(label); jointBox.add(this.postheaderlines); detailsBox.add(jointBox); this.postheaderlines.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent ev) { int selectedRow = fileselector.getSelectedRow(); if (selectedRow >= 0) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } } }); jointBox = Box.createHorizontalBox(); label = new JLabel("Format:"); jointBox.add(label); this.singleFormatText = new JTextField("%s"); jointBox.add(this.singleFormatText); jointBox.add(new JLabel("Repeat")); this.repeatFormatNumber = new JSpinner(); this.repeatFormatNumber.setValue(new Integer(1)); jointBox.add(this.repeatFormatNumber); this.addFormatButton = new JButton("Add"); jointBox.add(this.addFormatButton); this.removeFormatButton = new JButton("Remove"); jointBox.add(this.removeFormatButton); detailsBox.add(jointBox); jointBox = Box.createHorizontalBox(); label = new JLabel("Column Format:"); this.formatmodel = new FormatTableModel(); this.formatTable = new JTable(this.formatmodel); this.formatmodel.addTableModelListener(this.fmtlistener); JTable hdrTable = this.formatTable.getTableHeader().getTable(); this.formatTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); JScrollPane fsp = new JScrollPane(this.formatTable); fsp.setPreferredSize(new Dimension(200, 100)); jointBox.add(label); jointBox.add(fsp); detailsBox.add(jointBox); jointBox = Box.createHorizontalBox(); label = new JLabel("Field Delimiter:"); this.fieldDelimiter = new JTextField("\\t"); this.fieldDelimiter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int selectedRow = fileselector.getSelectedRow(); if (selectedRow >= 0) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } } }); jointBox.add(label); jointBox.add(this.fieldDelimiter); this.inferButton = new JButton("Infer"); this.inferButton.setEnabled(false); jointBox.add(this.inferButton); detailsBox.add(jointBox); jointBox = Box.createHorizontalBox(); label = new JLabel("Record Delimiter:"); this.recordDelimiter = new JTextField("\\n"); this.recordDelimiter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int selectedRow = fileselector.getSelectedRow(); if (selectedRow >= 0) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } } }); jointBox.add(label); jointBox.add(this.recordDelimiter); detailsBox.add(jointBox); detailsBox.add(Box.createVerticalGlue()); detailsBox.add(Box.createVerticalGlue()); detailsPanel.add(srcBox); detailsPanel.add(detailsBox); detailsPanel.add(previewPanel); this.addFormatButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { String fmt2rep = singleFormatText.getText(); Integer rep = (Integer) repeatFormatNumber.getValue(); Vector fmtparts = formatmodel.getFormatParts(); int selectedCol = formatTable.getSelectedColumn(); if (selectedCol < 0) { selectedCol = formatTable.getColumnCount() - 1; } for (int r = 1; r <= rep.intValue(); r++) { fmtparts.insertElementAt(fmt2rep, selectedCol); } formatmodel.setFormatParts(fmtparts); updateFormatTable(); int selectedRow = fileselector.getSelectedRow(); if ((selectedRow < sourcemodel.getRowCount()) && (selectedRow >= 0)) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); fn = fn.trim(); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } } }); this.removeFormatButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int selectedCol = formatTable.getSelectedColumn(); if (selectedCol < 0) { return; } Vector parts = formatmodel.getFormatParts(); if (parts.size() == 1) { throw new RuntimeException("At least one format column is required."); } parts.removeElementAt(selectedCol); formatmodel.setFormatParts(parts); updateFormatTable(); int selectedRow = fileselector.getSelectedRow(); if ((selectedRow < sourcemodel.getRowCount()) && (selectedRow >= 0)) { String fn = (String) sourcemodel.getValueAt(selectedRow, 0); fn = fn.trim(); if (fn != null) { fn = fn.trim(); if ((fn != null) && (fn.length() > 0)) { updateDetailsFor(fn); } } } System.out.println("The new Column count after remove is " + formatmodel.getColumnCount()); } }); this.inferButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int row = fileselector.getSelectedRow(); int col = 0; String filename = (String) sourcemodel.getValueAt(0, 0); Boolean isURL = (Boolean) sourcemodel.getValueAt(0, 1); BufferedReader br = null; File file = null; DataInputStream in = null; if (isURL.booleanValue()) { try { URL url2goto = new URL(filename); in = new DataInputStream(url2goto.openStream()); System.out.println("READY TO READ FROM URL:" + url2goto); } catch (Exception err) { throw new RuntimeException("Problem constructing URI for " + filename + ".", err); } } else { file = new File(filename); if (!file.exists()) { throw new RuntimeException("The file named '" + filename + "' does not exist."); } FileInputStream fstream = null; try { fstream = new FileInputStream(filename); in = new DataInputStream(fstream); } catch (Exception err) { throw new RuntimeException("Problem creating FileInputStream for " + filename + ".", err); } } br = new BufferedReader(new InputStreamReader(in)); JTable hdrTable = formatTable.getTableHeader().getTable(); try { String strLine; int line = 0; int ignorePreHdrLines = ((Integer) preheaderlines.getValue()).intValue(); int ignorePostHdrLines = ((Integer) postheaderlines.getValue()).intValue(); int numhdr = 0; boolean hasHeaderLine = false; if (hasHeaderLineBox.isSelected()) { hasHeaderLine = true; } if (hasHeaderLine) { numhdr = 1; } String FD = fieldDelimiter.getText(); while ((strLine = br.readLine()) != null) { if (line <= (ignorePreHdrLines + numhdr + ignorePostHdrLines)) { System.out.println(strLine); } else { String[] putative_cols = strLine.split(FD); System.out.println("The number of potential columns is " + putative_cols.length); String FMT = ""; while (formatTable.getColumnCount() > putative_cols.length) { TableColumn tcol = formatTable.getColumnModel().getColumn(0); formatTable.removeColumn(tcol); } for (int i = 0; i < putative_cols.length; i++) { String fmt = ""; try { Double dummy = new Double(putative_cols[i]); fmt = "%f"; } catch (Exception err) { fmt = "%s"; } FMT = FMT + fmt; formatTable.setValueAt(fmt, 0, i); } System.out.println("The potential format is " + FMT); formatmodel.setFormat(FMT); break; } line++; } in.close(); } catch (Exception err) { throw new RuntimeException("Problem reading single line from file.", err); } for (int j = 0; j < formatTable.getColumnCount(); j++) { hdrTable.getColumnModel().getColumn(j).setHeaderValue("" + (j + 1)); } formatTable.repaint(); } }); Box topbox = Box.createHorizontalBox(); topbox.add(detailsPanel); Box mainbox = Box.createVerticalBox(); Box setBox = Box.createHorizontalBox(); setBox.add(this.editPrefsButton); jointBox = Box.createHorizontalBox(); label = new JLabel("Created On:"); jointBox.add(label); this.createdOnText.setPreferredSize(new Dimension(50, 25)); jointBox.add(this.createdOnText); setBox.add(jointBox); jointBox = Box.createHorizontalBox(); label = new JLabel("Created By:"); jointBox.add(label); this.createdByText.setPreferredSize(new Dimension(50, 25)); jointBox.add(this.createdByText); setBox.add(jointBox); setBox.add(this.uploadButton); setBox.add(this.repositoryView); setBox.add(this.nicknameText); setBox.add(this.enabledRadio); mainbox.add(setBox); jointBox = Box.createHorizontalBox(); label = new JLabel("Comment:"); jointBox.add(label); jointBox.add(new JScrollPane(this.commentTextArea)); mainbox.add(jointBox); mainbox.add(topbox); mainbox.add(previewPanel); this.add(mainbox); this.addSources.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { int option = chooser.showOpenDialog(null); File[] files = null; if (option == JFileChooser.APPROVE_OPTION) { files = chooser.getSelectedFiles(); if (files.length > 10) { ((DefaultTableModel) sourcemodel).setRowCount(files.length); } else { ((DefaultTableModel) sourcemodel).setRowCount(10); } for (int i = 0; i < files.length; i++) { sourcemodel.setValueAt(files[i].getAbsolutePath(), i, 0); } } if (anyNonEmptySources()) { allowFormatParsing(true); } else { allowFormatParsing(false); } } }); this.preview.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { FlatFileDOM[] filespecs = new FlatFileDOM[map.size()]; int k = 0; for (int j = 0; j < sourcemodel.getRowCount(); j++) { String fn = (String) sourcemodel.getValueAt(j, 0); if (map.containsKey(fn)) { filespecs[k] = (FlatFileDOM) map.get(fn); k++; } } Vector hdrs = null; Vector types = null; for (int j = 0; j < filespecs.length; j++) { DataSetReader rdr = new DataSetReader(filespecs[j]); int rc = rdr.determineRowCount(); filespecs[j].setRowCount(rc); if (j == 0) { hdrs = rdr.getHeaders(); types = rdr.getTypes(); } System.out.println("The number of rows is=" + rc); } System.out.println("Creating flatfileset"); FlatFileSet dataset = new FlatFileSet(filespecs); System.out.println("Finished sorting!!!"); for (int j = 0; j < hdrs.size(); j++) { dataset.addColumn((String) hdrs.get(j), (Class) types.get(j)); } System.out.println("Number of headers is=" + hdrs.size()); System.out.println("The dataset rc is " + dataset.getRowCount()); System.out.println("The dataset cc is " + dataset.getColumnCount()); previewPanel.setDataSet(dataset); previewPanel.setVerticalScrollIntermittant(true); previewPanel.setHorizontalScrollIntermittant(true); previewPanel.setEditable(false); if (anyNonEmptySources()) { allowFormatParsing(true); } else { allowFormatParsing(false); } } }); allowFormatParsing(false); this.formatTable.repaint(); }
Code Sample 2:
protected void setRankOrder() { this.rankOrder = new int[values.length]; for (int i = 0; i < rankOrder.length; i++) { rankOrder[i] = i; assert (!Double.isNaN(values[i])); } for (int i = rankOrder.length - 1; i >= 0; i--) { boolean swapped = false; for (int j = 0; j < i; j++) if (values[rankOrder[j]] < values[rankOrder[j + 1]]) { int r = rankOrder[j]; rankOrder[j] = rankOrder[j + 1]; rankOrder[j + 1] = r; } } }
|
00
|
Code Sample 1:
public static void copy(File sourceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
String processURLInput(String inputURL) throws SoaplabException { try { File tmpFile = File.createTempFile("gowlab.", null); tmpFile.deleteOnExit(); Object data = inputs.get(inputURL); URL url = new URL(data.toString()); if (url.getProtocol().equals("file")) logAndThrow("Trying to get local file '" + url.toString() + "' is not allowed."); URLConnection uc = url.openConnection(); uc.connect(); InputStream in = uc.getInputStream(); byte[] buffer = new byte[256]; DataOutputStream fileout = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tmpFile))); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { fileout.write(buffer, 0, bytesRead); } fileout.close(); return tmpFile.getAbsolutePath(); } catch (IOException e) { logAndThrow("In processURLData: " + e.toString()); } return null; }
|
00
|
Code Sample 1:
@Override public void discoverPlugIns() throws PlugInManagerException { LOG.info("Discovering plug-ins defined in JAR manifests..."); ClassLoader classLoader = this.getClass().getClassLoader(); Enumeration<URL> manifests = null; try { manifests = classLoader.getResources(MANIFEST_RESOURCE); if (manifests == null || !manifests.hasMoreElements()) { LOG.info("No provider manifests found"); return; } } catch (IOException ex) { LOG.error("Discovery failed", ex); return; } while (manifests.hasMoreElements()) { URL url = manifests.nextElement(); try { Manifest manifest = new Manifest(url.openStream()); LOG.debug("Validating manifest with URL of " + url); if (validatePlugInInfo(manifest)) { P plugIn = instantiatePlugIn(manifest); registerPlugIn(plugIn); } } catch (IOException e) { LOG.error("Failed to load manifest with url " + url, e); } catch (InvalidPlugInException e) { LOG.error("Provider with url " + url + " is not valid", e); } catch (PlugInInstantiationException e) { LOG.error("Provider with url " + url + " could not be instantiated", e); } catch (Exception e) { LOG.error("Provider with url " + url + " could not be initialized", e); } } LOG.info("Found and successfully validated " + getPlugIns().size() + " plug-ins"); }
Code Sample 2:
@Test public void testTrim() throws Exception { TreeNode ast = TestUtil.readFileInAST("resources/SimpleTestFile.java"); DecoratorSelection ds = new DecoratorSelection(); XmlFileSystemRepository rep = new XmlFileSystemRepository(); XmlToFormatContentConverter converter = new XmlToFormatContentConverter(rep); URI url = new File("resources/javaDefaultFormats.xml").toURI(); InputStream is = url.toURL().openStream(); converter.convert(is); File f = new File("resources/javaDefaultFormats.xml").getAbsoluteFile(); converter.convert(f); String string = new File("resources/query.xml").getAbsolutePath(); Document qDoc = XmlUtil.loadXmlFromFile(string); Query query = new Query(qDoc); Format format = XfsrFormatManager.getInstance().getFormats("java", "signature only"); TokenAutoTrimmer.create("Java", "resources/java.autotrim"); Document doc = rep.getXmlContentTree(ast, query, format, ds).getOwnerDocument(); String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><sourcecode>main(String[])</sourcecode>"; ByteArrayOutputStream bout = new ByteArrayOutputStream(); XmlUtil.outputXml(doc, bout); String actual = bout.toString(); assertEquals(expected, actual); }
|
11
|
Code Sample 1:
@Override public void remove(int disciplinaId) { try { this.criaConexao(false); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } String sql = "delete from Disciplina where id = ?"; PreparedStatement stmt = null; try { stmt = this.getConnection().prepareStatement(sql); stmt.setInt(1, disciplinaId); int retorno = stmt.executeUpdate(); if (retorno == 0) { this.getConnection().rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de remover dados de Revendedor no banco!"); } this.getConnection().commit(); } catch (SQLException e) { try { this.getConnection().rollback(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } } }
Code Sample 2:
@Override public void update(DisciplinaDTO disciplina) { try { this.criaConexao(false); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } LOG.debug("Criou a conex�o!"); String sql = "update Disciplina set nome = ? where id = ?"; PreparedStatement stmt = null; try { stmt = this.getConnection().prepareStatement(sql); LOG.debug("PreparedStatement criado com sucesso!"); stmt.setString(1, disciplina.getNome()); stmt.setInt(2, disciplina.getId()); int retorno = stmt.executeUpdate(); if (retorno == 0) { this.getConnection().rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de alterar dados de Revendedor no banco!"); } LOG.debug("Confirmando as altera��es no banco."); this.getConnection().commit(); } catch (SQLException e) { LOG.debug("Desfazendo as altera��es no banco."); try { this.getConnection().rollback(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } LOG.debug("Lan�ando a exce��o da camada de persist�ncia."); try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } } }
|
00
|
Code Sample 1:
private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Code Sample 2:
public void command() { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(dir)); int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { filename = chooser.getSelectedFile().getAbsolutePath(); String f2 = ""; for (int i = 0; i < filename.length(); ++i) { if (filename.charAt(i) != '\\') { f2 = f2 + filename.charAt(i); } else f2 = f2 + '/'; } filename = f2; if (filename.contains(dir)) { filename = filename.substring(dir.length()); } else { try { FileChannel srcFile = new FileInputStream(filename).getChannel(); FileChannel dstFile; filename = "ueditor_files/" + chooser.getSelectedFile().getName(); File newFile; if (!(newFile = new File(dir + filename)).createNewFile()) { dstFile = new FileInputStream(dir + filename).getChannel(); newFile = null; } else { dstFile = new FileOutputStream(newFile).getChannel(); } dstFile.transferFrom(srcFile, 0, srcFile.size()); srcFile.close(); dstFile.close(); System.out.println("file copyed to: " + dir + filename); } catch (Exception e) { e.printStackTrace(); label.setIcon(InputText.iconX); filename = null; for (Group g : groups) { g.updateValidity(true); } return; } } label.setIcon(InputText.iconV); for (Group g : groups) { g.updateValidity(true); } } }
|
00
|
Code Sample 1:
private void callbackWS(String xmlControl, String ws_results, long docId) { SimpleProvider config; Service service; Object ret; Call call; Object[] parameter; String method; String wsurl; URL url; NodeList delegateNodes; Node actualNode; InputSource xmlcontrolstream; try { xmlcontrolstream = new InputSource(new StringReader(xmlControl)); delegateNodes = SimpleXMLParser.parseDocument(xmlcontrolstream, AgentBehaviour.XML_CALLBACK); actualNode = delegateNodes.item(0); wsurl = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_URL); method = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_METHOD); if (wsurl == null || method == null) { System.out.println("----- Did not get method or wsurl from the properties! -----"); return; } url = new java.net.URL(wsurl); try { url.openConnection().connect(); } catch (IOException ex) { System.out.println("----- Could not connect to the webservice! -----"); } Vector v_param = new Vector(); v_param.add(ws_results); v_param.add(new Long(docId)); parameter = v_param.toArray(); config = new SimpleProvider(); config.deployTransport("http", new HTTPSender()); service = new Service(config); call = (Call) service.createCall(); call.setTargetEndpointAddress(url); call.setOperationName(new QName("http://schemas.xmlsoap.org/soap/encoding/", method)); try { ret = call.invoke(parameter); if (ret == null) { ret = new String("No response from callback function!"); } System.out.println("Callback function returned: " + ret); } catch (RemoteException ex) { System.out.println("----- Could not invoke the method! -----"); } } catch (Exception ex) { ex.printStackTrace(System.err); } }
Code Sample 2:
public static void copyFile(String oldPath, String newPath) throws IOException { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); } }
|
00
|
Code Sample 1:
public 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:
public Object run() { try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(buf.toString().getBytes()); byte[] data = digest.digest(); serialNum = new BASE64Encoder().encode(data); return serialNum; } catch (NoSuchAlgorithmException exp) { BootSecurityManager.securityLogger.log(Level.SEVERE, exp.getMessage(), exp); return buf.toString(); } }
|
00
|
Code Sample 1:
private static String getRegistrationClasses() { CentralRegistrationClass c = new CentralRegistrationClass(); String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class"); try { Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); String file = url.getFile(); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest mf = jarConnection.getManifest(); Attributes attrs = (Attributes) mf.getAttributes(name); if (attrs != null) { String classes = attrs.getValue("RegistrationClasses"); return classes; } } } catch (IOException ex) { ex.printStackTrace(); } return ""; }
Code Sample 2:
public Project deleteProject(int projectID) throws AdaptationException { Project project = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM Projects WHERE id = " + projectID; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete project failed."; log.error(msg); throw new AdaptationException(msg); } project = getProject(resultSet); query = "DELETE FROM Projects WHERE id = " + projectID; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProject"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return project; }
|
11
|
Code Sample 1:
public void postProcess() throws StopWriterVisitorException { dxfWriter.postProcess(); try { FileChannel fcinDxf = new FileInputStream(fTemp).getChannel(); FileChannel fcoutDxf = new FileOutputStream(m_Fich).getChannel(); DriverUtilities.copy(fcinDxf, fcoutDxf); fTemp.delete(); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } }
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; }
|
00
|
Code Sample 1:
private static byte[] calcMd5(String pass) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pass.getBytes(), 0, pass.length()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm found"); System.exit(1); } return null; }
Code Sample 2:
public void sortingByBubble(int[] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length - 1 - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } }
|
00
|
Code Sample 1:
public void deleteUser(User portalUserBean, AuthSession authSession) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portalUserBean.getUserId() == null) throw new IllegalArgumentException("id of portal user is null"); String sql = "update WM_LIST_USER " + "set is_deleted=1 " + "where ID_USER=? and is_deleted = 0 and ID_FIRM in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedCompanyId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_FIRM from v$_read_list_firm z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setLong(num++, portalUserBean.getUserId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) { dbDyn.rollback(); } } catch (Exception e001) { } String es = "Error delete of portal user"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
Code Sample 2:
public static final void copyFile(File argSource, File argDestination) throws IOException { FileChannel srcChannel = new FileInputStream(argSource).getChannel(); FileChannel dstChannel = new FileOutputStream(argDestination).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } }
|
11
|
Code Sample 1:
public static void TestDBStore() throws PDException, Exception { StoreDDBB StDB = new StoreDDBB("jdbc:derby://localhost:1527/Prodoc", "Prodoc", "Prodoc", "org.apache.derby.jdbc.ClientDriver;STBLOB"); System.out.println("Driver[" + StDB.getDriver() + "] Tabla [" + StDB.getTable() + "]"); StDB.Connect(); FileInputStream in = new FileInputStream("/tmp/readme.htm"); StDB.Insert("12345678-1", "1.0", in); int TAMBUFF = 1024 * 64; byte Buffer[] = new byte[TAMBUFF]; InputStream Bytes; Bytes = StDB.Retrieve("12345678-1", "1.0"); FileOutputStream fo = new FileOutputStream("/tmp/12345679.htm"); int readed = Bytes.read(Buffer); while (readed != -1) { fo.write(Buffer, 0, readed); readed = Bytes.read(Buffer); } Bytes.close(); fo.close(); StDB.Delete("12345678-1", "1.0"); StDB.Disconnect(); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
private void copyFiles(File oldFolder, File newFolder) { for (File fileToCopy : oldFolder.listFiles()) { File copiedFile = new File(newFolder.getAbsolutePath() + "\\" + fileToCopy.getName()); try { FileInputStream source = new FileInputStream(fileToCopy); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } }
Code Sample 2:
public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); while (in.read(buff) != -1) { PrintUtil.prt("%%%"); buff.flip(); out.write(buff); buff.clear(); } }
|
11
|
Code Sample 1:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
Code Sample 2:
static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; }
|
00
|
Code Sample 1:
public void setPassword(UserType user, String clearPassword) { try { Random r = new Random(); String newSalt = Long.toString(Math.abs(r.nextLong())); MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.reset(); md.update(newSalt.getBytes("UTF-8")); md.update(clearPassword.getBytes("UTF-8")); String encodedString = new String(Base64.encode(md.digest())); user.setPassword(encodedString); user.setSalt(newSalt); this.markModified(user); } catch (UnsupportedEncodingException ex) { logger.fatal("Your computer does not have UTF-8 support for Java installed.", ex); GlobalUITools.displayFatalExceptionMessage(null, "UTF-8 for Java not installed", ex, true); } catch (NoSuchAlgorithmException ex) { String errorMessage = "Could not use algorithm " + HASH_ALGORITHM; logger.fatal(errorMessage, ex); GlobalUITools.displayFatalExceptionMessage(null, errorMessage, ex, true); } }
Code Sample 2:
public static String doPostWithBasicAuthentication(URL url, String username, String password, String parameters, Map<String, String> headers) throws IOException { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); con.setConnectTimeout(2000); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (parameters != null) con.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length)); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(parameters); wr.flush(); wr.close(); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); }
|
00
|
Code Sample 1:
private String transferWSDL(String wsdlURL, String userPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (userPassword != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDeployDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
Code Sample 2:
public static String md5hash(String text) { java.security.MessageDigest md; try { md = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.update(text.getBytes()); byte[] md5bytes = md.digest(); return new String(org.apache.commons.codec.binary.Hex.encodeHex(md5bytes)); }
|
11
|
Code Sample 1:
public static String extractIconPath(String siteURL) throws IOException { siteURL = siteURL.trim(); if (!siteURL.startsWith("http://")) { siteURL = "http://" + siteURL; } URL url = new URL(siteURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String iconURL = null; String iconPath = null; String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("type=\"image/x-icon\"") || inputLine.toLowerCase().contains("rel=\"shortcut icon\"")) { String tmp = new String(inputLine); String[] smallLines = inputLine.replace(">", ">\n").split("\n"); for (String smallLine : smallLines) { if (smallLine.contains("type=\"image/x-icon\"") || smallLine.toLowerCase().contains("rel=\"shortcut icon\"")) { tmp = smallLine; break; } } iconURL = tmp.replaceAll("^.*href=\"", ""); iconURL = iconURL.replaceAll("\".*", ""); tmp = null; String originalSiteURL = new String(siteURL); siteURL = getHome(siteURL); if (iconURL.charAt(0) == '/') { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL.substring(1); } else { iconURL = siteURL + iconURL; } } else if (!iconURL.startsWith("http://")) { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } siteURL = originalSiteURL; break; } if (inputLine.contains("</head>".toLowerCase())) { break; } } in.close(); siteURL = getHome(siteURL); if (iconURL == null || "".equals(iconURL.trim())) { iconURL = "favicon.ico"; if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } try { String iconFileName = siteURL; if (iconFileName.startsWith("http://")) { iconFileName = iconFileName.substring(7); } iconFileName = iconFileName.replaceAll("\\W", " ").trim().replace(" ", "_").concat(".ico"); iconPath = JReader.getConfig().getShortcutIconsDir() + File.separator + iconFileName; InputStream inIcon = new URL(iconURL).openStream(); OutputStream outIcon = new FileOutputStream(iconPath); byte[] buf = new byte[1024]; int len; while ((len = inIcon.read(buf)) > 0) { outIcon.write(buf, 0, len); } inIcon.close(); outIcon.close(); } catch (Exception e) { } return iconPath; }
Code Sample 2:
public static String getTextFileFromURL(String urlName) { try { StringBuffer textFile = new StringBuffer(""); String line = null; URL url = new URL(urlName); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) textFile = textFile.append(line + "\n"); reader.close(); return textFile.toString(); } catch (Exception e) { Debug.signal(Debug.ERROR, null, "Failed to open " + urlName + ", exception " + e); return null; } }
|
11
|
Code Sample 1:
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpClientInfo clientInfo = HttpUtil.parseClientInfo((HttpServletRequest) request); if (request.getParameter("_debug_") != null) { StringBuffer buffer = new StringBuffer(); Enumeration iter = request.getHeaderNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); buffer.append(name + "=" + request.getHeader(name)).append("\n"); } buffer.append("\n"); iter = request.getParameterNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); String value = request.getParameter(name); if (!"ISO-8859-1".equalsIgnoreCase(clientInfo.getPreferCharset())) value = new String(value.getBytes("ISO-8859-1"), clientInfo.getPreferCharset()); buffer.append(name).append("=").append(value).append("\n"); } response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(buffer.toString()); return null; } Object resultObj = handleRequest(request); if (resultObj == null) { String requestException = (String) request.getAttribute("XSMP.handleRequest.Exception"); if (requestException != null) response.sendError(500, requestException); else response.setContentLength(0); } else { if (resultObj instanceof DataHandler) { response.setContentType(((DataHandler) resultObj).getContentType()); response.setContentLength(((DataHandler) resultObj).getInputStream().available()); IOUtils.copy(((DataHandler) resultObj).getInputStream(), response.getOutputStream()); } else { String temp = resultObj.toString(); if (temp.startsWith("<") && temp.endsWith(">")) response.setContentType("text/html; charset=" + clientInfo.getPreferCharset()); else response.setContentType("text/plain; charset=" + clientInfo.getPreferCharset()); byte[] buffer = temp.getBytes(clientInfo.getPreferCharset()); response.setContentLength(buffer.length); response.getOutputStream().write(buffer); } } return null; }
Code Sample 2:
static void createCompleteXML(File file) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(errorFile); fos = new FileOutputStream(file); byte[] data = new byte[Integer.parseInt(BlueXStatics.prop.getProperty("allocationUnit"))]; int offset; while ((offset = fis.read(data)) != -1) fos.write(data, 0, offset); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } try { fos.close(); } catch (Exception e) { } } FileWriter fw = null; try { fw = new FileWriter(file, true); fw.append("</detail>"); fw.append("\n</exception>"); fw.append("\n</log>"); } catch (Exception e) { e.printStackTrace(); } finally { try { fw.close(); } catch (Exception e) { } } }
|
11
|
Code Sample 1:
protected void setUp() throws Exception { testOutputDirectory = new File(getClass().getResource("/").getPath()); zipFile = new File(this.testOutputDirectory, "/plugin.zip"); zipOutputDirectory = new File(this.testOutputDirectory, "zip"); zipOutputDirectory.mkdir(); logger.fine("zip dir created"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); zos.putNextEntry(new ZipEntry("css/")); zos.putNextEntry(new ZipEntry("css/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("js/")); zos.putNextEntry(new ZipEntry("js/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/mylib.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/mylib.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); }
Code Sample 2:
public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
|
11
|
Code Sample 1:
private static String digest(String myinfo) { try { MessageDigest alga = MessageDigest.getInstance("SHA"); alga.update(myinfo.getBytes()); byte[] digesta = alga.digest(); return byte2hex(digesta); } catch (Exception ex) { return myinfo; } }
Code Sample 2:
public byte[] getDigest(OMText text, String digestAlgorithm) throws OMException { byte[] digest = new byte[0]; try { MessageDigest md = MessageDigest.getInstance(digestAlgorithm); md.update((byte) 0); md.update((byte) 0); md.update((byte) 0); md.update((byte) 3); md.update(text.getText().getBytes("UnicodeBigUnmarked")); digest = md.digest(); } catch (NoSuchAlgorithmException e) { throw new OMException(e); } catch (UnsupportedEncodingException e) { throw new OMException(e); } return digest; }
|
00
|
Code Sample 1:
public void copyImage(String from, String to) { File inputFile = new File(from); File outputFile = new File(to); try { if (inputFile.canRead()) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buf = new byte[65536]; int c; while ((c = in.read(buf)) > 0) out.write(buf, 0, c); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
byte[] loadUrlByteArray(String szName, int offset, int size) { byte[] baBuffer = new byte[size]; try { URL url = new URL(waba.applet.Applet.currentApplet.getCodeBase(), szName); try { InputStream file = url.openStream(); if (size == 0) { int n = file.available(); baBuffer = new byte[n - offset]; } DataInputStream dataFile = new DataInputStream(file); try { dataFile.skip(offset); dataFile.readFully(baBuffer); } catch (EOFException e) { System.err.print(e.getMessage()); } file.close(); } catch (IOException e) { System.err.print(e.getMessage()); } } catch (MalformedURLException e) { System.err.print(e.getMessage()); } return baBuffer; }
|
00
|
Code Sample 1:
public Boolean connect() throws Exception { try { _ftpClient = new FTPClient(); _ftpClient.connect(_url); _ftpClient.login(_username, _password); _rootPath = _ftpClient.printWorkingDirectory(); return true; } catch (Exception ex) { throw new Exception("Cannot connect to server."); } }
Code Sample 2:
public void updatePortletName(PortletNameBean portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "update WM_PORTAL_PORTLET_NAME " + "set TYPE=? " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); ps.setString(1, portletNameBean.getPortletName()); RsetTools.setLong(ps, 2, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
|
11
|
Code Sample 1:
public void copyJarContent(File jarPath, File targetDir) throws IOException { log.info("Copying natives from " + jarPath.getName()); JarFile jar = new JarFile(jarPath); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = entries.nextElement(); File f = new File(targetDir, file.getName()); log.info("Copying native - " + file.getName()); File parentFile = f.getParentFile(); parentFile.mkdirs(); if (file.isDirectory()) { f.mkdir(); continue; } InputStream is = null; FileOutputStream fos = null; try { is = jar.getInputStream(file); fos = new FileOutputStream(f); IOUtils.copy(is, fos); } finally { if (fos != null) fos.close(); if (is != null) is.close(); } } }
Code Sample 2:
@Test public void config() throws IOException { Reader reader = new FileReader(new File("src/test/resources/test.yml")); Writer writer = new FileWriter(new File("src/site/apt/config.apt")); writer.write("------\n"); writer.write(FileUtils.readFully(reader)); writer.flush(); writer.close(); }
|
11
|
Code Sample 1:
public void testBlobB() { ResultSet rs; byte[] ba; byte[] baR1 = new byte[] { (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB }; byte[] baR2 = new byte[] { (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB }; try { connection.setAutoCommit(false); Statement st = connection.createStatement(); st.executeUpdate("DROP TABLE blo IF EXISTS"); st.executeUpdate("CREATE TABLE blo (id INTEGER, b blob( 100))"); PreparedStatement ps = connection.prepareStatement("INSERT INTO blo(id, b) values(2, ?)"); ps.setBlob(1, new SerialBlob(baR1)); ps.executeUpdate(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } java.sql.Blob blob1 = rs.getBlob("b"); System.out.println("Size of retrieved blob: " + blob1.length()); byte[] baOut = blob1.getBytes(1, (int) blob1.length()); if (baOut.length != baR1.length) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } for (int i = 0; i < baOut.length; i++) { if (baOut[i] != baR1[i]) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } } rs.close(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } blob1 = rs.getBlob("b"); ba = blob1.getBytes(1, baR2.length); if (ba.length != baR2.length) { assertTrue("row2 byte length differs", false); } for (int i = 0; i < ba.length; i++) { if (ba[i] != baR1[i]) { assertTrue("row2 byte " + i + " differs", false); } } rs.close(); connection.rollback(); ps.setBinaryStream(1, new HsqlByteArrayInputStream(baR1), baR1.length); ps.executeUpdate(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } blob1 = rs.getBlob("b"); System.out.println("Size of retrieved blob: " + blob1.length()); baOut = blob1.getBytes(1, (int) blob1.length()); if (baOut.length != baR1.length) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } for (int i = 0; i < baOut.length; i++) { if (baOut[i] != baR1[i]) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } } rs.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); fail("test failure"); } }
Code Sample 2:
public void testJDBCSavepoints() throws Exception { String sql; String msg; int i; PreparedStatement ps; ResultSet rs; Savepoint sp1; Savepoint sp2; Savepoint sp3; Savepoint sp4; Savepoint sp5; Savepoint sp6; Savepoint sp7; int rowcount = 0; sql = "drop table t if exists"; stmt.executeUpdate(sql); sql = "create table t(id int, fn varchar, ln varchar, zip int)"; stmt.executeUpdate(sql); conn1.setAutoCommit(true); conn1.setAutoCommit(false); sql = "insert into t values(?,?,?,?)"; ps = conn1.prepareStatement(sql); ps.setString(2, "Mary"); ps.setString(3, "Peterson-Clancy"); i = 0; for (; i < 10; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp1 = conn1.setSavepoint("savepoint1"); for (; i < 20; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp2 = conn1.setSavepoint("savepoint2"); for (; i < 30; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp3 = conn1.setSavepoint("savepoint3"); for (; i < 40; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp4 = conn1.setSavepoint("savepoint4"); for (; i < 50; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp5 = conn1.setSavepoint("savepoint5"); sp6 = conn1.setSavepoint("savepoint6"); sp7 = conn1.setSavepoint("savepoint7"); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) from t value"; try { assertEquals(msg, 50, rowcount); } catch (Exception e) { } conn2.setAutoCommit(false); conn2.setSavepoint("savepoint1"); conn2.setSavepoint("savepoint2"); msg = "savepoint released succesfully on non-originating connection"; try { conn2.releaseSavepoint(sp2); assertTrue(msg, false); } catch (Exception e) { } try { conn2.rollback(sp1); msg = "succesful rollback to savepoint on " + "non-originating connection"; assertTrue(msg, false); } catch (Exception e) { } msg = "direct execution of <release savepoint> statement failed to " + "release JDBC-created SQL-savepoint with identical savepoint name"; try { conn2.createStatement().executeUpdate("release savepoint \"savepoint2\""); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } msg = "direct execution of <rollback to savepoint> statement failed to " + "roll back to existing JDBC-created SQL-savepoint with identical " + "savepoint name"; try { conn2.createStatement().executeUpdate("rollback to savepoint \"savepoint1\""); } catch (Exception e) { e.printStackTrace(); try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.releaseSavepoint(sp6); msg = "savepoint released succesfully > 1 times"; try { conn1.releaseSavepoint(sp6); assertTrue(msg, false); } catch (Exception e) { } msg = "savepoint released successfully after preceding savepoint released"; try { conn1.releaseSavepoint(sp7); assertTrue(msg, false); } catch (Exception e) { } msg = "preceding same-point savepoint destroyed by following savepoint release"; try { conn1.releaseSavepoint(sp5); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.rollback(sp4); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select * rowcount after 50 inserts - 10 rolled back:"; try { assertEquals(msg, 40, rowcount); } catch (Exception e) { } msg = "savepoint rolled back succesfully > 1 times"; try { conn1.rollback(sp4); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp3); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) after 50 inserts - 20 rolled back:"; try { assertEquals(msg, 30, rowcount); } catch (Exception e) { } msg = "savepoint released succesfully after use in rollback"; try { conn1.releaseSavepoint(sp3); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp1); msg = "savepoint rolled back without raising an exception after " + "rollback to a preceeding savepoint"; try { conn1.rollback(sp2); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(); msg = "savepoint released succesfully when it should have been " + "destroyed by a full rollback"; try { conn1.releaseSavepoint(sp1); assertTrue(msg, false); } catch (Exception e) { } conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.rollback(); conn1.setAutoCommit(false); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); }
|
00
|
Code Sample 1:
Bitmap downloadImage(String uri) { try { mGetMethod.setURI(new URI(uri)); HttpResponse resp = mClient.execute(mGetMethod); if (resp.getStatusLine().getStatusCode() < 400) { InputStream is = resp.getEntity().getContent(); String tmp = convertStreamToString(is); Log.d(TAG, "hoge" + tmp); is.close(); return null; } } catch (Exception e) { e.printStackTrace(); } return null; }
Code Sample 2:
public InputLattice(String file, int type, boolean convertJoinMeet) throws FileNotFoundException, IOException { InputStream latStream = null; labels = new Vector(); upperCoversVector = new Vector(); Vector upperCovers = new Vector(); edgeColors = new Hashtable(); Vector upperCovering = new Vector(); int level = 0; String str; String currentElt = null; String cover = null; boolean first = true; StreamTokenizer in; switch(type) { case FILE: latStream = new FileInputStream(file); break; case STRING: latStream = new StringBufferInputStream(file); break; case URL: URL url = new URL("http", Config.HOST, Config.PORT, "/" + Config.HASSE + "/" + Config.URL_STREAMER + file); System.out.println("url is " + url); URLConnection connection = url.openConnection(); latStream = new DataInputStream(connection.getInputStream()); break; } in = new StreamTokenizer(latStream); in.wordChars('^', '_'); in.wordChars('*', '.'); while (in.nextToken() != StreamTokenizer.TT_EOF) { if (in.ttype == StreamTokenizer.TT_WORD || in.ttype == StreamTokenizer.TT_NUMBER || in.ttype == '"') { if (in.ttype == StreamTokenizer.TT_NUMBER) { str = "" + Math.round(in.nval); } else { str = in.sval; } if (convertJoinMeet && level > 1) { str = stringSubstitute(str, joinStr, joinSign); str = stringSubstitute(str, meetStr, meetSign); } if (level == 1) { name = new String(str); } if (level == 2) { labels.addElement(str); currentElt = str; } if (level == 3) { upperCovers.addElement(str); } if (level == 4) { if (first) { upperCovers.addElement(str); cover = str; first = false; } else { edgeColors.put(new Edge(currentElt, cover), str); } } } if (in.ttype == '(') { level++; if (level == 3) upperCovers = new Vector(); } if (in.ttype == ')') { level--; if (level == 3) first = true; if (level == 2) upperCoversVector.addElement(upperCovers); if (level == 0) { if (latStream != null) latStream.close(); return; } } } }
|
00
|
Code Sample 1:
public static void main(String[] args) { try { Transaction transaction = session.beginTransaction(); URL url1 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/keren.jpg"); HttpURLConnection conn1 = (HttpURLConnection) url1.openConnection(); conn1.connect(); Users keren = new Users("kerenhaas@gmail.com", "123456", "keren", null, "sokolov 14 Raanana", Hibernate.createBlob(conn1.getInputStream(), conn1.getContentLength()), "about keren", "admin", false); session.save(keren); session.flush(); session.refresh(keren); URL url2 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/alex.jpg"); HttpURLConnection conn2 = (HttpURLConnection) url2.openConnection(); Users alex = new Users("alex.uretsky@mail.huji.ac.il", "123456", "alex", null, null, Hibernate.createBlob(conn2.getInputStream(), conn2.getContentLength()), null, "admin", false); session.save(alex); session.flush(); session.refresh(alex); URL url3 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/julia.jpg"); HttpURLConnection conn3 = (HttpURLConnection) url3.openConnection(); conn3.connect(); Users julia = new Users("juliasht@gmail.com", "123456", "julia", null, null, Hibernate.createBlob(conn3.getInputStream(), conn3.getContentLength()), null, "admin", false); session.save(julia); session.flush(); session.refresh(julia); URL url4 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/meir.jpg"); HttpURLConnection conn4 = (HttpURLConnection) url4.openConnection(); conn4.connect(); Users meir = new Users("meir.spielrein@mail.huji.ac.il", "123456", "meir", null, null, Hibernate.createBlob(conn4.getInputStream(), conn4.getContentLength()), null, "admin", false); session.save(meir); session.flush(); session.refresh(meir); URL url5 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/miki.jpg"); HttpURLConnection conn5 = (HttpURLConnection) url5.openConnection(); conn5.connect(); Users miki = new Users("miki.shifman@mail.huji.ac.il", "123456", "miki", null, null, Hibernate.createBlob(conn5.getInputStream(), conn5.getContentLength()), null, "admin", false); session.save(miki); session.flush(); session.refresh(miki); URL url6 = new URL("http://www.cs.huji.ac.il/~keren_ha/J2EE/tamar.jpg"); HttpURLConnection conn6 = (HttpURLConnection) url6.openConnection(); conn6.connect(); Users tami = new Users("taamar@gmail.com", "123456", "tami", null, null, Hibernate.createBlob(conn6.getInputStream(), conn6.getContentLength()), null, "admin", false); session.save(tami); session.flush(); session.refresh(tami); Lists basicComplexity = new Lists("Complexity", "Basic"); session.save(basicComplexity); Lists mediumComplexity = new Lists("Complexity", "Medium"); session.save(mediumComplexity); Lists highComplexity = new Lists("Complexity", "High"); session.save(highComplexity); Lists chefComplexity = new Lists("Complexity", "Chef"); session.save(chefComplexity); Lists appetizers = new Lists("DishType", "Appetizers"); session.save(appetizers); Lists firstCourse = new Lists("DishType", "First Course"); session.save(firstCourse); Lists mainCourse = new Lists("DishType", "Main Course"); session.save(mainCourse); Lists dessert = new Lists("DishType", "Dessert"); session.save(dessert); Lists cocktails = new Lists("DishType", "Cocktails"); session.save(cocktails); System.out.println("2 : " + session.isOpen()); Lists italian = new Lists("Cuisine", "Italian"); session.save(italian); Lists chinese = new Lists("Cuisine", "Chinese"); session.save(chinese); Lists indian = new Lists("Cuisine", "Indian"); session.save(indian); Lists french = new Lists("Cuisine", "French"); session.save(french); Lists thai = new Lists("Cuisine", "Thai"); session.save(thai); Lists arabic = new Lists("Cuisine", "Arabic"); session.save(arabic); Lists israeli = new Lists("Cuisine", "Israeli"); session.save(israeli); Lists other = new Lists("Cuisine", "Other"); session.save(other); Ingredients flour = new Ingredients("flour"); session.save(flour); Ingredients sugar = new Ingredients("white sugar"); session.save(sugar); Ingredients bakingPower = new Ingredients("baking powder"); session.save(bakingPower); Ingredients groundNutmeg = new Ingredients("ground nutmeg"); session.save(groundNutmeg); Ingredients salt = new Ingredients("salt"); session.save(salt); Ingredients pepper = new Ingredients("pepper"); session.save(pepper); Ingredients egg = new Ingredients("egg"); session.save(egg); Ingredients milk = new Ingredients("milk"); session.save(milk); Ingredients butter = new Ingredients("butter"); session.save(butter); Ingredients groundCinnamon = new Ingredients("ground cinnamon"); session.save(groundCinnamon); Ingredients strawberries = new Ingredients("strawberries"); session.save(strawberries); Ingredients bisquick = new Ingredients("bisquick"); session.save(bisquick); Ingredients whippedCream = new Ingredients("Whipped Cream"); session.save(whippedCream); Ingredients potato = new Ingredients("potato"); session.save(potato); Ingredients carrot = new Ingredients("carrot"); session.save(carrot); Ingredients onion = new Ingredients("onion"); session.save(onion); Ingredients ketchup = new Ingredients("ketchup"); session.save(ketchup); Ingredients mustard = new Ingredients("mustard"); session.save(mustard); Ingredients cookingCream = new Ingredients("Cooking Cream"); session.save(cookingCream); Ingredients bread = new Ingredients("bread"); session.save(bread); Ingredients caviar = new Ingredients("caviar"); session.save(caviar); Ingredients foigra = new Ingredients("foigra"); session.save(foigra); Ingredients vodka = new Ingredients("vodka"); session.save(vodka); Ingredients orangeJuice = new Ingredients("orangeJuice"); session.save(orangeJuice); Ingredients ribs = new Ingredients("ribs"); session.save(ribs); Ingredients tomato = new Ingredients("tomato"); session.save(tomato); Ingredients cucumber = new Ingredients("cucumber"); session.save(cucumber); Ingredients oliveoil = new Ingredients("olive oil"); session.save(oliveoil); Ingredients chickenBreast = new Ingredients("chicken Breast"); session.save(chickenBreast); Ingredients apple = new Ingredients("apple"); session.save(apple); Ingredients vanilla = new Ingredients("vanilla"); session.save(vanilla); String description; description = "These muffins are delicious! The cinnamon sugar topping flavors them perfectly. This is my 10 year old brother's favorite recipe"; Recipes rec1 = addRecipe(basicComplexity, description, "French Breakfast Muffins", keren, 10, 25, 12, dessert, "http://www.cs.huji.ac.il/~keren_ha/J2EE/muffins.jpg", Arrays.asList("Preheat oven to 350 degrees F (175 degrees C). Grease muffin cups or line with paper muffin liners.", "In a medium mixing bowl, stir together flour, 1/2 cup sugar, baking powder, nutmeg and salt. Make a well in the center of the mixture. Stir together egg, milk and 1/3 cup melted butter. Add egg mixture to flour mixture; stir until just moistened (batter may be lumpy). Spoon batter into prepared muffin cups.", "Bake in preheated oven for 20 to 25 minutes. Meanwhile, combine 1/4 cup sugar, cinnamon When muffins are finished baking, dip tops of muffins in the melted butter, and then in the cinnamon sugar mixture. Serve warm.")); createRecipeIngredients(rec1, flour, 1.5, "cups"); createRecipeIngredients(rec1, sugar, 0.5, "cups"); createRecipeIngredients(rec1, bakingPower, 1.5, "teaspoons"); createRecipeIngredients(rec1, groundNutmeg, 0.25, "teaspoons"); createRecipeIngredients(rec1, salt, 0.125, "teaspoons"); createRecipeIngredients(rec1, egg, 1, "lightly beaten"); createRecipeIngredients(rec1, milk, 0.5, "cups"); createRecipeIngredients(rec1, butter, 0.33, "cups"); createRecipeIngredients(rec1, groundCinnamon, 0.25, "cups"); createRecipeIngredients(rec1, groundCinnamon, 0.5, "teaspoon"); createRecipeIngredients(rec1, sugar, 0.33, "cups"); session.flush(); session.refresh(rec1); description = "This dish leaves even the biggest pasta lover satisfied. Fresh vegetables make this dish wonderful and it's easy to add meat to if you wish."; Recipes rec2 = addRecipe(mediumComplexity, description, "Veggie Pasta Minus the Pasta", alex, 30, 40, 6, mainCourse, "http://2.bp.blogspot.com/_wAVccjOeYzc/R4KYRa5MkLI/AAAAAAAAGz8/WeosqyuyjoQ/s400/vegetarian-tofu-curry-recipe+(13).JPG", Arrays.asList("Preheat an oven to 350 degrees F (175 degrees C). Arrange the tomatoes on a baking sheet with the cut sides facing up. ", "Roast the tomatoes in the preheated oven until cooked through and slightly browned on the underside, about 15 minutes. ", "Place squash halves face down in glass baking dish with the water; cover with plastic wrap. Microwave on High for 8 minutes. Leave covered and set aside. Once the squash is cool enough to handle, scrape in strands into a large bowl with a fork; season with salt and pepper and toss with 1 tablespoon olive oil. ", "Heat the remaining 2 tablespoons olive oil in a large skillet over medium-low heat; cook and stir the garlic, basil, and Italian seasoning in the oil until the garlic is softened, about 10 minutes. Add the onion, green bell pepper, eggplant, and carrot to the garlic; increase heat to medium. Continue cooking and stirring until the vegetables are nearly tender, 10 to 15 minutes. Mix the tomatoes and white wine into the vegetable mixture; cook another 2 to 3 minutes. Transfer the vegetables to the bowl with the spaghetti squash; gently toss together.")); createRecipeIngredients(rec2, flour, 1.5, "cups"); createRecipeIngredients(rec2, sugar, 0.5, "cups"); createRecipeIngredients(rec2, bakingPower, 1.5, "teaspoons"); createRecipeIngredients(rec2, groundNutmeg, 0.25, "teaspoons"); createRecipeIngredients(rec2, salt, 0.125, "teaspoons"); createRecipeIngredients(rec2, egg, 1, "lightly beaten"); createRecipeIngredients(rec2, milk, 0.5, "cups"); createRecipeIngredients(rec2, butter, 0.33, "cups"); createRecipeIngredients(rec2, groundCinnamon, 0.25, "cups"); createRecipeIngredients(rec2, groundCinnamon, 0.5, "teaspoon"); createRecipeIngredients(rec2, sugar, 0.33, "cups"); createComment(rec2, 1, julia, "This dish was extremely disappointing. I was very optimistic looking at the ingredient list, but after putting it all together, there was a profound lack of flavor. We eat a good deal of vegetable dishes, but this is not one we will be repeating."); createComment(rec2, 4, alex, "Very good, I also think to use less butter."); session.flush(); session.refresh(rec2); description = "A finger licking good strawberry cake!"; Recipes rec3 = addRecipe(basicComplexity, description, "Strawberry short cake", alex, 60, 70, 12, dessert, "http://static.open.salon.com/files/coconut_strawberry_cake1226877577.jpg", Arrays.asList("Sprinkle strawberries with 2/3 cups sugar. Let stand 1 hour ", "Heat over to 425 degrees.", "Mix all ingredients and place in the over", "Slice it and eat up!")); createRecipeIngredients(rec3, strawberries, 1.5, "cups"); createRecipeIngredients(rec3, sugar, 0.66, "cups"); createRecipeIngredients(rec3, bisquick, 2, "boxese"); createRecipeIngredients(rec3, sugar, 3, "tablespoons"); createRecipeIngredients(rec3, milk, 0.5, "cups"); createRecipeIngredients(rec3, whippedCream, 0.75, "cups"); createComment(rec3, 5, julia, "Best cake I ever had!!! Kudos!!"); session.flush(); session.refresh(rec3); description = "My secret Barbecue Beef Short Ribs recipe revealed!"; Recipes rec4 = addRecipe(highComplexity, description, "Short Ribs", meir, 70, 500, 6, mainCourse, "http://farm2.static.flickr.com/1310/1237575824_9068241a81.jpg", Arrays.asList("Put the potatoes and carrots in a large slow cooker", "Top with the onion wedges then the beef", "Combine the ketchup, , mustrard and salt", "Put ofver the beef", "Cook on LOW for 8 to 10 hours")); createRecipeIngredients(rec4, potato, 10, "pieces"); createRecipeIngredients(rec4, carrot, 1, "cups"); createRecipeIngredients(rec4, onion, 2, "units"); createRecipeIngredients(rec4, ribs, 3.5, "pounds"); createRecipeIngredients(rec4, ketchup, 1, "cups"); createRecipeIngredients(rec4, mustard, 0.5, "teaspoon"); createComment(rec4, 4, keren, "My whole family loved it!"); createComment(rec4, 5, alex, "This was outstanding, will definitely use this recipe often. I used chicken legs as that was what I had and it worked great. thanks!!!!"); session.flush(); session.refresh(rec4); description = "a simple, yet yasty, Salad"; Recipes rec5 = addRecipe(basicComplexity, description, "Garden Salad", alex, 10, 15, 6, firstCourse, "http://ww-recipes.net/wp-content/uploads/2008/09/weight-watchers-arabic-salad-recipe.jpg", Arrays.asList("Slice the tomatoes to cubes", "Slice the cucumbers to julian strips", "add a pinch salt and pepper", "top with olive oil")); createRecipeIngredients(rec5, tomato, 3, "pieces"); createRecipeIngredients(rec5, cucumber, 3, "pieces"); createRecipeIngredients(rec5, oliveoil, 2, "tablespoons"); createRecipeIngredients(rec5, salt, 1, "pinch"); createRecipeIngredients(rec5, pepper, 1, "pinch"); createComment(rec5, 5, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec5); description = "Creme Brule - the full recipe! no shortcuts ;) "; Recipes rec7 = addRecipe(highComplexity, description, "Creme brule", miki, 30, 200, 6, dessert, "http://www.cookingforengineers.com/hello/259/958/640/IMG_3335_sharp.jpg", Arrays.asList("bring the cooking cream to boiling temperature", "insert vanilla stick", "whisk eggs with sugar", "add cream to eggs CAREFULLY", "put in over for 30 minutes, then to the fridge for 4 hours")); createRecipeIngredients(rec7, cookingCream, 2, "cartons"); createRecipeIngredients(rec7, egg, 3, "yolks"); createRecipeIngredients(rec7, sugar, 2, "tablespoons"); createRecipeIngredients(rec7, vanilla, 1, "stick"); createComment(rec7, 4, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec7); description = "some toasts with foigra to get the meal started"; Recipes rec8 = addRecipe(basicComplexity, description, "foigra on toast", alex, 15, 15, 6, appetizers, "http://www.italiq-expos.com/news/images/Gastronomie/Foie-gras/assiette-foie-gras.jpg", Arrays.asList("cut bread into oval slices", "place in toaster until a golden brown color in formed", "speard some foigra pate on the toasts", "optional - add some baluga caviar on top")); createRecipeIngredients(rec8, bread, 6, "slices"); createRecipeIngredients(rec8, foigra, 1, "can"); createRecipeIngredients(rec8, caviar, 1, "minijar"); createComment(rec8, 5, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec8); description = "delicious diatetic chicken steak"; Recipes rec9 = addRecipe(mediumComplexity, description, "chicken steak", meir, 15, 20, 2, mainCourse, "http://4.bp.blogspot.com/_jhlSdMizhlU/RdOVtm-0QAI/AAAAAAAAABg/81W-JvXOACI/s400/Chicken_Steak.jpg", Arrays.asList("Heat a frying pan with some (preferably olive) oil", "when the oil is hot, place the chicken and onions in the middle", "fry on both sides on medium flame until it starts to turn golden", "season with salt and pepper")); createRecipeIngredients(rec9, chickenBreast, 2, "pieces"); createRecipeIngredients(rec9, onion, 1, "piece"); createRecipeIngredients(rec9, salt, 1, "pinch"); createRecipeIngredients(rec9, pepper, 1, "pinch"); createComment(rec9, 5, julia, "Delicious and so easy to make!"); session.flush(); session.refresh(rec9); Favorites fav1 = new Favorites(keren, rec1, null); session.save(fav1); Favorites fav2 = new Favorites(keren, rec2, null); session.save(fav2); Favorites fav3 = new Favorites(keren, rec3, null); session.save(fav3); Favorites fav4 = new Favorites(keren, rec4, null); session.save(fav4); Favorites fav5 = new Favorites(alex, rec4, null); session.save(fav5); Favorites fav6 = new Favorites(alex, rec2, null); session.save(fav6); RecentlyViewed recViewed1 = new RecentlyViewed(keren, rec1, new Date()); session.save(recViewed1); RecentlyViewed recViewed2 = new RecentlyViewed(keren, rec2, new Date()); session.save(recViewed2); Friends friend1 = new Friends(keren, alex, true); session.save(friend1); Friends friend2 = new Friends(alex, keren, true); session.save(friend2); Friends friend3 = new Friends(keren, julia, false); session.save(friend3); Friends friend4 = new Friends(keren, meir, true); session.save(friend4); Friends friend5 = new Friends(meir, keren, true); session.save(friend5); Friends friend6 = new Friends(tami, keren, false); session.save(friend6); transaction.commit(); } catch (Exception e) { e.printStackTrace(); } finally { session.flush(); session.close(); } }
Code Sample 2:
public void test(TestHarness harness) { harness.checkPoint("TestOfMD4"); try { Security.addProvider(new JarsyncProvider()); algorithm = MessageDigest.getInstance("BrokenMD4", "JARSYNC"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); throw new Error(x); } try { for (int i = 0; i < 64; i++) algorithm.update((byte) 'a'); byte[] md = algorithm.digest(); String exp = "755cd64425f260e356f5303ee82a2d5f"; harness.check(exp.equals(Util.toHexString(md)), "testSixtyFourA"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); } try { harness.verbose("NOTE: This test may take a while."); for (int i = 0; i < 536870913; i++) algorithm.update((byte) 'a'); byte[] md = algorithm.digest(); String exp = "b6cea9f528a85963f7529a9e3a2153db"; harness.check(exp.equals(Util.toHexString(md)), "test536870913A"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); } try { byte[] md = algorithm.digest("a".getBytes()); String exp = "bde52cb31de33e46245e05fbdbd6fb24"; harness.check(exp.equals(Util.toHexString(md)), "testA"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testA"); } try { byte[] md = algorithm.digest("abc".getBytes()); String exp = "a448017aaf21d8525fc10ae87aa6729d"; harness.check(exp.equals(Util.toHexString(md)), "testABC"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testABC"); } try { byte[] md = algorithm.digest("message digest".getBytes()); String exp = "d9130a8164549fe818874806e1c7014b"; harness.check(exp.equals(Util.toHexString(md)), "testMessageDigest"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testMessageDigest"); } try { byte[] md = algorithm.digest("abcdefghijklmnopqrstuvwxyz".getBytes()); String exp = "d79e1c308aa5bbcdeea8ed63df412da9"; harness.check(exp.equals(Util.toHexString(md)), "testAlphabet"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testAlphabet"); } try { byte[] md = algorithm.digest("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".getBytes()); String exp = "043f8582f241db351ce627e153e7f0e4"; harness.check(exp.equals(Util.toHexString(md)), "testAsciiSubset"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testAsciiSubset"); } try { byte[] md = algorithm.digest("12345678901234567890123456789012345678901234567890123456789012345678901234567890".getBytes()); String exp = "e33b4ddc9c38f2199c3e7b164fcc0536"; harness.check(exp.equals(Util.toHexString(md)), "testEightyNumerics"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testEightyNumerics"); } try { algorithm.update("a".getBytes(), 0, 1); clone = (MessageDigest) algorithm.clone(); byte[] md = algorithm.digest(); String exp = "bde52cb31de33e46245e05fbdbd6fb24"; harness.check(exp.equals(Util.toHexString(md)), "testCloning #1"); clone.update("bc".getBytes(), 0, 2); md = clone.digest(); exp = "a448017aaf21d8525fc10ae87aa6729d"; harness.check(exp.equals(Util.toHexString(md)), "testCloning #2"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testCloning"); } }
|
00
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public static String generate(String source) { byte[] SHA = new byte[20]; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(source.getBytes()); SHA = digest.digest(); } catch (NoSuchAlgorithmException e) { System.out.println("NO SUCH ALGORITHM EXCEPTION: " + e.getMessage()); } CommunicationLogger.warning("SHA1 DIGEST: " + SHA); return SHA.toString(); }
|
00
|
Code Sample 1:
public FileBean create(MimeTypeBean mimeType, SanBean san) throws SQLException { long fileId = 0; DataSource ds = getDataSource(DEFAULT_DATASOURCE); Connection conn = ds.getConnection(); try { conn.setAutoCommit(false); Statement stmt = conn.createStatement(); stmt.execute(NEXT_FILE_ID); ResultSet rs = stmt.getResultSet(); while (rs.next()) { fileId = rs.getLong(NEXTVAL); } PreparedStatement pstmt = conn.prepareStatement(INSERT_FILE); pstmt.setLong(1, fileId); pstmt.setLong(2, mimeType.getId()); pstmt.setLong(3, san.getId()); pstmt.setLong(4, WORKFLOW_ATTENTE_VALIDATION); int nbrow = pstmt.executeUpdate(); if (nbrow == 0) { throw new SQLException(); } conn.commit(); closeRessources(conn, pstmt); } catch (SQLException e) { log.error("Can't FileDAOImpl.create " + e.getMessage()); conn.rollback(); throw e; } FileBean fileBean = new FileBean(); return fileBean; }
Code Sample 2:
public static String getMd5Hash(String text) { StringBuffer result = new StringBuffer(32); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); Formatter f = new Formatter(result); byte[] digest = md5.digest(); for (int i = 0; i < digest.length; i++) { f.format("%02x", new Object[] { new Byte(digest[i]) }); } } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return result.toString(); }
|
11
|
Code Sample 1:
protected void copyFile(File source, File destination) throws ApplicationException { try { OutputStream out = new FileOutputStream(destination); DataInputStream in = new DataInputStream(new FileInputStream(source)); byte[] buf = new byte[8192]; for (int nread = in.read(buf); nread > 0; nread = in.read(buf)) { out.write(buf, 0, nread); } in.close(); out.close(); } catch (IOException e) { throw new ApplicationException("Can't copy file " + source + " to " + destination); } }
Code Sample 2:
public static void copyFile(File source, File destination) throws IOException { if (source == null) { String message = Logging.getMessage("nullValue.SourceIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (destination == null) { String message = Logging.getMessage("nullValue.DestinationIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fic, foc; try { fis = new FileInputStream(source); fic = fis.getChannel(); fos = new FileOutputStream(destination); foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); fos.flush(); fis.close(); fos.close(); } finally { WWIO.closeStream(fis, source.getPath()); WWIO.closeStream(fos, destination.getPath()); } }
|
11
|
Code Sample 1:
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()); }
Code Sample 2:
public DataRecord addRecord(InputStream input) throws DataStoreException { File temporary = null; try { temporary = newTemporaryFile(); DataIdentifier tempId = new DataIdentifier(temporary.getName()); usesIdentifier(tempId); long length = 0; MessageDigest digest = MessageDigest.getInstance(DIGEST); OutputStream output = new DigestOutputStream(new FileOutputStream(temporary), digest); try { length = IOUtils.copyLarge(input, output); } finally { output.close(); } DataIdentifier identifier = new DataIdentifier(digest.digest()); File file; synchronized (this) { usesIdentifier(identifier); file = getFile(identifier); System.out.println("new file name: " + file.getName()); File parent = file.getParentFile(); System.out.println("parent file: " + file.getParentFile().getName()); if (!parent.isDirectory()) { parent.mkdirs(); } if (!file.exists()) { temporary.renameTo(file); if (!file.exists()) { throw new IOException("Can not rename " + temporary.getAbsolutePath() + " to " + file.getAbsolutePath() + " (media read only?)"); } } else { long now = System.currentTimeMillis(); if (file.lastModified() < now) { file.setLastModified(now); } } if (!file.isFile()) { throw new IOException("Not a file: " + file); } if (file.length() != length) { throw new IOException(DIGEST + " collision: " + file); } } inUse.remove(tempId); return new FileDataRecord(identifier, file); } catch (NoSuchAlgorithmException e) { throw new DataStoreException(DIGEST + " not available", e); } catch (IOException e) { throw new DataStoreException("Could not add record", e); } finally { if (temporary != null) { temporary.delete(); } } }
|
11
|
Code Sample 1:
private void pack() { String szImageDir = m_szBasePath + "Images"; File fImageDir = new File(szImageDir); fImageDir.mkdirs(); String ljIcon = System.getProperty("user.home"); ljIcon += System.getProperty("file.separator") + "MochaJournal" + System.getProperty("file.separator") + m_szUsername + System.getProperty("file.separator") + "Cache"; File fUserDir = new File(ljIcon); File[] fIcons = fUserDir.listFiles(); int iSize = fIcons.length; for (int i = 0; i < iSize; i++) { try { File fOutput = new File(fImageDir, fIcons[i].getName()); if (!fOutput.exists()) { fOutput.createNewFile(); FileOutputStream fOut = new FileOutputStream(fOutput); FileInputStream fIn = new FileInputStream(fIcons[i]); while (fIn.available() > 0) fOut.write(fIn.read()); } } catch (IOException e) { System.err.println(e); } } try { FileOutputStream fOut; InputStream fLJIcon = getClass().getResourceAsStream("/org/homedns/krolain/MochaJournal/Images/userinfo.gif"); File fLJOut = new File(fImageDir, "user.gif"); if (!fLJOut.exists()) { fOut = new FileOutputStream(fLJOut); while (fLJIcon.available() > 0) fOut.write(fLJIcon.read()); } fLJIcon = getClass().getResourceAsStream("/org/homedns/krolain/MochaJournal/Images/communitynfo.gif"); fLJOut = new File(fImageDir, "comm.gif"); if (!fLJOut.exists()) { fOut = new FileOutputStream(fLJOut); while (fLJIcon.available() > 0) fOut.write(fLJIcon.read()); } fLJIcon = getClass().getResourceAsStream("/org/homedns/krolain/MochaJournal/Images/icon_private.gif"); fLJOut = new File(fImageDir, "icon_private.gif"); if (!fLJOut.exists()) { fOut = new FileOutputStream(fLJOut); while (fLJIcon.available() > 0) fOut.write(fLJIcon.read()); } fLJIcon = getClass().getResourceAsStream("/org/homedns/krolain/MochaJournal/Images/icon_protected.gif"); fLJOut = new File(fImageDir, "icon_protected.gif"); if (!fLJOut.exists()) { fOut = new FileOutputStream(fLJOut); while (fLJIcon.available() > 0) fOut.write(fLJIcon.read()); } } catch (IOException e) { System.err.println(e); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
public Main(String[] args) { boolean encrypt = false; if (args[0].compareTo("-e") == 0) { encrypt = true; } else if (args[0].compareTo("-d") == 0) { encrypt = false; } else { System.out.println("first argument is invalid"); System.exit(-2); } char[] password = new char[args[2].length()]; for (int i = 0; i < args[2].length(); i++) { password[i] = (char) args[2].getBytes()[i]; } try { InitializeCipher(encrypt, password); } catch (Exception e) { System.out.println("error initializing cipher"); System.exit(-3); } try { InputStream is = new FileInputStream(args[1]); OutputStream os; int read, max = 10; byte[] buffer = new byte[max]; if (encrypt) { os = new FileOutputStream(args[1] + ".enc"); os = new CipherOutputStream(os, cipher); } else { os = new FileOutputStream(args[1] + ".dec"); is = new CipherInputStream(is, cipher); } read = is.read(buffer); while (read != -1) { os.write(buffer, 0, read); read = is.read(buffer); } while (read == max) ; os.close(); is.close(); System.out.println(new String(buffer)); } catch (Exception e) { System.out.println("error encrypting/decrypting message:"); e.printStackTrace(); System.exit(-4); } System.out.println("done"); }
Code Sample 2:
@RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } }
|
11
|
Code Sample 1:
public static String generateHash(String message) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException { MessageDigest digest; digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(message.getBytes("iso-8859-1"), 0, message.length()); byte[] output = new byte[20]; digest.digest(output, 0, output.length); return convertToHex(output); }
Code Sample 2:
public static final String Digest(String credentials, String algorithm, String encoding) { try { MessageDigest md = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); if (encoding == null) { md.update(credentials.getBytes()); } else { md.update(credentials.getBytes(encoding)); } return (HexUtils.convert(md.digest())); } catch (Exception ex) { log.error(ex); return credentials; } }
|
11
|
Code Sample 1:
public static String getHashedPasswordTc(String password) throws java.security.NoSuchAlgorithmException { java.security.MessageDigest d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(password.getBytes()); byte[] buf = d.digest(); char[] cbf = new char[buf.length * 2]; for (int jj = 0, kk = 0; jj < buf.length; jj++) { cbf[kk++] = "0123456789abcdef".charAt((buf[jj] >> 4) & 0x0F); cbf[kk++] = "0123456789abcdef".charAt(buf[jj] & 0x0F); } return new String(cbf); }
Code Sample 2:
public static String md5Encrypt(String valueToEncrypted) { String encryptedValue = ""; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(valueToEncrypted.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); encryptedValue = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } return encryptedValue; }
|
11
|
Code Sample 1:
public static boolean dumpFile(String from, File to, String lineBreak) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(from))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to))); String line = null; while ((line = in.readLine()) != null) out.write(Main.getInstance().resolve(line) + lineBreak); in.close(); out.close(); } catch (Exception e) { Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e)); return false; } return true; }
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 String encrypt(String password) { if (password.length() == 40) { return password; } if (salt != null) { password = password + salt; } MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e.getMessage(), e); } messageDigest.reset(); messageDigest.update(password.getBytes()); final byte[] bytes = messageDigest.digest(); String encrypted = new BigInteger(1, bytes).toString(16); if (encrypted.length() < 40) { final StringBuilder builder = new StringBuilder(encrypted); while (builder.length() < 40) { builder.insert(0, '0'); } encrypted = builder.toString(); } return encrypted; }
Code Sample 2:
private boolean loadNodeData(NodeInfo info) { String query = mServer + "load.php" + ("?id=" + info.getId()) + ("&mask=" + NodePropertyFlag.Data); boolean rCode = false; try { URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(false); conn.setRequestMethod("GET"); setCredentials(conn); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream stream = conn.getInputStream(); byte[] data = new byte[0], temp = new byte[1024]; boolean eof = false; while (!eof) { int read = stream.read(temp); if (read > 0) { byte[] buf = new byte[data.length + read]; System.arraycopy(data, 0, buf, 0, data.length); System.arraycopy(temp, 0, buf, data.length, read); data = buf; } else if (read < 0) { eof = true; } } info.setData(data); info.setMIMEType(new MimeType(conn.getContentType())); rCode = true; stream.close(); } } catch (Exception ex) { } return rCode; }
|
11
|
Code Sample 1:
static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; }
Code Sample 2:
public void merge(VMImage image, VMSnapShot another) throws VMException { if (path == null || another.getPath() == null) throw new VMException("EmuVMSnapShot is NULL!"); logging.debug(LOG_NAME, "merge images " + path + " and " + another.getPath()); File target = new File(path); File src = new File(another.getPath()); if (target.isDirectory() || src.isDirectory()) return; try { FileInputStream in = new FileInputStream(another.getPath()); FileChannel inChannel = in.getChannel(); FileOutputStream out = new FileOutputStream(path, true); FileChannel outChannel = out.getChannel(); outChannel.transferFrom(inChannel, 0, inChannel.size()); outChannel.close(); inChannel.close(); } catch (IOException e) { throw new VMException(e); } }
|
11
|
Code Sample 1:
public static Debugger getDebugger(InetAddress host, int port, String password) throws IOException { try { Socket s = new Socket(host, port); try { ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream()); ObjectInputStream in = new ObjectInputStream(s.getInputStream()); int protocolVersion = in.readInt(); if (protocolVersion > 220) { throw new IOException("Incompatible protocol version " + protocolVersion + ". At most 220 was expected."); } byte[] challenge = (byte[]) in.readObject(); MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); md.update(challenge); out.writeObject(md.digest()); return new LocalDebuggerProxy((Debugger) in.readObject()); } finally { s.close(); } } catch (IOException e) { throw e; } catch (Exception e) { throw new UndeclaredThrowableException(e); } }
Code Sample 2:
public static String sha1Hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; }
|
00
|
Code Sample 1:
public static String getAnalysisServletOutput(String inputXml) { java.io.BufferedWriter bWriter = null; URLConnection connection = null; String resultString = ""; bWriter = null; connection = null; String target = ServletConstant.ANALYSIS_SERVLET; String message = "\nTHIS MESSAGE IS SENT FROM THE CLIENT APPLET \n\r"; try { URL url = new URL(target); connection = (HttpURLConnection) url.openConnection(); ((HttpURLConnection) connection).setRequestMethod("POST"); connection.setDoOutput(true); bWriter = new java.io.BufferedWriter(new java.io.OutputStreamWriter(connection.getOutputStream())); bWriter.write(message); bWriter.flush(); bWriter.close(); java.io.BufferedReader bReader = null; bReader = new java.io.BufferedReader(new java.io.InputStreamReader(connection.getInputStream())); String line; StringBuffer sb = new StringBuffer(); while ((line = bReader.readLine()) != null) { sb.append(line); } resultString = sb.toString(); bReader.close(); ((HttpURLConnection) connection).disconnect(); } catch (java.io.IOException ex) { resultString += ex.toString(); } finally { if (bWriter != null) { try { bWriter.close(); } catch (Exception ex) { resultString += ex.toString(); } } if (connection != null) { try { ((HttpURLConnection) connection).disconnect(); } catch (Exception ex) { resultString += ex.toString(); } } } return resultString; }
Code Sample 2:
public static String getMd5Digest(String pInput) { try { MessageDigest lDigest = MessageDigest.getInstance("MD5"); lDigest.update(pInput.getBytes()); BigInteger lHashInt = new BigInteger(1, lDigest.digest()); return String.format("%1$032x", lHashInt).toLowerCase(); } catch (NoSuchAlgorithmException lException) { throw new RuntimeException(lException); } }
|
11
|
Code Sample 1:
public static void httpOnLoad(String fileName, String urlpath) throws Exception { URL url = new URL(urlpath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); int responseCode = conn.getResponseCode(); System.err.println("Code : " + responseCode); System.err.println("getResponseMessage : " + conn.getResponseMessage()); if (responseCode >= 400) { return; } int threadSize = 3; int fileLength = conn.getContentLength(); System.out.println("fileLength:" + fileLength); int block = fileLength / threadSize; int lastBlock = fileLength - (block * (threadSize - 1)); conn.disconnect(); File file = new File(fileName); RandomAccessFile randomFile = new RandomAccessFile(file, "rw"); randomFile.setLength(fileLength); randomFile.close(); for (int i = 2; i < 3; i++) { int startPosition = i * block; if (i == threadSize - 1) { block = lastBlock; } RandomAccessFile threadFile = new RandomAccessFile(file, "rw"); threadFile.seek(startPosition); new TestDownFile(url, startPosition, threadFile, block).start(); } }
Code Sample 2:
@Test public void testDocumentDownloadExcel() throws IOException { if (uploadedExcelDocumentID == null) { fail("Document Upload Test should run first"); } String downloadLink = GoogleDownloadLinkGenerator.generateXlDownloadLink(uploadedExcelDocumentID); URL url = new URL(downloadLink); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream input = url.openStream(); FileWriter fw = new FileWriter("tmpOutput.kb"); Reader reader = new InputStreamReader(input); BufferedReader bufferedReader = new BufferedReader(reader); String strLine = ""; int count = 0; while (count < 10000) { strLine = bufferedReader.readLine(); if (strLine != null && strLine != "") { fw.write(strLine); } count++; } }
|
00
|
Code Sample 1:
private void bokActionPerformed(java.awt.event.ActionEvent evt) { Vector vret = this.uniformtitlepanel.getEnteredValuesKeys(); String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveUniformTitleSH("2", vret, patlib); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "UniformTitleSubjectHeadingServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } }
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()); } }
|
00
|
Code Sample 1:
public void adicionaCliente(ClienteBean cliente) { PreparedStatement pstmt = null; ResultSet rs = null; String sql = "insert into cliente(nome,cpf,telefone,cursoCargo,bloqueado,ativo,tipo) values(?,?,?,?,?,?,?)"; try { pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, cliente.getNome()); pstmt.setString(2, cliente.getCPF()); pstmt.setString(3, cliente.getTelefone()); pstmt.setString(4, cliente.getCursoCargo()); pstmt.setString(5, cliente.getBloqueado()); pstmt.setString(6, cliente.getAtivo()); pstmt.setString(7, cliente.getTipo()); pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); if (rs.next()) { cliente.setIdCliente(rs.getLong(1)); } connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao inserir cliente.", ex1); } throw new RuntimeException("Erro ao inserir cliente.", ex); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); } catch (SQLException ex) { throw new RuntimeException("Ocorreu um erro no banco de dados.", ex); } } }
Code Sample 2:
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); }
|
11
|
Code Sample 1:
public static Set<Street> getVias(String pURL) { Set<Street> result = new HashSet<Street>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniVia = "<calle>"; String finVia = "</calle>"; String iniCodVia = "<cv>"; String finCodVia = "</cv>"; String iniTipoVia = "<tv>"; String finTipoVia = "</tv>"; String iniNomVia = "<nv>"; String finNomVia = "</nv>"; boolean error = false; int ini, fin; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; Street via; while ((str = br.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniVia)) { via = new Street(); while ((str = br.readLine()) != null && !str.contains(finVia)) { if (str.contains(iniCodVia)) { ini = str.indexOf(iniCodVia) + iniCodVia.length(); fin = str.indexOf(finCodVia); via.setCodeStreet(Integer.parseInt(str.substring(ini, fin))); } if (str.contains(iniTipoVia)) { TypeStreet tipo = new TypeStreet(); if (!str.contains(finTipoVia)) tipo.setCodetpStreet(""); else { ini = str.indexOf(iniTipoVia) + iniTipoVia.length(); fin = str.indexOf(finTipoVia); tipo.setCodetpStreet(str.substring(ini, fin)); } tipo.setDescription(getDescripcionTipoVia(tipo.getCodetpStreet())); via.setTypeStreet(tipo); } if (str.contains(iniNomVia)) { ini = str.indexOf(iniNomVia) + iniNomVia.length(); fin = str.indexOf(finNomVia); via.setStreetName(str.substring(ini, fin).trim()); } } result.add(via); } } } br.close(); } catch (Exception e) { System.err.println(e); } return result; }
Code Sample 2:
public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
|
00
|
Code Sample 1:
private static String md5(String pwd) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(pwd.getBytes(), 0, pwd.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new Error(); } }
Code Sample 2:
private void writeToUrl(byte[] data, String url) throws IOException, MalformedURLException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); OutputStream out = connection.getOutputStream(); out.write(data); out.flush(); out.close(); }
|
00
|
Code Sample 1:
private String getPage(String urlString) throws Exception { if (pageBuffer.containsKey(urlString)) return pageBuffer.get(urlString); URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); BufferedReader in = null; StringBuilder page = new StringBuilder(); try { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException ioe) { logger.warn("Failed to read web page"); } finally { if (in != null) { in.close(); } } return page.toString(); }
Code Sample 2:
private void initURL() { try { log.fine("Checking: " + locator); URLConnection conn = URIFactory.url(locator).openConnection(); conn.setUseCaches(false); log.info(conn.getHeaderFields().toString()); String header = conn.getHeaderField(null); if (header.contains("404")) { log.info("404 file not found: " + locator); return; } if (header.contains("500")) { log.info("500 server error: " + locator); return; } if (conn.getContentLength() > 0) { byte[] buffer = new byte[50]; conn.getInputStream().read(buffer); if (new String(buffer).trim().startsWith("<!DOCTYPE")) return; } else if (conn.getContentLength() == 0) { exists = true; return; } exists = true; length = conn.getContentLength(); } catch (Exception ioe) { System.err.println(ioe); } }
|
11
|
Code Sample 1:
private void executeRequest(OperationContext context) throws java.lang.Throwable { long t1 = System.currentTimeMillis(); DirectoryParams params = context.getRequestOptions().getDirectoryOptions(); try { String srvCfg = context.getRequestContext().getApplicationConfiguration().getCatalogConfiguration().getParameters().getValue("openls.directory"); HashMap<String, String> poiProperties = params.getPoiProperties(); Set<String> keys = poiProperties.keySet(); Iterator<String> iter = keys.iterator(); StringBuffer filter = new StringBuffer(); while (iter.hasNext()) { String key = iter.next(); QueryFilter queryFilter = new QueryFilter(key, poiProperties.get(key)); filter.append(makePOIRequest(queryFilter)); } String sUrl = srvCfg + "/query?" + filter.toString(); LOGGER.info("REQUEST=\n" + sUrl); URL url = new URL(sUrl); URLConnection conn = url.openConnection(); String line = ""; String sResponse = ""; InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader rd = new BufferedReader(isr); while ((line = rd.readLine()) != null) { sResponse += line; } rd.close(); url = null; parsePOIResponse(sResponse, params); } catch (Exception p_e) { LOGGER.severe("Throwing exception" + p_e.getMessage()); throw p_e; } finally { long t2 = System.currentTimeMillis(); LOGGER.info("PERFORMANCE: " + (t2 - t1) + " ms spent performing service"); } }
Code Sample 2:
public static TestResponse post(String urlString, byte[] data, String contentType, String accept) throws IOException { HttpURLConnection httpCon = null; byte[] result = null; byte[] errorResult = null; try { URL url = new URL(urlString); httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("POST"); httpCon.setRequestProperty("Content-Type", contentType); httpCon.setRequestProperty("Accept", accept); if (data != null) { OutputStream output = httpCon.getOutputStream(); output.write(data); output.close(); } BufferedInputStream in = new BufferedInputStream(httpCon.getInputStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); int next = in.read(); while (next > -1) { os.write(next); next = in.read(); } os.flush(); result = os.toByteArray(); os.close(); } catch (IOException e) { e.printStackTrace(); } finally { InputStream errorStream = httpCon.getErrorStream(); if (errorStream != null) { BufferedInputStream errorIn = new BufferedInputStream(errorStream); ByteArrayOutputStream errorOs = new ByteArrayOutputStream(); int errorNext = errorIn.read(); while (errorNext > -1) { errorOs.write(errorNext); errorNext = errorIn.read(); } errorOs.flush(); errorResult = errorOs.toByteArray(); errorOs.close(); } return new TestResponse(httpCon.getResponseCode(), errorResult, result); } }
|
00
|
Code Sample 1:
public static void runDBUpdate() { if (!updateRunning) { if (updateJob != null) updateJob.cancel(); updateJob = new Job("Worm Database Update") { protected IStatus run(IProgressMonitor monitor) { try { updateRunning = true; distributor = getFromFile("[SERVER]", "csz", getAppPath() + "/server.ini"); MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini"); serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini"); if (MAC.equals("not_found") || serial.equals("not_found") || !serial.startsWith(distributor)) { try { MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini"); serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini"); } catch (Exception e) { System.out.println(e); } } else { try { url = new URL("http://" + getFromFile("[SERVER]", "url", getAppPath() + "/server.ini")); } catch (MalformedURLException e) { System.out.println(e); } download = "/download2.php?distributor=" + distributor + "&&mac=" + MAC + "&&serial=" + serial; readXML(); if (htmlMessage.contains("error")) { try { PrintWriter pw = new PrintWriter(getAppPath() + "/register.ini"); pw.write(""); pw.close(); } catch (IOException e) { System.out.println(e); } setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } } else { if (!getDBVersion().equals(latestVersion)) { try { OutputStream out = null; HttpURLConnection conn = null; InputStream in = null; int size; try { URL url = new URL(fileLoc); String outFile = getAppPath() + "/temp/" + getFileName(url); File oFile = new File(outFile); oFile.delete(); out = new BufferedOutputStream(new FileOutputStream(outFile)); monitor.beginTask("Connecting to NWD Server", 100); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(20000); conn.connect(); if (conn.getResponseCode() / 100 != 2) { System.out.println("Error: " + conn.getResponseCode()); return null; } monitor.worked(100); monitor.done(); size = conn.getContentLength(); monitor.beginTask("Download Worm Definition", size); in = conn.getInputStream(); byte[] buffer; String downloadedSize; long numWritten = 0; boolean status = true; while (status) { if (size - numWritten > 1024) { buffer = new byte[1024]; } else { buffer = new byte[(int) (size - numWritten)]; } int read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); numWritten += read; downloadedSize = Long.toString(numWritten / 1024) + " KB"; monitor.worked(read); monitor.subTask(downloadedSize + " of " + Integer.toString(size / 1024) + " KB"); if (size == numWritten) { status = false; } if (monitor.isCanceled()) return Status.CANCEL_STATUS; } if (in != null) { in.close(); } if (out != null) { out.close(); } try { ZipFile zFile = new ZipFile(outFile); Enumeration all = zFile.entries(); while (all.hasMoreElements()) { ZipEntry zEntry = (ZipEntry) all.nextElement(); long zSize = zEntry.getSize(); if (zSize > 0) { if (zEntry.getName().endsWith("script")) { InputStream instream = zFile.getInputStream(zEntry); FileOutputStream fos = new FileOutputStream(oldLoc[0]); int ch; while ((ch = instream.read()) != -1) { fos.write(ch); } instream.close(); fos.close(); } else if (zEntry.getName().endsWith("data")) { InputStream instream = zFile.getInputStream(zEntry); FileOutputStream fos = new FileOutputStream(oldLoc[1]); int ch; while ((ch = instream.read()) != -1) { fos.write(ch); } instream.close(); fos.close(); } } } File xFile = new File(outFile); xFile.deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } try { monitor.done(); monitor.beginTask("Install Worm Definition", 10000); monitor.worked(2500); CorePlugin.getDefault().getRawPacketHandler().removeRawPacketListener(p); p = null; if (!wormDB.getConn().isClosed()) { shutdownDB(); } System.out.println(wormDB.getConn().isClosed()); for (int i = 0; i < 2; i++) { try { Process pid = Runtime.getRuntime().exec("cmd /c copy \"" + oldLoc[i].replace("/", "\\") + "\" \"" + newLoc[i].replace("/", "\\") + "\"/y"); } catch (Exception e) { e.printStackTrace(); } new File(oldLoc[i]).deleteOnExit(); } monitor.worked(2500); initialArray(); p = new PacketPrinter(); CorePlugin.getDefault().getRawPacketHandler().addRawPacketListener(p); monitor.worked(2500); monitor.done(); setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction()); } } catch (Exception e) { setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } System.out.println(e); } finally { } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } e.printStackTrace(); } } else { cancel(); setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults1(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction1()); } } } } return Status.OK_STATUS; } catch (Exception e) { showResults2(); return Status.OK_STATUS; } finally { lock.release(); updateRunning = false; if (getValue("AUTO_UPDATE")) schedule(10800000); } } }; updateJob.schedule(); } }
Code Sample 2:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getproducts"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); String theString = new String(""); HttpGet request1 = new HttpGet(SERVICE_URI + "/json/getroutes/3165"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient1 = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString = new String(); String tempStringID = new String(); String tempStringName = new String(); String tempStringPrice = new String(); String tempStringSymbol = new String(); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); JSONObject json = new JSONObject(theString); Log.i("_GetPerson_", "<jsonobject>\n" + json.toString() + "\n</jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray; nameArray = json.getJSONArray("getProductsResult"); for (int i = 0; i < nameArray.length(); i++) { tempStringID = nameArray.getJSONObject(i).getString("ID"); tempStringName = nameArray.getJSONObject(i).getString("Name"); tempStringPrice = nameArray.getJSONObject(i).getString("Price"); tempStringSymbol = nameArray.getJSONObject(i).getString("Symbol"); this.dm.insertIntoProducts(tempStringID, tempStringName, tempStringPrice, tempStringSymbol); tempString = nameArray.getJSONObject(i).getString("Name") + "\n" + nameArray.getJSONObject(i).getString("Price") + "\n" + nameArray.getJSONObject(i).getString("Symbol"); vectorOfStrings.add(new String(tempString)); } int orderCount = vectorOfStrings.size(); String[] orderTimeStamps = new String[orderCount]; vectorOfStrings.copyInto(orderTimeStamps); } catch (Exception e) { e.printStackTrace(); } try { HttpResponse response1 = httpClient1.execute(request1); HttpEntity response1Entity = response1.getEntity(); InputStream stream1 = response1Entity.getContent(); BufferedReader reader1 = new BufferedReader(new InputStreamReader(stream1)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString1 = new String(); String tempStringAgent = new String(); String tempStringClient = new String(); String tempStringRoute = new String(); String tempStringZone = new String(); StringBuilder builder1 = new StringBuilder(); String line1; while ((line1 = reader1.readLine()) != null) { builder1.append(line1); } stream1.close(); theString = builder1.toString(); JSONObject json1 = new JSONObject(theString); Log.i("_GetPerson_", "<jsonobject>\n" + json1.toString() + "\n</jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray1; nameArray1 = json1.getJSONArray("GetRoutesByAgentResult"); for (int i = 0; i < nameArray1.length(); i++) { tempStringAgent = nameArray1.getJSONObject(i).getString("Agent"); tempStringClient = nameArray1.getJSONObject(i).getString("Client"); tempStringRoute = nameArray1.getJSONObject(i).getString("Route"); tempStringZone = nameArray1.getJSONObject(i).getString("Zone"); this.dm.insertIntoClients(tempStringAgent, tempStringClient, tempStringRoute, tempStringZone); tempString1 = nameArray1.getJSONObject(i).getString("Client") + "\n" + nameArray1.getJSONObject(i).getString("Route") + "\n" + nameArray1.getJSONObject(i).getString("Zone"); vectorOfStrings.add(new String(tempString1)); } int orderCount1 = vectorOfStrings.size(); String[] orderTimeStamps1 = new String[orderCount1]; vectorOfStrings.copyInto(orderTimeStamps1); } catch (Exception a) { a.printStackTrace(); } }
|
00
|
Code Sample 1:
private void getGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
public static Search Search(String searchString) throws Exception { Uri.Builder builder = new Uri.Builder(); builder.scheme("http"); builder.authority("www.goodreads.com"); builder.path("search/search"); builder.appendQueryParameter("format", "xml"); builder.appendQueryParameter("key", _ConsumerKey); builder.appendQueryParameter("q", searchString); HttpClient httpClient = new DefaultHttpClient(); HttpGet getSearchResponse = new HttpGet(builder.build().toString()); HttpResponse searchResponse = httpClient.execute(getSearchResponse); Response searchResponseData = ResponseParser.parse(searchResponse.getEntity().getContent()); return searchResponseData.get_Search(); }
|
11
|
Code Sample 1:
private void save() { int[] selection = list.getSelectionIndices(); String dir = System.getProperty("user.dir"); for (int i = 0; i < selection.length; i++) { File src = files[selection[i]]; FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterPath(dir); dialog.setFileName(src.getName()); String destination = dialog.open(); if (destination != null) { File dest = new File(destination); try { dest.createNewFile(); FileChannel srcC = new FileInputStream(src).getChannel(); FileChannel destC = new FileOutputStream(dest).getChannel(); destC.transferFrom(srcC, 0, srcC.size()); destC.close(); srcC.close(); updateSaved(selection[i], true); files[selection[i]] = dest; } catch (FileNotFoundException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } catch (IOException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } } } }
Code Sample 2:
void copyFile(File src, File dst) throws IOException { FileInputStream fis = new FileInputStream(src); byte[] buf = new byte[10000]; int n; FileOutputStream fos = new FileOutputStream(dst); while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); copied++; }
|
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 static String[] putFECSplitFile(String uri, File file, int htl, boolean mode) { FcpFECUtils fecutils = null; Vector segmentHeaders = null; Vector segmentFileMaps = new Vector(); Vector checkFileMaps = new Vector(); Vector segmentKeyMaps = new Vector(); Vector checkKeyMaps = new Vector(); int fileLength = (int) file.length(); String output = new String(); int maxThreads = frame1.frostSettings.getIntValue("splitfileUploadThreads"); Thread[] chunkThreads = null; String[][] chunkResults = null; Thread[] checkThreads = null; String[][] checkResults = null; int threadCount = 0; String board = getBoard(file); { fecutils = new FcpFECUtils(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getIntValue("nodePort")); synchronized (fecutils.getClass()) { try { segmentHeaders = fecutils.FECSegmentFile("OnionFEC_a_1_2", fileLength); } catch (Exception e) { } } int chunkCnt = 0; int checkCnt = 0; synchronized (fecutils.getClass()) { try { Socket fcpSock; BufferedInputStream fcpIn; PrintStream fcpOut; for (int i = 0; i < segmentHeaders.size(); i++) { int blockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount; int blockNo = 0; fcpSock = new Socket(InetAddress.getByName(frame1.frostSettings.getValue("nodeAddress")), frame1.frostSettings.getIntValue("nodePort")); fcpSock.setSoTimeout(1800000); fcpOut = new PrintStream(fcpSock.getOutputStream()); fcpIn = new BufferedInputStream(fcpSock.getInputStream()); FileInputStream fileIn = new FileInputStream(file); File[] chunkFiles = new File[blockCount]; { System.out.println("Processing segment " + i); fileIn.skip(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset); long segLength = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount * ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize; System.out.println("segLength = " + Long.toHexString(segLength)); String headerString = "SegmentHeader\n" + ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).reconstruct() + "EndMessage\n"; String dataHeaderString = "\0\0\0\2FECEncodeSegment\nMetadataLength=" + Long.toHexString(headerString.length()) + "\nDataLength=" + Long.toHexString(headerString.length() + segLength) + "\nData\n" + headerString; System.out.print(dataHeaderString); fcpOut.print(dataHeaderString); long count = 0; while (count < segLength) { byte[] buffer = new byte[(int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize]; System.out.println(Long.toHexString(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset + count)); int inbytes = fileIn.read(buffer); if (inbytes < 0) { System.out.println("End of input file - no data"); for (int j = 0; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes < buffer.length) { System.out.println("End of input file - not enough data"); for (int j = inbytes; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes > segLength - count) inbytes = (int) (segLength - count); fcpOut.write(buffer); File uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-" + chunkCnt + ".tmp"); chunkFiles[blockNo] = uploadMe; uploadMe.deleteOnExit(); FileOutputStream fileOut = new FileOutputStream(uploadMe); fileOut.write(buffer, 0, (int) inbytes); fileOut.close(); count += inbytes; chunkCnt++; ; blockNo++; if (blockNo >= blockCount) break; } segmentFileMaps.add(chunkFiles); fcpOut.flush(); fileIn.close(); } int checkNo = 0; int checkBlockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockCount; File[] checkFiles = new File[checkBlockCount]; File uploadMe = null; FileOutputStream outFile = null; { String currentLine; long checkBlockSize = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockSize; int checkPtr = 0; int length = 0; do { boolean started = false; currentLine = fecutils.getLine(fcpIn).trim(); if (currentLine.equals("DataChunk")) { started = true; } if (currentLine.startsWith("Length=")) { length = Integer.parseInt((currentLine.split("="))[1], 16); } if (currentLine.equals("Data")) { int currentRead; byte[] buffer = new byte[(int) length]; if (uploadMe == null) { uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-chk-" + checkCnt + ".tmp"); uploadMe.deleteOnExit(); outFile = new FileOutputStream(uploadMe); } currentRead = fcpIn.read(buffer); while (currentRead < length) { currentRead += fcpIn.read(buffer, currentRead, length - currentRead); } outFile.write(buffer); checkPtr += currentRead; if (checkPtr == checkBlockSize) { outFile.close(); checkFiles[checkNo] = uploadMe; uploadMe = null; checkNo++; checkCnt++; checkPtr = 0; } } } while (currentLine.length() > 0); checkFileMaps.add(checkFiles); } fcpOut.close(); fcpIn.close(); fcpSock.close(); } } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } int chunkNo = 0; int uploadedBytes = 0; for (int i = 0; i < segmentFileMaps.size(); i++) { File[] currentFileMap = (File[]) segmentFileMaps.get(i); chunkThreads = new Thread[currentFileMap.length]; chunkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Chunk: " + chunkNo); while (getActiveThreads(chunkThreads) >= maxThreads) mixed.wait(5000); chunkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, chunkResults, threadCount, mode); chunkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); chunkNo++; } while (getActiveThreads(chunkThreads) > 0) { if (DEBUG) System.out.println("Active Splitfile inserts remaining: " + getActiveThreads(chunkThreads)); mixed.wait(3000); } segmentKeyMaps.add(chunkResults); } int checkNo = 0; for (int i = 0; i < checkFileMaps.size(); i++) { File[] currentFileMap = (File[]) checkFileMaps.get(i); checkThreads = new Thread[currentFileMap.length]; checkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Check: " + checkNo); while (getActiveThreads(checkThreads) >= maxThreads) mixed.wait(5000); checkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, checkResults, threadCount, mode); checkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); checkNo++; } while (getActiveThreads(checkThreads) > 0) { if (DEBUG) System.out.println("Active Checkblock inserts remaining: " + getActiveThreads(checkThreads)); mixed.wait(3000); } checkKeyMaps.add(checkResults); } checkThreads = null; } String redirect = null; { synchronized (fecutils.getClass()) { try { redirect = fecutils.FECMakeMetadata(segmentHeaders, segmentKeyMaps, checkKeyMaps, "Frost"); } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } String[] sortedRedirect = redirect.split("\n"); for (int z = 0; z < sortedRedirect.length; z++) System.out.println(sortedRedirect[z]); int sortStart = -1; int sortEnd = -1; for (int line = 0; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("Document")) { sortStart = line + 1; break; } } for (int line = sortStart; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("End")) { sortEnd = line; break; } } System.out.println("sortStart " + sortStart + " sortEnd " + sortEnd); if (sortStart < sortEnd) Arrays.sort(sortedRedirect, sortStart, sortEnd); redirect = new String(); for (int line = 0; line < sortedRedirect.length; line++) redirect += sortedRedirect[line] + "\n"; System.out.println(redirect); } int tries = 0; String[] result = { "Error", "Error" }; while (!result[0].equals("Success") && !result[0].equals("KeyCollision") && tries < 8) { tries++; try { FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); output = connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, mode); } catch (FcpToolsException e) { if (DEBUG) System.out.println("FcpToolsException " + e); frame1.displayWarning(e.toString()); } catch (UnknownHostException e) { if (DEBUG) System.out.println("UnknownHostException"); frame1.displayWarning(e.toString()); } catch (IOException e) { if (DEBUG) System.out.println("IOException"); frame1.displayWarning(e.toString()); } result = result(output); mixed.wait(3000); if (DEBUG) System.out.println("*****" + result[0] + " " + result[1] + " "); } if ((result[0].equals("Success") || result[0].equals("KeyCollision")) && mode) { try { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); String dirdate = cal.get(Calendar.YEAR) + "."; dirdate += cal.get(Calendar.MONTH) + 1 + "."; dirdate += cal.get(Calendar.DATE); String fileSeparator = System.getProperty("file.separator"); String destination = frame1.keypool + board + fileSeparator + dirdate + fileSeparator; FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); String contentKey = result(connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, false))[1]; String prefix = new String("freenet:"); if (contentKey.startsWith(prefix)) contentKey = contentKey.substring(prefix.length()); FileAccess.writeFile("Already uploaded today", destination + contentKey + ".lck"); } catch (Exception e) { } } return result; }
|
00
|
Code Sample 1:
private String doRawGet(URI uri) throws XdsInternalException { HttpURLConnection conn = null; String response = null; try { URL url; try { url = uri.toURL(); } catch (Exception e) { throw HttpClient.getException(e, uri.toString()); } HttpsURLConnection.setDefaultHostnameVerifier(this); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/html, text/xml, text/plain, */*"); conn.connect(); response = this.getResponse(conn); } catch (IOException e) { throw HttpClient.getException(e, uri.toString()); } finally { if (conn != null) { conn.disconnect(); } } return response; }
Code Sample 2:
public alto.io.Output openOutput() throws java.io.IOException { URL url = this.url; if (null != url) { URLConnection connection = url.openConnection(); connection.setDoOutput(true); if (connection instanceof alto.net.Connection) { ((alto.net.Connection) connection).setReference(this); } return new ReferenceOutputStream(this, connection); } HttpMessage container = this.write(); return new ReferenceOutputStream(this, container); }
|
00
|
Code Sample 1:
public static String getRolesString(HttpServletRequest hrequest, HttpServletResponse hresponse, String username, String servicekey) { String registerapp = SSOFilter.getRegisterapp(); String u = SSOUtil.addParameter(registerapp + "/api/getroles", "username", username); u = SSOUtil.addParameter(u, "servicekey", servicekey); String roles = ""; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { roles = line.trim(); } reader.close(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } if ("error".equals(roles)) { return ""; } return roles.trim(); }
Code Sample 2:
public SessionManager(String username) { try { url = new URL("http://" + username + ".bebo.com"); conn = url.openConnection(); } catch (MalformedURLException ex) { Logger.getLogger(SessionManager.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(SessionManager.class.getName()).log(Level.SEVERE, null, ex); } }
|
00
|
Code Sample 1:
public void add(Site site) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sqlStr = "insert into t_ip_site (id,name,description,ascii_name,site_path,remark_number,increment_index,use_status,appserver_id) VALUES(?,?,?,?,?,?,?,?,?)"; dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setInt(1, site.getSiteID()); preparedStatement.setString(2, site.getName()); preparedStatement.setString(3, site.getDescription()); preparedStatement.setString(4, site.getAsciiName()); preparedStatement.setString(5, site.getPath()); preparedStatement.setInt(6, site.getRemarkNumber()); preparedStatement.setString(7, site.getIncrementIndex().trim()); preparedStatement.setString(8, String.valueOf(site.getUseStatus())); preparedStatement.setString(9, String.valueOf(site.getAppserverID())); preparedStatement.executeUpdate(); String[] path = new String[1]; path[0] = site.getPath(); selfDefineAdd(path, site, connection, preparedStatement); connection.commit(); int resID = site.getSiteID() + Const.SITE_TYPE_RES; String resName = site.getName(); int resTypeID = Const.RES_TYPE_ID; int operateTypeID = Const.OPERATE_TYPE_ID; String remark = ""; AuthorityManager am = new AuthorityManager(); am.createExtResource(Integer.toString(resID), resName, resTypeID, operateTypeID, remark); site.wirteFile(); } catch (SQLException ex) { connection.rollback(); log.error("����վ��ʧ��!", ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } }
Code Sample 2:
public byte[] getEncoded(X509Certificate checkCert, X509Certificate rootCert, String url) { try { if (checkCert == null || rootCert == null) return null; if (url == null) { url = PdfPKCS7.getOCSPURL(checkCert); } if (url == null) return null; OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber()); byte[] array = request.getEncoded(); URL urlt = new URL(url); HttpURLConnection con = (HttpURLConnection) urlt.openConnection(); con.setRequestProperty("Content-Type", "application/ocsp-request"); con.setRequestProperty("Accept", "application/ocsp-response"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out)); dataOut.write(array); dataOut.flush(); dataOut.close(); if (con.getResponseCode() / 100 != 2) { throw new IOException(MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode())); } InputStream in = (InputStream) con.getContent(); OCSPResp ocspResponse = new OCSPResp(RandomAccessFileOrArray.InputStreamToArray(in)); if (ocspResponse.getStatus() != 0) throw new IOException(MessageLocalization.getComposedMessage("invalid.status.1", ocspResponse.getStatus())); BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); if (basicResponse != null) { SingleResp[] responses = basicResponse.getResponses(); if (responses.length == 1) { SingleResp resp = responses[0]; Object status = resp.getCertStatus(); if (status == CertificateStatus.GOOD) { return basicResponse.getEncoded(); } else if (status instanceof org.bouncycastle.ocsp.RevokedStatus) { throw new IOException(MessageLocalization.getComposedMessage("ocsp.status.is.revoked")); } else { throw new IOException(MessageLocalization.getComposedMessage("ocsp.status.is.unknown")); } } } } catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error("OcspClientBouncyCastle", ex); } return null; }
|
11
|
Code Sample 1:
@SuppressWarnings("unchecked") @Override public synchronized void drop(DropTargetDropEvent arg0) { Helper.log().debug("Dropped"); Transferable t = arg0.getTransferable(); try { arg0.acceptDrop(arg0.getDropAction()); List<File> filelist = (List<File>) t.getTransferData(t.getTransferDataFlavors()[0]); for (File file : filelist) { Helper.log().debug(file.getAbsolutePath()); if (file.getName().toLowerCase().contains(".lnk")) { Helper.log().debug(file.getName() + " is a link"); File target = new File(rp.getRoot().getFullPath() + "/" + file.getName()); Helper.log().debug("I have opened the mayor at " + target.getAbsolutePath()); FileOutputStream fo = new FileOutputStream(target); FileInputStream fi = new FileInputStream(file); int i = 0; while (fi.available() > 0) { fo.write(fi.read()); System.out.print("."); i++; } Helper.log().debug(i + " bytes have been written to " + target.getAbsolutePath()); fo.close(); fi.close(); } } rp.redraw(); } catch (Throwable tr) { tr.printStackTrace(); } Helper.log().debug(arg0.getSource().toString()); }
Code Sample 2:
public void deploy(final File extension) { log.info("Deploying new extension from {}", extension.getPath()); RequestContextHolder.setRequestContext(new RequestContext(SZoneConfig.getDefaultZoneName(), SZoneConfig.getAdminUserName(SZoneConfig.getDefaultZoneName()), new BaseSessionContext())); RequestContextHolder.getRequestContext().resolve(); JarInputStream warIn; try { warIn = new JarInputStream(new FileInputStream(extension), true); } catch (IOException e) { log.warn("Unable to open extension WAR at " + extension.getPath(), e); return; } SAXReader reader = new SAXReader(false); reader.setIncludeExternalDTDDeclarations(false); String extensionPrefix = extension.getName().substring(0, extension.getName().lastIndexOf(".")); File extensionDir = new File(extensionBaseDir, extensionPrefix); extensionDir.mkdirs(); File extensionWebDir = new File(this.extensionWebDir, extensionPrefix); extensionWebDir.mkdirs(); try { for (JarEntry entry = warIn.getNextJarEntry(); entry != null; entry = warIn.getNextJarEntry()) { File inflated = new File(entry.getName().startsWith(infPrefix) ? extensionDir : extensionWebDir, entry.getName()); if (entry.isDirectory()) { log.debug("Creating directory at {}", inflated.getPath()); inflated.mkdirs(); continue; } inflated.getParentFile().mkdirs(); FileOutputStream entryOut = new FileOutputStream(inflated); if (!entry.getName().endsWith(configurationFileExtension)) { log.debug("Inflating file resource to {}", inflated.getPath()); IOUtils.copy(warIn, entryOut); entryOut.close(); continue; } try { final Document document = reader.read(new TeeInputStream(new CloseShieldInputStream(warIn), entryOut, true)); Attribute schema = document.getRootElement().attribute(schemaAttribute); if (schema == null || StringUtils.isBlank(schema.getText())) { log.debug("Inflating XML with unrecognized schema to {}", inflated.getPath()); continue; } if (schema.getText().contains(definitionsSchemaNamespace)) { log.debug("Inflating and registering definition from {}", inflated.getPath()); document.getRootElement().add(new AbstractAttribute() { private static final long serialVersionUID = -7880537136055718310L; public QName getQName() { return new QName(extensionAttr, document.getRootElement().getNamespace()); } public String getValue() { return extension.getName().substring(0, extension.getName().lastIndexOf(".")); } }); definitionModule.addDefinition(document, true); continue; } if (schema.getText().contains(templateSchemaNamespace)) { log.debug("Inflating and registering template from {}", inflated.getPath()); templateService.addTemplate(document, true, zoneModule.getDefaultZone()); continue; } } catch (DocumentException e) { log.warn("Malformed XML file in extension war at " + extension.getPath(), e); return; } } } catch (IOException e) { log.warn("Malformed extension war at " + extension.getPath(), e); return; } finally { try { warIn.close(); } catch (IOException e) { log.warn("Unable to close extension war at " + extension.getPath(), e); return; } RequestContextHolder.clear(); } log.info("Extension deployed successfully from {}", extension.getPath()); }
|
11
|
Code Sample 1:
public boolean copyFile(File destinationFolder, File fromFile) { boolean result = false; String toFileName = destinationFolder.getAbsolutePath() + "/" + fromFile.getName(); File toFile = new File(toFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (from != null) { try { from.close(); } catch (IOException e2) { e2.printStackTrace(); } if (to != null) { try { to.close(); result = true; } catch (IOException e3) { e3.printStackTrace(); } } } } return result; }
Code Sample 2:
public void testRevcounter() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Created at: " + secondSource.getSourceRevision()); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } System.out.println("Read again at:" + secondSource.getSourceRevision()); assertNotNull(emptySource.getSourceRevision()); }
|
11
|
Code Sample 1:
public void sendContent(OutputStream out, Range range, Map map, String string) throws IOException, NotAuthorizedException, BadRequestException { System.out.println("sendContent " + file); RFileInputStream in = new RFileInputStream(file); try { IOUtils.copyLarge(in, out); } finally { in.close(); } }
Code Sample 2:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); int i; for (i = 0; ((i < list.length) && !stop); i++) { current = i; if ((list[i].compareTo("Images") != 0) && ((list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".jpg") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".bmp") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".png") == 0))) { String name = list[i]; String pathSrc = directoryPath.concat(list[i]); name = name.replace(' ', '_').replace(',', '-').replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('Á', 'A').replace('É', 'E').replace('Í', 'I').replace('Ó', 'O').replace('Ú', 'U'); String pathDst = directoryPath.concat(name); Vector aux = new Vector(); aux = dataBase.imageSearch(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) pathDst = pathDst.substring(0, pathDst.lastIndexOf('.')) + '_' + aux.size() + ".png"; File src = new File(pathSrc); File absPath = new File(""); String nameSrc = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase() + src.separator + pathDst.substring(pathDst.lastIndexOf(src.separator) + 1, pathDst.length()); String newDirectory = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase(); String imagePathThumb = (nameSrc.substring(0, nameSrc.lastIndexOf("."))).concat("_th.jpg"); ImageIcon image = null; if (src != null) { if (TFileUtils.isJAIRequired(src)) { RenderedOp src_aux = JAI.create("fileload", src.getAbsolutePath()); BufferedImage bufferedImage = src_aux.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(src.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { System.out.print("Error al insertar imagen: "); System.out.println(pathDst); } else { int option = 0; imageFile = new File(directoryPath + "Images"); if (!imageFile.exists()) { TIGNewImageDataDialog dialog = new TIGNewImageDataDialog(editor, dataBase, image, nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length()), list[i].substring(0, list[i].lastIndexOf('.')), myTask); option = dialog.getOption(); if (option != 0) { File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } } if (imageFile.exists()) { dataBase.insertImageDB(list[i].substring(0, list[i].lastIndexOf('.')), nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length())); File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } } if (imageFile.exists() && !stop) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(imageFile); Element dataBaseElement = doc.getDocumentElement(); if (dataBaseElement.getTagName().equals("dataBase")) { NodeList imageNodeList = dataBaseElement.getElementsByTagName("image"); for (int j = 0; j < imageNodeList.getLength(); j++) { current++; Node imageNode = imageNodeList.item(j); NodeList lista = imageNode.getChildNodes(); Node nameNode = imageNode.getChildNodes().item(0); String imageName = nameNode.getChildNodes().item(0).getNodeValue(); int imageKey = dataBase.imageKeySearchName(imageName.substring(0, imageName.lastIndexOf('.'))); if (imageKey != -1) { for (int k = 1; k < imageNode.getChildNodes().getLength(); k++) { Node keyWordNode = imageNode.getChildNodes().item(k); String keyWord = keyWordNode.getChildNodes().item(0).getNodeValue(); int conceptKey = dataBase.conceptKeySearch(keyWord); if (conceptKey == -1) { dataBase.insertConceptDB(keyWord); conceptKey = dataBase.conceptKeySearch(keyWord); } dataBase.insertAsociatedDB(conceptKey, imageKey); } } } } } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } current = lengthOfTask; }
|
11
|
Code Sample 1:
public List<SatelliteElementSet> parseTLE(String urlString) throws IOException { List<SatelliteElementSet> elementSets = new ArrayList<SatelliteElementSet>(); BufferedReader reader = null; try { String line = null; int i = 0; URL url = new URL(urlString); String[] lines = new String[3]; reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { i++; switch(i) { case 1: { lines[0] = line; break; } case 2: { lines[1] = line; break; } case 3: { lines[2] = line; Long catnum = Long.parseLong(StringUtils.strip(lines[1].substring(2, 7))); long setnum = Long.parseLong(StringUtils.strip(lines[1].substring(64, 68))); elementSets.add(new SatelliteElementSet(catnum, lines, setnum, Calendar.getInstance(TZ).getTime())); i = 0; break; } default: { throw new IOException("TLE string did not contain three elements"); } } } } finally { if (null != reader) { reader.close(); } } return elementSets; }
Code Sample 2:
private void getServiceReponse(String service, NameSpaceDefinition nsDefinition) throws Exception { Pattern pattern = Pattern.compile("(?i)(?:.*(xmlns(?:\\:\\w+)?=\\\"http\\:\\/\\/www\\.ivoa\\.net\\/.*" + service + "[^\\\"]*\\\").*)"); pattern = Pattern.compile(".*xmlns(?::\\w+)?=(\"[^\"]*(?i)(?:" + service + ")[^\"]*\").*"); logger.debug("read " + this.url + service); BufferedReader in = new BufferedReader(new InputStreamReader((new URL(this.url + service)).openStream())); String inputLine; BufferedWriter bfw = new BufferedWriter(new FileWriter(this.baseDirectory + service + ".xml")); boolean found = false; while ((inputLine = in.readLine()) != null) { if (!found) { Matcher m = pattern.matcher(inputLine); if (m.matches()) { nsDefinition.init("xmlns:vosi=" + m.group(1)); found = true; } } bfw.write(inputLine + "\n"); } in.close(); bfw.close(); }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void main(String[] args) { String command = "java -jar "; String linkerJarPath = ""; String path = ""; String osName = System.getProperty("os.name"); String temp = Launcher.class.getResource("").toString(); int index = temp.indexOf(".jar"); int start = index - 1; while (Character.isLetter(temp.charAt(start))) { start--; } String jarName = temp.substring(start + 1, index + 4); System.out.println(jarName); if (osName.startsWith("Linux")) { temp = temp.substring(temp.indexOf("/"), temp.indexOf(jarName)); } else if (osName.startsWith("Windows")) { temp = temp.substring(temp.indexOf("file:") + 5, temp.indexOf(jarName)); } else { System.exit(0); } path = path + temp; try { path = java.net.URLDecoder.decode(path, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File dir = new File(path); File[] files = dir.listFiles(); String exeJarName = null; for (File f : files) { if (f.getName().endsWith(".jar") && !f.getName().startsWith(jarName)) { exeJarName = f.getName(); break; } } if (exeJarName == null) { System.out.println("no exefile"); System.exit(0); } linkerJarPath = path + exeJarName; String pluginDirPath = path + "plugin" + File.separator; File[] plugins = new File(pluginDirPath).listFiles(); StringBuffer pluginNames = new StringBuffer(""); for (File plugin : plugins) { if (plugin.getAbsolutePath().endsWith(".jar")) { pluginNames.append("plugin/" + plugin.getName() + " "); } } String libDirPath = path + "lib" + File.separator; File[] libs = new File(libDirPath).listFiles(); StringBuffer libNames = new StringBuffer(""); for (File lib : libs) { if (lib.getAbsolutePath().endsWith(".jar")) { libNames.append("lib/" + lib.getName() + " "); } } try { JarFile jarFile = new JarFile(linkerJarPath); Manifest manifest = jarFile.getManifest(); if (manifest == null) { manifest = new Manifest(); } Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Class-Path", pluginNames.toString() + libNames.toString()); String backupFile = linkerJarPath + "back"; FileInputStream copyInput = new FileInputStream(linkerJarPath); FileOutputStream copyOutput = new FileOutputStream(backupFile); byte[] buffer = new byte[4096]; int s; while ((s = copyInput.read(buffer)) > -1) { copyOutput.write(buffer, 0, s); } copyOutput.flush(); copyOutput.close(); copyInput.close(); JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(linkerJarPath), manifest); JarInputStream jarIn = new JarInputStream(new FileInputStream(backupFile)); byte[] buf = new byte[4096]; JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if ("META-INF/MANIFEST.MF".equals(entry.getName())) continue; jarOut.putNextEntry(entry); int read; while ((read = jarIn.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); } jarOut.flush(); jarOut.close(); jarIn.close(); File file = new File(backupFile); if (file.exists()) { file.delete(); } } catch (IOException e1) { e1.printStackTrace(); } try { if (System.getProperty("os.name").startsWith("Linux")) { Runtime runtime = Runtime.getRuntime(); String[] commands = new String[] { "java", "-jar", path + exeJarName }; runtime.exec(commands); } else { path = path.substring(1); command = command + "\"" + path + exeJarName + "\""; System.out.println(command); Runtime.getRuntime().exec(command); } } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
@Override public void actionPerformed(ActionEvent event) { if (event.getSource() == btnChange) { Error.log(7002, "Bot�o alterar pressionado por " + login + "."); if (new String(passwordUser1.getPassword()).compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo senha requerido"); passwordUser1.setFocusable(true); return; } String password1 = new String(passwordUser1.getPassword()); String password2 = new String(passwordUser2.getPassword()); if (password1.compareTo(password2) != 0) { JOptionPane.showMessageDialog(null, "Senhas n�o casam"); passwordUser1.setText(""); passwordUser2.setText(""); passwordUser1.setFocusable(true); return; } char c = passwordUser1.getPassword()[0]; int j = 1; for (j = 1; j < password1.length(); j++) { if (passwordUser1.getPassword()[j] != c) { break; } c = passwordUser1.getPassword()[j]; } if (j == password1.length()) { JOptionPane.showMessageDialog(null, "Senha fraca"); return; } if (password1.length() < 6) { JOptionPane.showMessageDialog(null, "Senha deve ter mais que 6 digitos"); return; } if (numPasswordOneUseUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo n�mero de senhas de uso �nico requerido"); return; } if (!(Integer.parseInt(numPasswordOneUseUser.getText()) > 0 && Integer.parseInt(numPasswordOneUseUser.getText()) < 41)) { JOptionPane.showMessageDialog(null, "N�mero de senhas de uso �nico entre 1 e 40"); return; } String outputDigest = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password1.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); outputDigest = bigInt.toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } Statement stmt; String sql; sql = "update Usuarios set password = '" + outputDigest + "' where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r; Vector<Integer> passwordVector = new Vector<Integer>(); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } JOptionPane.showMessageDialog(null, "Usu�rio " + login + " foi alterado com sucesso."); dispose(); } if (event.getSource() == btnCancel) { Error.log(7003, "Bot�o voltar de alterar para o menu principal pressionado por " + login + "."); dispose(); } }
Code Sample 2:
@Override protected void copy(InputStream inputs, OutputStream outputs) throws IOException { if (outputs == null) { throw new NullPointerException(); } if (inputs == null) { throw new NullPointerException(); } ZipOutputStream zipoutputs = null; try { zipoutputs = new ZipOutputStream(outputs); zipoutputs.putNextEntry(new ZipEntry("default")); IOUtils.copy(inputs, zipoutputs); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (zipoutputs != null) { zipoutputs.close(); } if (inputs != null) { inputs.close(); } } }
|
11
|
Code Sample 1:
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; }
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())); }
|
11
|
Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
Code Sample 2:
public static String CreateZip(String[] filesToZip, String zipFileName) { byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.setLevel(Deflater.BEST_COMPRESSION); for (int i = 0; i < filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); String fileName = null; for (int X = filesToZip[i].length() - 1; X >= 0; X--) { if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') { fileName = filesToZip[i].substring(X + 1); break; } else if (X == 0) fileName = filesToZip[i]; } out.putNextEntry(new ZipEntry(fileName)); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); } out.close(); } catch (IllegalArgumentException e) { return "Failed to create zip: " + e.toString(); } catch (FileNotFoundException e) { return "Failed to create zip: " + e.toString(); } catch (IOException e) { return "Failed to create zip: " + e.toString(); } return "Success"; }
|
11
|
Code Sample 1:
@Override public void run() { File dir = new File(loggingDir); if (!dir.isDirectory()) { logger.error("Logging directory \"" + dir.getAbsolutePath() + "\" does not exist."); return; } File file = new File(dir, new Date().toString().replaceAll("[ ,:]", "") + "LoadBalancerLog.txt"); FileWriter writer; try { writer = new FileWriter(file); } catch (IOException e) { e.printStackTrace(); return; } int counter = 0; while (!isInterrupted() && counter < numProbes) { try { writer.write(System.currentTimeMillis() + "," + currentPending + "," + currentThreads + "," + droppedTasks + "," + executionExceptions + "," + currentWeight + "," + averageWaitTime + "," + averageExecutionTime + "#"); writer.flush(); } catch (IOException e) { e.printStackTrace(); break; } counter++; try { sleep(probeTime); } catch (InterruptedException e) { e.printStackTrace(); break; } } try { writer.close(); } catch (IOException e) { e.printStackTrace(); return; } FileReader reader; try { reader = new FileReader(file); } catch (FileNotFoundException e2) { e2.printStackTrace(); return; } Vector<StatStorage> dataV = new Vector<StatStorage>(); int c; try { c = reader.read(); } catch (IOException e1) { e1.printStackTrace(); c = -1; } String entry = ""; Date startTime = null; Date stopTime = null; while (c != -1) { if (c == 35) { String parts[] = entry.split(","); if (startTime == null) startTime = new Date(Long.parseLong(parts[0])); if (parts.length > 0) dataV.add(parse(parts)); stopTime = new Date(Long.parseLong(parts[0])); entry = ""; } else { entry += (char) c; } try { c = reader.read(); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); } catch (IOException e) { e.printStackTrace(); } if (dataV.size() > 0) { int[] dataPending = new int[dataV.size()]; int[] dataOccupied = new int[dataV.size()]; long[] dataDropped = new long[dataV.size()]; long[] dataException = new long[dataV.size()]; int[] dataWeight = new int[dataV.size()]; long[] dataExecution = new long[dataV.size()]; long[] dataWait = new long[dataV.size()]; for (int i = 0; i < dataV.size(); i++) { dataPending[i] = dataV.get(i).pending; dataOccupied[i] = dataV.get(i).occupied; dataDropped[i] = dataV.get(i).dropped; dataException[i] = dataV.get(i).exceptions; dataWeight[i] = dataV.get(i).currentWeight; dataExecution[i] = (long) dataV.get(i).executionTime; dataWait[i] = (long) dataV.get(i).waitTime; } String startName = startTime.toString(); startName = startName.replaceAll("[ ,:]", ""); file = new File(dir, startName + "pending.gif"); SimpleChart.drawChart(file, 640, 480, dataPending, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "occupied.gif"); SimpleChart.drawChart(file, 640, 480, dataOccupied, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "dropped.gif"); SimpleChart.drawChart(file, 640, 480, dataDropped, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "exceptions.gif"); SimpleChart.drawChart(file, 640, 480, dataException, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "weight.gif"); SimpleChart.drawChart(file, 640, 480, dataWeight, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "execution.gif"); SimpleChart.drawChart(file, 640, 480, dataExecution, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "wait.gif"); SimpleChart.drawChart(file, 640, 480, dataWait, startTime, stopTime, new Color(0, 0, 0)); } recordedExecutionThreads = 0; recordedWaitingThreads = 0; averageExecutionTime = 0; averageWaitTime = 0; if (!isLocked) { debugThread = new DebugThread(); debugThread.start(); } }
Code Sample 2:
private void compress(File target, Set<File> files) throws CacheOperationException, ConfigurationException { ZipOutputStream zipOutput = null; try { zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target))); for (File file : files) { BufferedInputStream fileInput = null; File cachePathName = new File(cacheFolder, file.getPath()); try { if (!cachePathName.exists()) { throw new CacheOperationException("Expected to add file ''{0}'' to export archive ''{1}'' (Account : {2}) but it " + "has gone missing (cause unknown). This can indicate implementation or deployment " + "error. Aborting export operation as a safety precaution.", cachePathName.getPath(), target.getAbsolutePath(), account.getOid()); } fileInput = new BufferedInputStream(new FileInputStream(cachePathName)); ZipEntry entry = new ZipEntry(file.getPath()); entry.setSize(cachePathName.length()); entry.setTime(cachePathName.lastModified()); zipOutput.putNextEntry(entry); cacheLog.debug("Added new export zip entry ''{0}''.", file.getPath()); int count, total = 0; int buffer = 2048; byte[] data = new byte[buffer]; while ((count = fileInput.read(data, 0, buffer)) != -1) { zipOutput.write(data, 0, count); total += count; } zipOutput.flush(); if (total != cachePathName.length()) { throw new CacheOperationException("Only wrote {0} out of {1} bytes when archiving file ''{2}'' (Account : {3}). " + "This could have occured either due implementation error or file I/O error. " + "Aborting archive operation to prevent a potentially corrupt export archive to " + "be created.", total, cachePathName.length(), cachePathName.getPath(), account.getOid()); } else { cacheLog.debug("Wrote {0} out of {1} bytes to zip entry ''{2}''", total, cachePathName.length(), file.getPath()); } } catch (SecurityException e) { throw new ConfigurationException("Security manager has denied r/w access when attempting to read file ''{0}'' and " + "write it to archive ''{1}'' (Account : {2}) : {3}", e, cachePathName.getPath(), target, account.getOid(), e.getMessage()); } catch (IllegalArgumentException e) { throw new CacheOperationException("Error creating ZIP archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (FileNotFoundException e) { throw new CacheOperationException("Attempted to include file ''{0}'' in export archive but it has gone missing " + "(Account : {1}). Possible implementation error in local file cache. Aborting " + "export operation as a precaution ({2})", e, cachePathName.getPath(), account.getOid(), e.getMessage()); } catch (ZipException e) { throw new CacheOperationException("Error writing export archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (IOException e) { throw new CacheOperationException("I/O error while creating export archive for account ID = {0}. " + "Operation aborted ({1})", e, account.getOid(), e.getMessage()); } finally { if (zipOutput != null) { try { zipOutput.closeEntry(); } catch (Throwable t) { cacheLog.warn("Unable to close zip entry for file ''{0}'' in export archive ''{1}'' " + "(Account : {2}) : {3}.", t, file.getPath(), target.getAbsolutePath(), account.getOid(), t.getMessage()); } } if (fileInput != null) { try { fileInput.close(); } catch (Throwable t) { cacheLog.warn("Failed to close input stream from file ''{0}'' being added " + "to export archive (Account : {1}) : {2}", t, cachePathName.getPath(), account.getOid(), t.getMessage()); } } } } } catch (FileNotFoundException e) { throw new CacheOperationException("Unable to create target export archive ''{0}'' for account {1) : {2}", e, target, account.getOid(), e.getMessage()); } finally { try { if (zipOutput != null) { zipOutput.close(); } } catch (Throwable t) { cacheLog.warn("Failed to close the stream to export archive ''{0}'' : {1}.", t, target, t.getMessage()); } } }
|
11
|
Code Sample 1:
private void initLogging() { File logging = new File(App.getHome(), "logging.properties"); if (!logging.exists()) { InputStream input = getClass().getResourceAsStream("logging.properties-setup"); OutputStream output = null; try { output = new FileOutputStream(logging); IOUtils.copy(input, output); } catch (Exception ex) { } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } FileInputStream input = null; try { input = new FileInputStream(logging); LogManager.getLogManager().readConfiguration(input); } catch (Exception ex) { } finally { IOUtils.closeQuietly(input); } }
Code Sample 2:
public static 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 execute() throws BuildException { Project proj = getProject(); if (templateFile == null) throw new BuildException("Template file not set"); if (targetFile == null) throw new BuildException("Target file not set"); try { File template = new File(templateFile); File target = new File(targetFile); if (!template.exists()) throw new BuildException("Template file does not exist " + template.toString()); if (!template.canRead()) throw new BuildException("Cannot read template file: " + template.toString()); if (((!append) && (!overwrite)) && (!target.exists())) throw new BuildException("Target file already exists and append and overwrite are false " + target.toString()); if (VERBOSE) { System.out.println("ProcessTemplate: tmpl in " + template.toString()); System.out.println("ProcessTemplate: file out " + target.toString()); } BufferedReader reader = new BufferedReader(new FileReader(template)); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, append)); parse(reader, writer); writer.flush(); writer.close(); } catch (Exception e) { if (VERBOSE) e.printStackTrace(); throw new BuildException(e); } }
Code Sample 2:
private void tar(FileHolder fileHolder, boolean gzipIt) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File tarDestFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(tarDestFile); if (gzipIt) { outStream = new GZIPOutputStream(outStream); } TarOutputStream tarOutStream = new TarOutputStream(outStream); for (int i = 0; i < fileHolder.selectedFileList.size(); i++) { File selectedFile = fileHolder.selectedFileList.get(i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); TarEntry tarEntry = null; try { tarEntry = new TarEntry(selectedFile, selectedFile.getName()); } catch (InvalidHeaderException e) { errEntry.setThrowable(e); errEntry.setAppContext("tar()"); errEntry.setAppMessage("Error tar'ing: " + selectedFile); logger.logError(errEntry); } tarOutStream.putNextEntry(tarEntry); while ((bytes_read = inStream.read(buffer)) != -1) { tarOutStream.write(buffer, 0, bytes_read); } tarOutStream.closeEntry(); inStream.close(); super.processorSyncFlag.restartWaitUntilFalse(); } tarOutStream.close(); } catch (Exception e) { errEntry.setThrowable(e); errEntry.setAppContext("tar()"); errEntry.setAppMessage("Error tar'ing: " + tarDestFile); logger.logError(errEntry); } }
|
11
|
Code Sample 1:
public void testQueryForBinary() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource source = (JCRNodeSource) resolveSource(BASE_URL + "images/photo.png"); assertNotNull(source); assertEquals(false, source.exists()); OutputStream os = source.getOutputStream(); assertNotNull(os); String content = "foo is a bar"; os.write(content.getBytes()); os.flush(); os.close(); QueryResultSource qResult = (QueryResultSource) resolveSource(BASE_URL + "images?/*[contains(local-name(), 'photo.png')]"); assertNotNull(qResult); Collection results = qResult.getChildren(); assertEquals(1, results.size()); Iterator it = results.iterator(); JCRNodeSource rSrc = (JCRNodeSource) it.next(); InputStream rSrcIn = rSrc.getInputStream(); ByteArrayOutputStream actualOut = new ByteArrayOutputStream(); IOUtils.copy(rSrcIn, actualOut); rSrcIn.close(); assertEquals(content, actualOut.toString()); actualOut.close(); rSrc.delete(); }
Code Sample 2:
@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(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
|
00
|
Code Sample 1:
@Override public void doHandler(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String directURL = request.getRequestURL().toString(); response.setCharacterEncoding("gbk"); PrintWriter out = response.getWriter(); try { directURL = urlTools.urlFilter(directURL, true); URL url = new URL(directURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "gbk")); String line; while ((line = in.readLine()) != null) { out.println(line); } in.close(); } catch (Exception e) { out.println("file not find"); } out.flush(); }
Code Sample 2:
public int delete(BusinessObject o) throws DAOException { int delete = 0; Currency curr = (Currency) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_CURRENCY")); pst.setInt(1, curr.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
private boolean copy(File in, File out) { try { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); FileChannel readableChannel = fis.getChannel(); FileChannel writableChannel = fos.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); fis.close(); fos.close(); return true; } catch (IOException ioe) { guiBuilder.showError("Copy Error", "IOException during copy", ioe.getMessage()); return false; } }
|
11
|
Code Sample 1:
private void copyPhoto(final IPhoto photo, final Map.Entry<String, Integer> size) { final File fileIn = new File(storageService.getPhotoPath(photo, storageService.getOriginalDir())); final File fileOut = new File(storageService.getPhotoPath(photo, size.getKey())); InputStream fileInputStream; OutputStream fileOutputStream; try { fileInputStream = new FileInputStream(fileIn); fileOutputStream = new FileOutputStream(fileOut); IOUtils.copy(fileInputStream, fileOutputStream); fileInputStream.close(); fileOutputStream.close(); } catch (final IOException e) { log.error("file io exception", e); return; } }
Code Sample 2:
private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
|
11
|
Code Sample 1:
protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } }
Code Sample 2:
private File uploadToTmp() { if (fileFileName == null) { return null; } File tmpFile = dataDir.tmpFile(shortname, fileFileName); log.debug("Uploading dwc archive file for new resource " + shortname + " to " + tmpFile.getAbsolutePath()); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(file); output = new FileOutputStream(tmpFile); IOUtils.copy(input, output); output.flush(); log.debug("Uploaded file " + fileFileName + " with content-type " + fileContentType); } catch (IOException e) { log.error(e); return null; } finally { if (output != null) { IOUtils.closeQuietly(output); } if (input != null) { IOUtils.closeQuietly(input); } } return tmpFile; }
|
00
|
Code Sample 1:
public synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
Code Sample 2:
public void testHttpsPersistentConnection() throws Throwable { setUpStoreProperties(); try { SSLContext ctx = getContext(); ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0); TestHostnameVerifier hnv = new TestHostnameVerifier(); HttpsURLConnection.setDefaultHostnameVerifier(hnv); URL url = new URL("https://localhost:" + ss.getLocalPort()); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); SSLSocket peerSocket = (SSLSocket) doPersistentInteraction(connection, ss); checkConnectionStateParameters(connection, peerSocket); connection.connect(); } finally { tearDownStoreProperties(); } }
|
00
|
Code Sample 1:
public void createFeed(Context ctx, URL url) { try { targetFlag = TARGET_FEED; droidDB = NewsDroidDB.getInstance(ctx); currentFeed.Url = url; SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(this); xr.parse(new InputSource(url.openStream())); } catch (IOException e) { Log.e(e.getMessage()); } catch (SAXException e) { Log.e(e.getMessage()); } catch (ParserConfigurationException e) { Log.e(e.getMessage()); } }
Code Sample 2:
public static byte[] SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return sha1hash; }
|
00
|
Code Sample 1:
public Vector getData(DataDescription descr, Station station, DateInterval dateInterval, int sampling) throws ApiException { Connection con = null; Statement stmt = null; String table = (descr != null) ? descr.getTable() : null; Vector dsList = new Vector(); try { String wsflag = Settings.get(table + ".useWebService"); if ("yes".equals(wsflag) || "true".equals(wsflag)) { String serviceUrl = Settings.get(table + ".dataServiceUrl"); String serviceUser = Settings.get(table + ".dataServiceUser"); String servicePassword = Settings.get(table + ".dataServicePassword"); Call call = (Call) (new Service()).createCall(); call.setTargetEndpointAddress(serviceUrl); call.setOperationName("getData"); if (serviceUser != null) { call.setUsername(serviceUser); if (servicePassword != null) { call.setPassword(servicePassword); } } if (log.isDebugEnabled()) { log.debug("Service " + serviceUrl + " authentication user=" + serviceUser + " passwd=" + servicePassword + " call method getData" + " for table " + table + " station " + ((station != null) ? station.getStn() : "") + " element " + ((descr != null && descr.getElement() != null) ? descr.getElement() : "") + " dateFrom " + dateInterval.getDateFrom().getDayId() + " dateTo " + dateInterval.getDateTo().getDayId() + " sampling " + sampling); } String dssUrl = (String) call.invoke(new Object[] { table, ((station != null) ? station.getStn() : ""), ((descr != null && descr.getElement() != null) ? descr.getElement() : ""), "" + dateInterval.getDateFrom().getDayId(), "" + dateInterval.getDateTo().getDayId(), "", "" + sampling }); if (log.isDebugEnabled()) { log.debug("Service return url '" + dssUrl + "'"); } if (dssUrl != null && !"".equals(dssUrl)) { URL dataurl = new URL(dssUrl); DataSequenceSet dsstmp = readDataSet(dataurl.openStream()); if (dsstmp != null && dsstmp.size() > 0) { dsList.addAll(dsstmp); if (log.isDebugEnabled()) { log.debug("Data set list size is " + dsstmp.size()); } } else { if (log.isDebugEnabled()) { log.debug("Data set list is empty"); } } } } else { con = ConnectionPool.getConnection(table); stmt = con.createStatement(); String className = Settings.get(table + ".classGetter"); if (className == null) { throw new ApiException("Undefined classGetter field for table '" + table + "'"); } dsList = ((DBAccess) Class.forName(className).newInstance()).getDataSequence(stmt, descr, station, dateInterval, sampling); } return dsList; } catch (Exception e) { e.printStackTrace(); throw new ApiException("Data are not available: " + e.toString()); } finally { try { if (stmt != null) { stmt.close(); } } catch (Exception e) { } ConnectionPool.releaseConnection(con); } }
Code Sample 2:
@Override public final byte[] getDigest() { try { final MessageDigest hashing = MessageDigest.getInstance("SHA-256"); final Charset utf16 = Charset.forName("UTF-16"); for (final CollationKey wordKey : this.words) { hashing.update(wordKey.toByteArray()); } hashing.update(this.locale.toString().getBytes(utf16)); hashing.update(ByteUtils.toBytesLE(this.collator.getStrength())); hashing.update(ByteUtils.toBytesLE(this.collator.getDecomposition())); return hashing.digest(); } catch (final NoSuchAlgorithmException e) { FileBasedDictionary.LOG.severe(e.toString()); return new byte[0]; } }
|
11
|
Code Sample 1:
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.*;"); importList.add("java.sql.Date;"); importList.add("com.emeraldjb.runtime.patternXmlObj.*;"); importList.add("javax.xml.parsers.*;"); importList.add("java.text.ParseException;"); importList.add("org.xml.sax.*;"); importList.add("org.xml.sax.helpers.*;"); 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"); boolean short_version = entity.getPatternBooleanValue(GeneratorConst.PATTERN_STREAM_XML_SHORT, false); StringBuffer preface = new StringBuffer(); StringBuffer consts = new StringBuffer(); StringBuffer f_writer = new StringBuffer(); StringBuffer f_writer_short = new StringBuffer(); StringBuffer f_reader = new StringBuffer(); StringBuffer end_elems = new StringBuffer(); boolean end_elem_needs_catch = false; consts.append("\n public static final String EL_CLASS_TAG=\"" + values_class_name + "\";"); preface.append("\n xos.print(\"<!-- This format is optimised for space, below are the column mappings\");"); boolean has_times = false; boolean has_strings = false; it = entity.getMembers().iterator(); int col_num = 0; while (it.hasNext()) { col_num++; Member member = (Member) it.next(); String nm = member.getName(); preface.append("\n xos.print(\"c" + col_num + " = " + nm + "\");"); String elem_name = nm; String elem_name_short = "c" + col_num; String el_name = nm.toUpperCase(); if (member.getColLen() > 0 || !member.isNullAllowed()) { end_elem_needs_catch = true; } String element_const = "EL_" + el_name; String element_const_short = "EL_" + el_name + "_SHORT"; consts.append("\n public static final String " + element_const + "=\"" + elem_name + "\";" + "\n public static final String " + element_const_short + "=\"" + elem_name_short + "\";"); String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member); String setter = "values_." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member); String pad = " "; JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType()); f_writer.append(gen_type.getToXmlCode(pad, element_const, getter + "()")); f_writer_short.append(gen_type.getToXmlCode(pad, element_const_short, getter + "()")); end_elems.append(gen_type.getFromXmlCode(pad, element_const, setter)); end_elems.append("\n //and also the short version"); end_elems.append(gen_type.getFromXmlCode(pad, element_const_short, setter)); } preface.append("\n xos.print(\"-->\");"); String body_part = f_writer.toString(); String body_part_short = preface.toString() + f_writer_short.toString(); String reader_vars = ""; String streamer_class_name = getClassName(entity); sb.append("public class " + streamer_class_name + " extends DefaultHandler implements TSParser\n"); sb.append("{" + consts + "\n public static final int PROTO_VERSION=" + proto_version + ";" + "\n private transient StringBuffer cdata_=new StringBuffer();" + "\n private transient String endElement_;" + "\n private transient TSParser parentParser_;" + "\n private transient XMLReader theReader_;\n" + "\n private " + values_class_name + " values_;"); sb.append("\n\n"); sb.append("\n /**" + "\n * This is really only here as an example. It is very rare to write a single" + "\n * object to a file - far more likely to have a collection or object graph. " + "\n * in which case you can write something similar - maybe using the writeXmlShort" + "\n * version instread." + "\n */" + "\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 XmlOutputFilter xos = new XmlOutputFilter(fos);" + "\n xos.openElement(\"FILE_\"+EL_CLASS_TAG);" + "\n writeXml(xos, obj);" + "\n xos.closeElement();" + "\n fos.close();" + "\n } // end of writeToFile" + "\n" + "\n public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException, SAXException" + "\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 marshalFromXml(dis, obj);" + "\n fis.close();" + "\n } // end of readFromFile" + "\n" + "\n public static void writeXml(XmlOutputFilter xos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n xos.openElement(EL_CLASS_TAG);" + body_part + "\n xos.closeElement();" + "\n } // end of writeXml" + "\n" + "\n public static void writeXmlShort(XmlOutputFilter xos, " + values_class_name + " obj) throws IOException" + "\n {" + "\n xos.openElement(EL_CLASS_TAG);" + body_part_short + "\n xos.closeElement();" + "\n } // end of writeXml" + "\n" + "\n public " + streamer_class_name + "(" + values_class_name + " obj) {" + "\n values_ = obj;" + "\n } // end of ctor" + "\n"); String xml_bit = addXmlFunctions(streamer_class_name, values_class_name, end_elem_needs_catch, end_elems, f_reader); String close = "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************"; return sb.toString() + xml_bit + close; }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.