label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: static Object executeMethod(HttpMethod method, int timeout, boolean array) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException { try { method.getParams().setSoTimeout(timeout * 1000); int status = -1; Object result = null; System.out.println("Execute method: " + method.getPath() + " " + method.getQueryString()); TwitterclipseConfig config = TwitterclipsePlugin.getDefault().getTwitterclipseConfiguration(); HttpClient httpClient = HttpClientUtils.createHttpClient(TWITTER_BASE_URL, config.getUserId(), config.getPassword()); status = httpClient.executeMethod(method); System.out.println("Received response. status = " + status); if (status == HttpStatus.SC_OK) { InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); String response = new String(baos.toByteArray(), "UTF-8"); System.out.println(response); if (array) result = JSONArray.fromString(response); else result = JSONObject.fromString(response); } else { throw new HttpRequestFailureException(status); } return result; } catch (SocketTimeoutException e) { throw new HttpRequestTimeoutException(e); } finally { method.releaseConnection(); } } Code Sample 2: public void storeArticles(Context ctx, RSSFeed feed) throws RSSHandlerError { try { mFeed = feed; db = new RSSDB(ctx); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(this); InputStream stream = feed.url.openStream(); InputSource source = new InputSource(stream); xr.parse(source); } catch (IOException e) { Log.e("GeneriCast", e.toString()); throw new RSSHandlerError("IOError"); } catch (SAXException e) { Log.e("GeneriCast", e.toString()); throw new RSSHandlerError("ParsingError"); } catch (ParserConfigurationException e) { Log.e("GeneriCast", e.toString()); throw new RSSHandlerError("ParsingError"); } }
11
Code Sample 1: public String hasheMotDePasse(String mdp) { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { } sha.reset(); sha.update(mdp.getBytes()); byte[] digest = sha.digest(); String pass = new String(Base64.encode(digest)); pass = "{SHA}" + pass; return pass; } Code Sample 2: public static String login() throws Exception { if (sid == null) { String login = ROLAPClientAux.loadProperties().getProperty("user"); String password = ROLAPClientAux.loadProperties().getProperty("password"); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); String password2 = asHexString(md.digest()); String query = "/server/login?user=" + login + "&extern_password=" + password + "&password=" + password2; Vector<String> res = ROLAPClientAux.sendRequest(query); String vals[] = res.get(0).split(";"); sid = vals[0]; } return sid; }
11
Code Sample 1: private static void insertModuleInEar(File fromEar, File toEar, String moduleType, String moduleName, String contextRoot) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEar)); FileOutputStream fos = new FileOutputStream(toEar); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("META-INF/application.xml")) { content = insertModule(earFile, next, content, moduleType, moduleName, contextRoot); next = new ZipEntry("META-INF/application.xml"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); } Code Sample 2: public Boolean compress(String sSourceDir, ArrayList<String> aFiles, String sDestinationFilename) { logger.debug("compress(%s, %s, %s)", sSourceDir, aFiles, sDestinationFilename); BufferedInputStream oOrigin = null; FileOutputStream oDestination; ZipOutputStream oOutput = null; Iterator<String> oIterator; byte[] aData; try { oDestination = new FileOutputStream(sDestinationFilename); oOutput = new ZipOutputStream(new BufferedOutputStream(oDestination)); aData = new byte[BUFFER_SIZE]; oIterator = aFiles.iterator(); while (oIterator.hasNext()) { try { String sFilename = (String) oIterator.next(); FileInputStream fisInput = new FileInputStream(sSourceDir + File.separator + sFilename); oOrigin = new BufferedInputStream(fisInput, BUFFER_SIZE); ZipEntry oEntry = new ZipEntry(sFilename.replace('\\', '/')); oOutput.putNextEntry(oEntry); int iCount; while ((iCount = oOrigin.read(aData, 0, BUFFER_SIZE)) != -1) oOutput.write(aData, 0, iCount); } finally { StreamHelper.close(oOrigin); } } } catch (Exception oException) { logger.error(oException.getMessage(), oException); return false; } finally { StreamHelper.close(oOutput); } return true; }
11
Code Sample 1: public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; Closer c = new Closer(); try { source = c.register(new FileInputStream(sourceFile).getChannel()); destination = c.register(new FileOutputStream(destFile).getChannel()); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { c.doNotThrow(); throw e; } finally { c.closeAll(); } } Code Sample 2: public void fileCopy(File inFile, File outFile) { try { FileInputStream in = new FileInputStream(inFile); FileOutputStream out = new FileOutputStream(outFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { System.err.println("Hubo un error de entrada/salida!!!"); } }
00
Code Sample 1: public String setContent(URL url, String inputdata) { String content = ""; try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.connect(); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(inputdata); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String strLine = ""; while ((strLine = in.readLine()) != null) { content = content + strLine; } in.close(); out.close(); } catch (IOException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Problem writing to " + url + " content " + inputdata, e); } return content; } Code Sample 2: protected void doRequest(HttpServletRequest request, HttpServletResponse response, boolean inGet) throws ServletException, IOException { response.setHeader("Server", WebConsoleServlet.SERVER_STRING); try { String requestedFilename = request.getRequestURI().substring(1); URL url = new URL(getJarFileName() + "/"); JarURLConnection jarConnection = (JarURLConnection) (url.openConnection()); JarFile jarFile = jarConnection.getJarFile(); String negotiatedFilename = null; ZipEntry zipEntry = null; zipEntry = negotiateImageFile(jarFile, requestedFilename, isIE6OrEarlier(request.getHeader("User-Agent"))); if (zipEntry == null) { zipEntry = jarFile.getEntry(requestedFilename); } else { negotiatedFilename = zipEntry.getName(); } if (zipEntry == null || zipEntry.isDirectory()) { handleFileNotFound(inGet, request, response); return; } int fileSize = (int) zipEntry.getSize(); response.setContentLength(fileSize); if (negotiatedFilename != null) { response.setContentType(getContentType(negotiatedFilename)); } else { response.setContentType(getContentType(request.getRequestURI())); } InputStream in = jarFile.getInputStream(zipEntry); BufferedInputStream bufferedInputStream = new BufferedInputStream(in); byte[] file = new byte[fileSize]; int bytesRead = bufferedInputStream.read(file); bufferedInputStream.close(); if (bytesRead == fileSize && cachingEnabled) { SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z"); java.util.Date today = new java.util.Date(); String date = formatter.format(GenericUtils.addOrSubstractDaysFromDate(today, 365)); response.setHeader("Expires", date); } OutputStream outputStream = response.getOutputStream(); outputStream.write(file); } catch (FileNotFoundException e) { handleFileNotFound(inGet, request, response); } catch (IOException e) { } catch (Throwable t) { Application.getApplication().logExceptionEvent(EventLogMessage.EventType.WEB_ERROR, t); } }
11
Code Sample 1: public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } } Code Sample 2: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); int i; Vector images = new Vector(); images = dataBase.allImageSearch(); lengthOfTask = images.size() * 2; String directory = directoryPath + "Images" + myDirectory.separator; File newDirectoryFolder = new File(directory); newDirectoryFolder.mkdirs(); try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); doc = domBuilder.newDocument(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Element dbElement = doc.createElement("dataBase"); for (i = 0; ((i < images.size()) && !stop); i++) { current = i; String element = (String) images.elementAt(i); String pathSrc = "Images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(myDirectory.separator) + 1, pathSrc.length()); String pathDst = directory + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector keyWords = new Vector(); keyWords = dataBase.asociatedConceptSearch((String) images.elementAt(i)); Element imageElement = doc.createElement("image"); Element imageNameElement = doc.createElement("name"); imageNameElement.appendChild(doc.createTextNode(name)); imageElement.appendChild(imageNameElement); for (int j = 0; j < keyWords.size(); j++) { Element keyWordElement = doc.createElement("keyWord"); keyWordElement.appendChild(doc.createTextNode((String) keyWords.elementAt(j))); imageElement.appendChild(keyWordElement); } dbElement.appendChild(imageElement); } try { doc.appendChild(dbElement); File dst = new File(directory.concat("Images")); BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "UTF-8")); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(bufferWriter); transformer.transform(source, result); bufferWriter.close(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } current = lengthOfTask; }
11
Code Sample 1: public static void main(String[] args) throws IOException { MSPack pack = new MSPack(new FileInputStream(args[0])); String[] files = pack.getFileNames(); for (int i = 0; i < files.length; i++) System.out.println(i + ": " + files[i] + ": " + pack.getLengths()[i]); System.out.println("Writing " + files[files.length - 1]); InputStream is = pack.getInputStream(files.length - 1); OutputStream os = new FileOutputStream(files[files.length - 1]); int n; byte[] buf = new byte[4096]; while ((n = is.read(buf)) != -1) os.write(buf, 0, n); os.close(); is.close(); } Code Sample 2: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
11
Code Sample 1: private static void copyImage(String srcImg, String destImg) { try { FileChannel srcChannel = new FileInputStream(srcImg).getChannel(); FileChannel dstChannel = new FileOutputStream(destImg).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static String encodeFromFile(String filename) throws java.io.IOException, URISyntaxException { String encodedData = null; Base641.InputStream bis = null; File file; try { URL url = new URL(filename); URLConnection conn = url.openConnection(); file = new File("myfile.doc"); java.io.InputStream inputStream = (java.io.InputStream) conn.getInputStream(); FileOutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; int length = 0; int numBytes = 0; bis = new Base641.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base641.ENCODE); while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } encodedData = new String(buffer, 0, length, Base641.PREFERRED_ENCODING); } catch (java.io.IOException e) { throw e; } finally { try { bis.close(); } catch (Exception e) { } } return encodedData; }
00
Code Sample 1: @SuppressWarnings(value = "RetentionPolicy.SOURCE") public static byte[] getHashMD5(String chave) { byte[] hashMd5 = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(chave.getBytes()); hashMd5 = md.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); Dialog.erro(ex.getMessage(), null); } return (hashMd5); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public void loginToServer() { new Thread(new Runnable() { public void run() { if (!shouldLogin) { u.p("skipping the auto-login"); return; } try { u.p("logging in to the server"); String query = "hostname=blahfoo2.com" + "&osname=" + URLEncoder.encode(System.getProperty("os.name"), "UTF-8") + "&javaver=" + URLEncoder.encode(System.getProperty("java.runtime.version"), "UTF-8") + "&timezone=" + URLEncoder.encode(TimeZone.getDefault().getID(), "UTF-8"); u.p("unencoded query: \n" + query); String login_url = "http://joshy.org:8088/org.glossitopeTracker/login.jsp?"; String url = login_url + query; u.p("final encoded url = \n" + url); InputStream in = new URL(url).openStream(); byte[] buf = new byte[256]; while (true) { int n = in.read(buf); if (n == -1) break; for (int i = 0; i < n; i++) { } } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }, "LoginToServerAction").start(); } Code Sample 2: public void create() throws IOException { FileChannel fc = new FileInputStream(sourceFile).getChannel(); for (RangeArrayElement element : array) { FileChannel fc_ = fc.position(element.starting()); File part = new File(destinationDirectory, "_0x" + Long.toHexString(element.starting()) + ".partial"); FileChannel partfc = new FileOutputStream(part).getChannel(); partfc.transferFrom(fc_, 0, element.getSize()); partfc.force(true); partfc.close(); } fc.close(); }
00
Code Sample 1: public void sendFile(File file, String filename, String contentType) throws SearchLibException { response.setContentType(contentType); response.addHeader("Content-Disposition", "attachment; filename=" + filename); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); ServletOutputStream outputStream = getOutputStream(); IOUtils.copy(inputStream, outputStream); outputStream.close(); } catch (FileNotFoundException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } finally { if (inputStream != null) IOUtils.closeQuietly(inputStream); } } Code Sample 2: private final void lookup() throws Exception { try { URL url; URLConnection urlConn; DataOutputStream printout; BufferedReader input; url = new URL("http://www.amazon.com/exec/obidos/search-handle-form"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String content = "page=" + URLEncoder.encode("1") + "&index=" + URLEncoder.encode("music") + "&field-artist=" + URLEncoder.encode(artist) + "&field-title=" + URLEncoder.encode(title) + "&field-binding=" + URLEncoder.encode(""); printout.writeBytes(content); printout.flush(); printout.close(); input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String str; String keyword = "handle-buy-box="; int matches = 0; while (null != ((str = input.readLine()))) { int idStart = str.indexOf(keyword); if (idStart > 0) { idStart = idStart + keyword.length(); String id = str.substring(idStart, idStart + 10); status.append("Match: "); status.append(id); status.append(". "); if (verifyMatch(id, title)) { discID = id; imageURL = "http://images.amazon.com/images/P/" + id + ".01.LZZZZZZZ.jpg"; matchType = EXACT_MATCH; } } } input.close(); } catch (Exception e) { throw e; } }
00
Code Sample 1: public MapInfo getMap(double latitude, double longitude, double wanted_mapblast_scale, int image_width, int image_height, String file_path_wo_extension, ProgressListener progress_listener) throws IOException { try { if (web_request_ == null) { web_request_ = new HttpRequester(HOST_NAME); } int zoom_index = getZoomLevelIndex(wanted_mapblast_scale); int google_zoom_level = GOOGLE_ZOOM_LEVELS[zoom_index]; double mapblast_scale = POSSIBLE_GOOGLE_SCALES[zoom_index]; Tile tile = new Tile(latitude, longitude, google_zoom_level); SimplePoint coords = tile.getTileLatLong(); SimplePoint google_xy = tile.getTileCoord(); MapInfo map_info = new MapInfo(); map_info.setLatitude(coords.getX()); map_info.setLongitude(coords.getY()); map_info.setScale((float) mapblast_scale); map_info.setWidth(256); map_info.setHeight(256); map_info.setFilename(file_path_wo_extension + "png"); Object[] params = new Object[] { new Integer(google_xy.getX()), new Integer(google_xy.getY()), new Integer(google_zoom_level) }; MessageFormat message_format = new MessageFormat(GOOGLE_MAPS_URL, Locale.US); String url_string = message_format.format(params); URL url = new URL(url_string); if (Debug.DEBUG) Debug.println("map_download", "loading map from url: " + url); URLConnection connection = url.openConnection(); if (resources_.getBoolean(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USE)) { String proxy_userid = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USERNAME); String proxy_password = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_PASSWORD); String auth_string = proxy_userid + ":" + proxy_password; auth_string = "Basic " + new sun.misc.BASE64Encoder().encode(auth_string.getBytes()); connection.setRequestProperty("Proxy-Authorization", auth_string); } connection.connect(); String mime_type = connection.getContentType().toLowerCase(); if (!mime_type.startsWith("image")) { if (mime_type.startsWith("text")) { HTMLViewerFrame viewer = new HTMLViewerFrame(url); viewer.setSize(640, 480); viewer.setTitle("ERROR on loading url: " + url); viewer.setVisible(true); throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type + "\nPage is displayed in HTML frame."); } throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type); } int content_length = connection.getContentLength(); if (content_length < 0) progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, Integer.MIN_VALUE); else progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, content_length); String extension = mime_type.substring(mime_type.indexOf('/') + 1); String filename = file_path_wo_extension + extension; FileOutputStream out = new FileOutputStream(filename); byte[] buffer = new byte[BUFFER_SIZE]; BufferedInputStream in = new BufferedInputStream(connection.getInputStream(), BUFFER_SIZE); int sum_bytes = 0; int num_bytes = 0; while ((num_bytes = in.read(buffer)) != -1) { out.write(buffer, 0, num_bytes); sum_bytes += num_bytes; progress_listener.actionProgress(PROGRESS_LISTENER_ID, sum_bytes); } progress_listener.actionEnd(PROGRESS_LISTENER_ID); in.close(); out.close(); return (map_info); } catch (NoRouteToHostException nrhe) { nrhe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = nrhe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_NO_ROUTE_TO_HOST_MESSAGE); throw new IOException(message); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = fnfe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_FILE_NOT_FOUND_MESSAGE); throw new IOException(message); } catch (Exception e) { progress_listener.actionEnd(PROGRESS_LISTENER_ID); e.printStackTrace(); String message = e.getMessage(); if (message == null) { Throwable cause = e.getCause(); if (cause != null) message = cause.getMessage(); } throw new IOException(message); } } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static boolean isMatchingAsPassword(final String password, final String amd5Password) { boolean response = false; try { final MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); final byte[] md5Byte = algorithm.digest(); final StringBuffer buffer = new StringBuffer(); for (final byte b : md5Byte) { if ((b <= 15) && (b >= 0)) { buffer.append("0"); } buffer.append(Integer.toHexString(0xFF & b)); } response = (amd5Password != null) && amd5Password.equals(buffer.toString()); } catch (final NoSuchAlgorithmException e) { ProjektUtil.LOG.error("No digester MD5 found in classpath!", e); } return response; }
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 getStringFromAFileAtURL(String anURL) { String htmlCode = "<html><body></body></html>"; try { URL url = new URL(anURL); URLConnection urlConnection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine = ""; htmlCode = ""; while ((inputLine = in.readLine()) != null) htmlCode += inputLine + "\n"; in.close(); } catch (Exception e) { logs.info("URLResolver : lien mort"); JOptionPane.showMessageDialog(null, "lien mort"); return "<html><body></body></html>"; } return checkXMLTagsLowerCase(htmlCode); }
00
Code Sample 1: public static String hash(String password) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(password.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(Hex.encodeHex(rawHash)); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public boolean saveLecturerecordingsXMLOnWebserver() { boolean error = false; FTPClient ftp = new FTPClient(); String lecture = ""; try { URL url = new URL("http://localhost:8080/virtPresenterVerwalter/lecturerecordings.jsp?seminarid=" + this.getSeminarID()); HttpURLConnection http = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream())); String zeile = ""; while ((zeile = in.readLine()) != null) { lecture += zeile + "\n"; } in.close(); http.disconnect(); } catch (Exception e) { System.err.println("Konnte lecturerecordings.xml nicht lesen."); } try { int reply; ftp.connect(this.getWebserver().getUrl()); System.out.println("Connected to " + this.getWebserver().getUrl() + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return false; } if (!ftp.login(this.getWebserver().getFtpBenutzer(), this.getWebserver().getFtpPasswort())) { System.err.println("FTP server: Login incorrect"); } String tmpSeminarID = this.getSeminarID(); if (tmpSeminarID == null) tmpSeminarID = "unbekannt"; try { ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); } catch (Exception e) { ftp.makeDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ByteArrayInputStream lectureIn = new ByteArrayInputStream(lecture.getBytes()); System.err.println("FTP Verzeichnis: " + ftp.printWorkingDirectory()); ftp.storeFile("lecturerecordings.xml", lectureIn); lectureIn.close(); ftp.logout(); ftp.disconnect(); } catch (IOException e) { System.err.println("Job " + this.getId() + ": Datei lecturerecordings.xml konnte nicht auf Webserver kopiert werden."); error = true; e.printStackTrace(); } catch (NullPointerException e) { System.err.println("Job " + this.getId() + ": Datei lecturerecordings.xml konnte nicht auf Webserver kopiert werden. (Kein Webserver zugewiesen)"); error = true; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return error; }
00
Code Sample 1: public Vector _getSiteNames() { Vector _mySites = new Vector(); boolean gotSites = false; while (!gotSites) { try { URL dataurl = new URL(getDocumentBase(), siteFile); BufferedReader readme = new BufferedReader(new InputStreamReader(new GZIPInputStream(dataurl.openStream()))); while (true) { String S = readme.readLine(); if (S == null) break; StringTokenizer st = new StringTokenizer(S); _mySites.addElement(st.nextToken()); } gotSites = true; } catch (IOException e) { _mySites.removeAllElements(); gotSites = false; } } return (_mySites); } Code Sample 2: private String sendToServer(String request) throws IOException { Log.d("test", "request body " + request); String result = null; maybeCreateHttpClient(); HttpPost post = new HttpPost(Config.APP_BASE_URI); post.addHeader("Content-Type", "text/vnd.aexp.json.req"); post.setEntity(new StringEntity(request)); HttpResponse resp = httpClient.execute(post); int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) throw new IOException("HTTP status: " + Integer.toString(status)); DataInputStream is = new DataInputStream(resp.getEntity().getContent()); result = is.readLine(); return result; }
00
Code Sample 1: private void extractByParsingHtml(String refererURL, String requestURL) throws MalformedURLException, IOException { URL url = new URL(refererURL); InputStream is = url.openStream(); mRefererURL = refererURL; if (requestURL.startsWith("http://www.")) { mRequestURLWWW = requestURL; mRequestURL = "http://" + mRequestURLWWW.substring(11); } else { mRequestURL = requestURL; mRequestURLWWW = "http://www." + mRequestURL.substring(7); } Parser parser = (new HTMLEditorKit() { public Parser getParser() { return super.getParser(); } }).getParser(); StringBuffer sb = new StringBuffer(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); try { String line = null; while ((line = br.readLine()) != null) { sb.append(line); } } finally { br.close(); } StringReader sr = new StringReader(sb.toString()); parser.parse(sr, new LinkbackCallback(), true); if (mStart != 0 && mEnd != 0 && mEnd > mStart) { mExcerpt = sb.toString().substring(mStart, mEnd); mExcerpt = Utilities.removeHTML(mExcerpt); if (mExcerpt.length() > mMaxExcerpt) { mExcerpt = mExcerpt.substring(0, mMaxExcerpt) + "..."; } } if (mTitle.startsWith(">") && mTitle.length() > 1) { mTitle = mTitle.substring(1); } } Code Sample 2: @SuppressWarnings("unchecked") protected void processDownloadAction(HttpServletRequest request, HttpServletResponse response) throws Exception { File transformationFile = new File(xslBase, "file-info.xsl"); HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); DataSourceIf dataSource = new NullSource(); Document fileInfoDoc = XmlUtils.getEmptyDOM(); DOMResult result = new DOMResult(fileInfoDoc); transformer.transform((Source) dataSource, result); Element documentElement = fileInfoDoc.getDocumentElement(); if (documentElement.getLocalName().equals("null")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } InputStream is = null; try { XPath xpath = XPathFactory.newInstance().newXPath(); String sourceType = XPathUtils.getStringValue(xpath, "source-type", documentElement, null); String location = XPathUtils.getStringValue(xpath, "location", documentElement, null); String fileName = XPathUtils.getStringValue(xpath, "file-name", documentElement, null); String mimeType = XPathUtils.getStringValue(xpath, "mime-type", documentElement, null); String encoding = XPathUtils.getStringValue(xpath, "encoding", documentElement, null); if (StringUtils.equals(sourceType, "cifsSource")) { String domain = XPathUtils.getStringValue(xpath, "domain", documentElement, null); String userName = XPathUtils.getStringValue(xpath, "username", documentElement, null); String password = XPathUtils.getStringValue(xpath, "password", documentElement, null); URI uri = new URI(location); if (StringUtils.isNotBlank(userName)) { String userInfo = ""; if (StringUtils.isNotBlank(domain)) { userInfo = userInfo + domain + ";"; } userInfo = userInfo + userName; if (StringUtils.isNotBlank(password)) { userInfo = userInfo + ":" + password; } uri = new URI(uri.getScheme(), userInfo, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } SmbFile smbFile = new SmbFile(uri.toURL()); is = new SmbFileInputStream(smbFile); } else if (StringUtils.equals(sourceType, "localFileSystemSource")) { File file = new File(location); is = new FileInputStream(file); } else { logger.error("Source type \"" + ((sourceType != null) ? sourceType : "") + "\" not supported"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (StringUtils.isBlank(mimeType) && StringUtils.isBlank(encoding)) { response.setContentType(Definitions.MIMETYPE_BINARY); } else if (StringUtils.isBlank(encoding)) { response.setContentType(mimeType); } else { response.setContentType(mimeType + ";charset=" + encoding); } if (request.getParameterMap().containsKey(Definitions.REQUEST_PARAMNAME_DOWNLOAD)) { response.setHeader("Content-Disposition", "attachment; filename=" + fileName); } IOUtils.copy(new BufferedInputStream(is), response.getOutputStream()); } finally { if (is != null) { is.close(); } } }
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: private void copyValidFile(File file, int cviceni) { try { String filename = String.format("%s%s%02d%s%s", validovane, File.separator, cviceni, File.separator, file.getName()); boolean copy = false; File newFile = new File(filename); if (newFile.exists()) { if (file.lastModified() > newFile.lastModified()) copy = true; else copy = false; } else { newFile.createNewFile(); copy = true; } if (copy) { String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(newFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); newFile.setLastModified(file.lastModified()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private LinkedList<Datum> processDatum(Datum dataset) { ArrayList<Object[]> markerTestResults = new ArrayList<Object[]>(); ArrayList<Object[]> alleleEstimateResults = new ArrayList<Object[]>(); boolean hasAlleleNames = false; String blank = new String(""); MarkerPhenotypeAdapter theAdapter; if (dataset.getDataType().equals(MarkerPhenotype.class)) { theAdapter = new MarkerPhenotypeAdapter((MarkerPhenotype) dataset.getData()); } else theAdapter = new MarkerPhenotypeAdapter((Phenotype) dataset.getData()); int numberOfMarkers = theAdapter.getNumberOfMarkers(); if (numberOfMarkers == 0) { return calculateBLUEsFromPhenotypes(theAdapter, dataset.getName()); } int numberOfCovariates = theAdapter.getNumberOfCovariates(); int numberOfFactors = theAdapter.getNumberOfFactors(); int numberOfPhenotypes = theAdapter.getNumberOfPhenotypes(); int expectedIterations = numberOfPhenotypes * numberOfMarkers; int iterationsSofar = 0; int percentFinished = 0; File tempFile = null; File ftestFile = null; File blueFile = null; BufferedWriter ftestWriter = null; BufferedWriter BLUEWriter = null; String ftestHeader = "Trait\tMarker\tLocus\tLocus_pos\tChr\tChr_pos\tmarker_F\tmarker_p\tperm_p\tmarkerR2\tmarkerDF\tmarkerMS\terrorDF\terrorMS\tmodelDF\tmodelMS"; String BLUEHeader = "Trait\tMarker\tObs\tLocus\tLocus_pos\tChr\tChr_pos\tAllele\tEstimate"; if (writeOutputToFile) { String outputbase = outputName; if (outputbase.endsWith(".txt")) { int index = outputbase.lastIndexOf("."); outputbase = outputbase.substring(0, index); } String datasetNameNoSpace = dataset.getName().trim().replaceAll("\\ ", "_"); ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.txt"); int count = 0; while (ftestFile.exists()) { count++; ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest" + count + ".txt"); } blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs.txt"); count = 0; while (blueFile.exists()) { count++; blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs" + count + ".txt"); } tempFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.tmp"); try { if (permute) { ftestWriter = new BufferedWriter(new FileWriter(tempFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } else { ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } if (reportBLUEs) { BLUEWriter = new BufferedWriter(new FileWriter(blueFile)); BLUEWriter.write(BLUEHeader); BLUEWriter.newLine(); } } catch (IOException e) { myLogger.error("Failed to open file for output"); myLogger.error(e); return null; } } if (permute) { minP = new double[numberOfPhenotypes][numberOfPermutations]; for (int i = 0; i < numberOfPermutations; i++) { for (int j = 0; j < numberOfPhenotypes; j++) { minP[j][i] = 1; } } } for (int ph = 0; ph < numberOfPhenotypes; ph++) { double[] phenotypeData = theAdapter.getPhenotypeValues(ph); boolean[] missing = theAdapter.getMissingPhenotypes(ph); ArrayList<String[]> factorList = MarkerPhenotypeAdapterUtils.getFactorList(theAdapter, ph, missing); ArrayList<double[]> covariateList = MarkerPhenotypeAdapterUtils.getCovariateList(theAdapter, ph, missing); double[][] permutedData = null; if (permute) { permutedData = permuteData(phenotypeData, missing, factorList, covariateList, theAdapter); } for (int m = 0; m < numberOfMarkers; m++) { Object[] markerData = theAdapter.getMarkerValue(ph, m); boolean[] finalMissing = new boolean[missing.length]; System.arraycopy(missing, 0, finalMissing, 0, missing.length); MarkerPhenotypeAdapterUtils.updateMissing(finalMissing, theAdapter.getMissingMarkers(ph, m)); int[] nonmissingRows = MarkerPhenotypeAdapterUtils.getNonMissingIndex(finalMissing); int numberOfObs = nonmissingRows.length; double[] y = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) y[i] = phenotypeData[nonmissingRows[i]]; int firstMarkerAlleleEstimate = 1; ArrayList<ModelEffect> modelEffects = new ArrayList<ModelEffect>(); FactorModelEffect meanEffect = new FactorModelEffect(new int[numberOfObs], false); meanEffect.setID("mean"); modelEffects.add(meanEffect); if (numberOfFactors > 0) { for (int f = 0; f < numberOfFactors; f++) { String[] afactor = factorList.get(f); String[] factorLabels = new String[numberOfObs]; for (int i = 0; i < numberOfObs; i++) factorLabels[i] = afactor[nonmissingRows[i]]; FactorModelEffect fme = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(factorLabels), true, theAdapter.getFactorName(f)); modelEffects.add(fme); firstMarkerAlleleEstimate += fme.getNumberOfLevels() - 1; } } if (numberOfCovariates > 0) { for (int c = 0; c < numberOfCovariates; c++) { double[] covar = new double[numberOfObs]; double[] covariateData = covariateList.get(c); for (int i = 0; i < numberOfObs; i++) covar[i] = covariateData[nonmissingRows[i]]; modelEffects.add(new CovariateModelEffect(covar, theAdapter.getCovariateName(c))); firstMarkerAlleleEstimate++; } } ModelEffect markerEffect; boolean markerIsDiscrete = theAdapter.isMarkerDiscrete(m); ArrayList<Object> alleleNames = new ArrayList<Object>(); if (markerIsDiscrete) { Object[] markers = new Object[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markers[i] = markerData[nonmissingRows[i]]; int[] markerLevels = ModelEffectUtils.getIntegerLevels(markers, alleleNames); markerEffect = new FactorModelEffect(markerLevels, true, theAdapter.getMarkerName(m)); hasAlleleNames = true; } else { double[] markerdbl = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markerdbl[i] = ((Double) markerData[nonmissingRows[i]]).doubleValue(); markerEffect = new CovariateModelEffect(markerdbl, theAdapter.getMarkerName(m)); } int[] alleleCounts = markerEffect.getLevelCounts(); modelEffects.add(markerEffect); int markerEffectNumber = modelEffects.size() - 1; Identifier[] taxaSublist = new Identifier[numberOfObs]; Identifier[] taxa = theAdapter.getTaxa(ph); for (int i = 0; i < numberOfObs; i++) taxaSublist[i] = taxa[nonmissingRows[i]]; boolean areTaxaReplicated = containsDuplicates(taxaSublist); double[] markerSSdf = null, errorSSdf = null, modelSSdf = null; double F, p; double[] beta = null; if (areTaxaReplicated && markerIsDiscrete) { ModelEffect taxaEffect = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(taxaSublist), true); modelEffects.add(taxaEffect); SweepFastNestedModel sfnm = new SweepFastNestedModel(modelEffects, y); double[] taxaSSdf = sfnm.getTaxaInMarkerSSdf(); double[] residualSSdf = sfnm.getErrorSSdf(); markerSSdf = sfnm.getMarkerSSdf(); errorSSdf = sfnm.getErrorSSdf(); modelSSdf = sfnm.getModelcfmSSdf(); F = markerSSdf[0] / markerSSdf[1] / taxaSSdf[0] * taxaSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], taxaSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sfnm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sfnm.getInverseOfXtX(), markerdf); } } else { SweepFastLinearModel sflm = new SweepFastLinearModel(modelEffects, y); modelSSdf = sflm.getModelcfmSSdf(); markerSSdf = sflm.getMarginalSSdf(markerEffectNumber); errorSSdf = sflm.getResidualSSdf(); F = markerSSdf[0] / markerSSdf[1] / errorSSdf[0] * errorSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], errorSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sflm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sflm.getInverseOfXtX(), markerdf); } } if (!filterOutput || p < maxp) { String traitname = theAdapter.getPhenotypeName(ph); if (traitname == null) traitname = blank; String marker = theAdapter.getMarkerName(m); if (marker == null) marker = blank; String locus = theAdapter.getLocusName(m); Integer site = new Integer(theAdapter.getLocusPosition(m)); String chrname = ""; Double chrpos = Double.NaN; if (hasMap) { int ndx = -1; ndx = myMap.getMarkerIndex(marker); if (ndx > -1) { chrname = myMap.getChromosome(ndx); chrpos = myMap.getGeneticPosition(ndx); } } Object[] result = new Object[16]; int col = 0; result[col++] = traitname; result[col++] = marker; result[col++] = locus; result[col++] = site; result[col++] = chrname; result[col++] = chrpos; result[col++] = new Double(F); result[col++] = new Double(p); result[col++] = Double.NaN; result[col++] = new Double(markerSSdf[0] / (modelSSdf[0] + errorSSdf[0])); result[col++] = new Double(markerSSdf[1]); result[col++] = new Double(markerSSdf[0] / markerSSdf[1]); result[col++] = new Double(errorSSdf[1]); result[col++] = new Double(errorSSdf[0] / errorSSdf[1]); result[col++] = new Double(modelSSdf[1]); result[col++] = new Double(modelSSdf[0] / modelSSdf[1]); if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int i = 1; i < 16; i++) sb.append("\t").append(result[i]); try { ftestWriter.write(sb.toString()); ftestWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { markerTestResults.add(result); } int numberOfMarkerAlleles = alleleNames.size(); if (numberOfMarkerAlleles == 0) numberOfMarkerAlleles++; for (int i = 0; i < numberOfMarkerAlleles; i++) { result = new Object[9]; result[0] = traitname; result[1] = marker; result[2] = new Integer(alleleCounts[i]); result[3] = locus; result[4] = site; result[5] = chrname; result[6] = chrpos; if (numberOfMarkerAlleles == 1) result[7] = ""; else result[7] = alleleNames.get(i); if (i == numberOfMarkerAlleles - 1) result[8] = 0.0; else result[8] = beta[firstMarkerAlleleEstimate + i]; if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int j = 1; j < 9; j++) sb.append("\t").append(result[j]); try { BLUEWriter.write(sb.toString()); BLUEWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { alleleEstimateResults.add(result); } } } int tmpPercent = ++iterationsSofar * 100 / expectedIterations; if (tmpPercent > percentFinished) { percentFinished = tmpPercent; fireProgress(percentFinished); } } } fireProgress(0); if (writeOutputToFile) { try { ftestWriter.close(); BLUEWriter.close(); } catch (IOException e) { e.printStackTrace(); } } HashMap<String, Integer> traitnameMap = new HashMap<String, Integer>(); if (permute) { for (int ph = 0; ph < numberOfPhenotypes; ph++) { Arrays.sort(minP[ph]); traitnameMap.put(theAdapter.getPhenotypeName(ph), ph); } if (writeOutputToFile) { try { BufferedReader tempReader = new BufferedReader(new FileReader(tempFile)); ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(tempReader.readLine()); ftestWriter.newLine(); String input; String[] data; Pattern tab = Pattern.compile("\t"); while ((input = tempReader.readLine()) != null) { data = tab.split(input); String trait = data[0]; double pval = Double.parseDouble(data[7]); int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; data[8] = Double.toString((double) ndx / (double) numberOfPermutations); ftestWriter.write(data[0]); for (int i = 1; i < data.length; i++) { ftestWriter.write("\t"); ftestWriter.write(data[i]); } ftestWriter.newLine(); } tempReader.close(); ftestWriter.close(); tempFile.delete(); } catch (IOException e) { myLogger.error(e); } } else { for (Object[] result : markerTestResults) { String trait = result[0].toString(); double pval = (Double) result[7]; int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; result[8] = new Double((double) ndx / (double) numberOfPermutations); } } } String[] columnLabels = new String[] { "Trait", "Marker", "Locus", "Locus_pos", "Chr", "Chr_pos", "marker_F", "marker_p", "perm_p", "markerR2", "markerDF", "markerMS", "errorDF", "errorMS", "modelDF", "modelMS" }; boolean hasMarkerNames = theAdapter.hasMarkerNames(); LinkedList<Integer> outputList = new LinkedList<Integer>(); outputList.add(0); if (hasMarkerNames) outputList.add(1); outputList.add(2); outputList.add(3); if (hasMap) { outputList.add(4); outputList.add(5); } outputList.add(6); outputList.add(7); if (permute) outputList.add(8); for (int i = 9; i < 16; i++) outputList.add(i); LinkedList<Datum> resultset = new LinkedList<Datum>(); int nrows = markerTestResults.size(); Object[][] table = new Object[nrows][]; int numberOfColumns = outputList.size(); String[] colnames = new String[numberOfColumns]; int count = 0; for (Integer ndx : outputList) colnames[count++] = columnLabels[ndx]; for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = markerTestResults.get(i); count = 0; for (Integer ndx : outputList) table[i][count++] = result[ndx]; } StringBuilder tableName = new StringBuilder("GLM_marker_test_"); tableName.append(dataset.getName()); StringBuilder comments = new StringBuilder("Tests of Marker-Phenotype Association"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + ftestFile.getPath()); } TableReport markerTestReport = new SimpleTableReport("Marker Test", colnames, table); resultset.add(new Datum(tableName.toString(), markerTestReport, comments.toString())); int[] outputIndex; columnLabels = new String[] { "Trait", "Marker", "Obs", "Locus", "Locus_pos", "Chr", "Chr_pos", "Allele", "Estimate" }; if (hasAlleleNames) { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 7, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 7, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 7, 8 }; } } else { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 8 }; } } nrows = alleleEstimateResults.size(); table = new Object[nrows][]; numberOfColumns = outputIndex.length; colnames = new String[numberOfColumns]; for (int j = 0; j < numberOfColumns; j++) { colnames[j] = columnLabels[outputIndex[j]]; } for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = alleleEstimateResults.get(i); for (int j = 0; j < numberOfColumns; j++) { table[i][j] = result[outputIndex[j]]; } } tableName = new StringBuilder("GLM allele estimates for "); tableName.append(dataset.getName()); comments = new StringBuilder("Marker allele effect estimates\n"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + blueFile.getPath()); } TableReport alleleEstimateReport = new SimpleTableReport("Allele Estimates", colnames, table); resultset.add(new Datum(tableName.toString(), alleleEstimateReport, comments.toString())); fireProgress(0); return resultset; } Code Sample 2: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
11
Code Sample 1: public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Git git = Git.getCurrent(req.getSession()); GitComponentReader gitReader = git.getComponentReader("warpinjector"); String id = req.getParameter("id"); GitElement element = gitReader.getElement(id); String path = (String) element.getAttribute("targetdir"); File folder = new File(path); PrintWriter out = helper.getPrintWriter(resp); MessageBundle messageBundle = new MessageBundle("net.sf.warpcore.cms/servlets/InjectorServletMessages"); Locale locale = req.getLocale(); helper.header(out, messageBundle, locale); if (git.getUser() == null) { helper.notLoggedIn(out, messageBundle, locale); } else { try { MultiPartRequest request = new MultiPartRequest(req); FileInfo info = request.getFileInfo("userfile"); File file = info.getFile(); out.println("tempfile found: " + file.getPath() + "<br>"); String fileName = info.getFileName(); File target = new File(folder, fileName); out.println("copying tempfile to: " + target.getPath() + "<br>"); FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(target); byte buf[] = new byte[1024]; int n; while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); out.println("copy successful - deleting old tempfile<br>"); out.println("deletion result. " + file.delete() + "<p>"); out.println(messageBundle.getMessage("Done. The file {0} has been uploaded", new String[] { "'" + fileName + "'" }, locale)); out.println("<p><a href=\"" + req.getRequestURI() + "?id=" + req.getParameter("id") + "\">" + messageBundle.getMessage("Click here to import another file.", locale) + "</a>"); } catch (Exception ex) { out.println(messageBundle.getMessage("An error occured: {0}", new String[] { ex.getMessage() }, locale)); } } helper.footer(out); } Code Sample 2: protected void setupService(MessageContext msgContext) throws Exception { String realpath = msgContext.getStrProp(Constants.MC_REALPATH); String extension = (String) getOption(OPTION_JWS_FILE_EXTENSION); if (extension == null) extension = DEFAULT_JWS_FILE_EXTENSION; if ((realpath != null) && (realpath.endsWith(extension))) { String jwsFile = realpath; String rel = msgContext.getStrProp(Constants.MC_RELATIVE_PATH); File f2 = new File(jwsFile); if (!f2.exists()) { throw new FileNotFoundException(rel); } if (rel.charAt(0) == '/') { rel = rel.substring(1); } int lastSlash = rel.lastIndexOf('/'); String dir = null; if (lastSlash > 0) { dir = rel.substring(0, lastSlash); } String file = rel.substring(lastSlash + 1); String outdir = msgContext.getStrProp(Constants.MC_JWS_CLASSDIR); if (outdir == null) outdir = "."; if (dir != null) { outdir = outdir + File.separator + dir; } File outDirectory = new File(outdir); if (!outDirectory.exists()) { outDirectory.mkdirs(); } if (log.isDebugEnabled()) log.debug("jwsFile: " + jwsFile); String jFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "java"; String cFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "class"; if (log.isDebugEnabled()) { log.debug("jFile: " + jFile); log.debug("cFile: " + cFile); log.debug("outdir: " + outdir); } File f1 = new File(cFile); String clsName = null; if (clsName == null) clsName = f2.getName(); if (clsName != null && clsName.charAt(0) == '/') clsName = clsName.substring(1); clsName = clsName.substring(0, clsName.length() - extension.length()); clsName = clsName.replace('/', '.'); if (log.isDebugEnabled()) log.debug("ClsName: " + clsName); if (!f1.exists() || f2.lastModified() > f1.lastModified()) { log.debug(Messages.getMessage("compiling00", jwsFile)); log.debug(Messages.getMessage("copy00", jwsFile, jFile)); FileReader fr = new FileReader(jwsFile); FileWriter fw = new FileWriter(jFile); char[] buf = new char[4096]; int rc; while ((rc = fr.read(buf, 0, 4095)) >= 0) fw.write(buf, 0, rc); fw.close(); fr.close(); log.debug("javac " + jFile); Compiler compiler = CompilerFactory.getCompiler(); compiler.setClasspath(ClasspathUtils.getDefaultClasspath(msgContext)); compiler.setDestination(outdir); compiler.addFile(jFile); boolean result = compiler.compile(); (new File(jFile)).delete(); if (!result) { (new File(cFile)).delete(); Document doc = XMLUtils.newDocument(); Element root = doc.createElementNS("", "Errors"); StringBuffer message = new StringBuffer("Error compiling "); message.append(jFile); message.append(":\n"); List errors = compiler.getErrors(); int count = errors.size(); for (int i = 0; i < count; i++) { CompilerError error = (CompilerError) errors.get(i); if (i > 0) message.append("\n"); message.append("Line "); message.append(error.getStartLine()); message.append(", column "); message.append(error.getStartColumn()); message.append(": "); message.append(error.getMessage()); } root.appendChild(doc.createTextNode(message.toString())); throw new AxisFault("Server.compileError", Messages.getMessage("badCompile00", jFile), null, new Element[] { root }); } ClassUtils.removeClassLoader(clsName); soapServices.remove(clsName); } ClassLoader cl = ClassUtils.getClassLoader(clsName); if (cl == null) { cl = new JWSClassLoader(clsName, msgContext.getClassLoader(), cFile); } msgContext.setClassLoader(cl); SOAPService rpc = (SOAPService) soapServices.get(clsName); if (rpc == null) { rpc = new SOAPService(new RPCProvider()); rpc.setName(clsName); rpc.setOption(RPCProvider.OPTION_CLASSNAME, clsName); rpc.setEngine(msgContext.getAxisEngine()); String allowed = (String) getOption(RPCProvider.OPTION_ALLOWEDMETHODS); if (allowed == null) allowed = "*"; rpc.setOption(RPCProvider.OPTION_ALLOWEDMETHODS, allowed); String scope = (String) getOption(RPCProvider.OPTION_SCOPE); if (scope == null) scope = Scope.DEFAULT.getName(); rpc.setOption(RPCProvider.OPTION_SCOPE, scope); rpc.getInitializedServiceDesc(msgContext); soapServices.put(clsName, rpc); } rpc.setEngine(msgContext.getAxisEngine()); rpc.init(); msgContext.setService(rpc); } if (log.isDebugEnabled()) { log.debug("Exit: JWSHandler::invoke"); } }
11
Code Sample 1: private void copyFile(File sourceFile, File destFile) throws IOException { if (log.isDebugEnabled()) { log.debug("CopyFile : Source[" + sourceFile.getAbsolutePath() + "] Dest[" + destFile.getAbsolutePath() + "]"); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: private void fileMaker() { try { long allData = 0; double a = 10; int range = 0; int blockLength = 0; File newFile = new File(mfr.getFilename() + ".part"); if (newFile.exists()) { newFile.delete(); } ArrayList<DataRange> rangeList = null; byte[] data = null; newFile.createNewFile(); ByteBuffer buffer = ByteBuffer.allocate(mfr.getBlocksize()); FileChannel rChannel = new FileInputStream(inputFileName).getChannel(); FileChannel wChannel = new FileOutputStream(newFile, true).getChannel(); System.out.println(); System.out.print("File completion: "); System.out.print("|----------|"); openConnection(); http.getResponseHeader(); for (int i = 0; i < fileMap.length; i++) { fileOffset = fileMap[i]; if (fileOffset != -1) { rChannel.read(buffer, fileOffset); buffer.flip(); wChannel.write(buffer); buffer.clear(); } else { if (!rangeQueue) { rangeList = rangeLookUp(i); range = rangeList.size(); openConnection(); http.setRangesRequest(rangeList); http.sendRequest(); http.getResponseHeader(); data = http.getResponseBody(mfr.getBlocksize()); allData += http.getAllTransferedDataLength(); } if ((i * mfr.getBlocksize() + mfr.getBlocksize()) < mfr.getLength()) { blockLength = mfr.getBlocksize(); } else { blockLength = (int) ((int) (mfr.getBlocksize()) + (mfr.getLength() - (i * mfr.getBlocksize() + mfr.getBlocksize()))); } buffer.put(data, (range - rangeList.size()) * mfr.getBlocksize(), blockLength); buffer.flip(); wChannel.write(buffer); buffer.clear(); rangeList.remove(0); if (rangeList.isEmpty()) { rangeQueue = false; } } if ((((double) i / ((double) fileMap.length - 1)) * 100) >= a) { progressBar(((double) i / ((double) fileMap.length - 1)) * 100); a += 10; } } newFile.setLastModified(getMTime()); sha = new SHA1(newFile); if (sha.SHA1sum().equals(mfr.getSha1())) { System.out.println("\nverifying download...checksum matches OK"); System.out.println("used " + (mfr.getLength() - (mfr.getBlocksize() * missing)) + " " + "local, fetched " + (mfr.getBlocksize() * missing)); new File(mfr.getFilename()).renameTo(new File(mfr.getFilename() + ".zs-old")); newFile.renameTo(new File(mfr.getFilename())); allData += mfr.getLengthOfMetafile(); System.out.println("really downloaded " + allData); double overhead = ((double) (allData - (mfr.getBlocksize() * missing)) / ((double) (mfr.getBlocksize() * missing))) * 100; System.out.println("overhead: " + df.format(overhead) + "%"); } else { System.out.println("\nverifying download...checksum don't match"); System.out.println("Deleting temporary file"); newFile.delete(); System.exit(1); } } catch (IOException ex) { System.out.println("Can't read or write, check your permissions."); System.exit(1); } }
11
Code Sample 1: private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
11
Code Sample 1: private static void readAndWriteFile(File source, File target) { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } } Code Sample 2: private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } }
00
Code Sample 1: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (destFile.getParentFile() != null && !destFile.getParentFile().mkdirs()) { LOG.error("GeneralHelper.copyFile(): Cannot create parent directories from " + destFile); } FileInputStream fIn = null; FileOutputStream fOut = null; FileChannel source = null; FileChannel destination = null; try { fIn = new FileInputStream(sourceFile); source = fIn.getChannel(); fOut = new FileOutputStream(destFile); destination = fOut.getChannel(); long transfered = 0; final long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } } finally { if (source != null) { source.close(); } else if (fIn != null) { fIn.close(); } if (destination != null) { destination.close(); } else if (fOut != null) { fOut.close(); } } } Code Sample 2: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jButton1.setEnabled(false); for (int i = 0; i < max; i++) { Card crd = WLP.getSelectedCard(WLP.jTable1.getSelectedRows()[i]); String s, s2; s = ""; s2 = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + crd.getWord()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("popWin\\('/cgi-bin/(.+?)'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); if (matcher.find()) { String newurl = "http://m-w.com/cgi-bin/" + matcher.group(1); try { URL url2 = new URL(newurl); BufferedReader in2 = new BufferedReader(new InputStreamReader(url2.openStream())); String str; while ((str = in2.readLine()) != null) { s2 = s2 + str; } in2.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern2 = Pattern.compile("<A HREF=\"http://(.+?)\">Click here to listen with your default audio player", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher2 = pattern2.matcher(s2); if (matcher2.find()) { getWave("http://" + matcher2.group(1), crd.getWord()); } int val = jProgressBar1.getValue(); val++; jProgressBar1.setValue(val); this.paintAll(this.getGraphics()); } } jButton1.setEnabled(true); }
11
Code Sample 1: private static void insertModuleInEar(File fromEar, File toEar, String moduleType, String moduleName, String contextRoot) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEar)); FileOutputStream fos = new FileOutputStream(toEar); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("META-INF/application.xml")) { content = insertModule(earFile, next, content, moduleType, moduleName, contextRoot); next = new ZipEntry("META-INF/application.xml"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); } Code Sample 2: private final void saveCopy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } to = null; from = null; }
00
Code Sample 1: @Override public void run() { if (mMode == 0) { long currentVersion = Version.extractVersion(App.getVersion()); if (currentVersion == 0) { mMode = 2; RESULT = MSG_UP_TO_DATE; return; } long versionAvailable = currentVersion; mMode = 2; try { StringBuilder buffer = new StringBuilder(mCheckURL); try { NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); if (!ni.isLoopback()) { if (ni.isUp()) { if (!ni.isVirtual()) { buffer.append('?'); byte[] macAddress = ni.getHardwareAddress(); for (byte one : macAddress) { buffer.append(Integer.toHexString(one >>> 4 & 0xF)); buffer.append(Integer.toHexString(one & 0xF)); } } } } } catch (Exception exception) { } URL url = new URL(buffer.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { StringTokenizer tokenizer = new StringTokenizer(line, "\t"); if (tokenizer.hasMoreTokens()) { try { if (tokenizer.nextToken().equalsIgnoreCase(mProductKey)) { String token = tokenizer.nextToken(); long version = Version.extractVersion(token); if (version > versionAvailable) { versionAvailable = version; } } } catch (Exception exception) { } } line = in.readLine(); } } catch (Exception exception) { } if (versionAvailable > currentVersion) { Preferences prefs = Preferences.getInstance(); String humanReadableVersion = Version.getHumanReadableVersion(versionAvailable); NEW_VERSION_AVAILABLE = true; RESULT = MessageFormat.format(MSG_OUT_OF_DATE, humanReadableVersion); if (versionAvailable > Version.extractVersion(prefs.getStringValue(MODULE, LAST_VERSION_KEY, App.getVersion()))) { prefs.setValue(MODULE, LAST_VERSION_KEY, humanReadableVersion); prefs.save(); mMode = 1; EventQueue.invokeLater(this); return; } } else { RESULT = MSG_UP_TO_DATE; } } else if (mMode == 1) { if (App.isNotificationAllowed()) { String result = getResult(); mMode = 2; if (WindowUtils.showConfirmDialog(null, result, MSG_UPDATE_TITLE, JOptionPane.OK_CANCEL_OPTION, new String[] { MSG_UPDATE_TITLE, MSG_IGNORE_TITLE }, MSG_UPDATE_TITLE) == JOptionPane.OK_OPTION) { goToUpdate(); } } else { DelayedTask.schedule(this, 250); } } } Code Sample 2: protected void doRestoreOrganizeType() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TYPE_TABLE; String strSelQuery = "SELECT organize_type_id,organize_type_name,width " + "FROM " + Common.ORGANIZE_TYPE_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_TABLE + " " + "(organize_type_id,organize_type_name,width) " + "VALUES (?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("organize_type_id")); ps.setString(2, result.getString("organize_type_name")); ps.setInt(3, result.getInt("width")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): SQLException while committing or rollback"); } }
00
Code Sample 1: @Override public CheckAvailabilityResult execute(final CheckAvailabilityAction action, final ExecutionContext context) throws ActionException { if (LOGGER.isDebugEnabled()) { String serverName = null; if (action.getServerId() == CheckAvailability.FEDORA_ID) { serverName = "fedora"; } else if (action.getServerId() == CheckAvailability.KRAMERIUS_ID) { serverName = "kramerius"; } LOGGER.debug("Processing action: CheckAvailability: " + serverName); } ServerUtils.checkExpiredSession(httpSessionProvider); boolean status = true; String url = null; String usr = ""; String pass = ""; if (action.getServerId() == CheckAvailability.FEDORA_ID) { url = configuration.getFedoraHost(); usr = configuration.getFedoraLogin(); pass = configuration.getFedoraPassword(); } else if (action.getServerId() == CheckAvailability.KRAMERIUS_ID) { url = configuration.getKrameriusHost() + SOME_STATIC_KRAMERIUS_PAGE; } else { throw new ActionException("Unknown server id"); } try { URLConnection con = RESTHelper.openConnection(url, usr, pass, false); if (con instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) con; int resp = httpConnection.getResponseCode(); if (resp < 200 || resp >= 308) { status = false; LOGGER.info("Server " + url + " answered with HTTP code " + httpConnection.getResponseCode()); } } else { status = false; } } catch (MalformedURLException e) { status = false; e.printStackTrace(); } catch (IOException e) { status = false; e.printStackTrace(); } return new CheckAvailabilityResult(status, url); } Code Sample 2: private MimeTypes() { try { final URL url = RES.getURL("types"); final InputStream is = url.openStream(); final BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = br.readLine(); while (line != null) { line = line.trim(); final int p = line.indexOf('#'); if (p >= 0) { line = line.substring(0, p).trim(); } if (line.length() > 0) { final StringTokenizer st = new StringTokenizer(line, " \t"); if (st.countTokens() > 1) { final String mime = st.nextToken(); while (st.hasMoreTokens()) { extnMap.put(st.nextToken(), mime); } } } line = br.readLine(); } br.close(); } catch (IOException e) { e.printStackTrace(); } canParse.add(TEXT_HTML); canParse.add(TEXT_CSS); }
00
Code Sample 1: public static int unzipFile(File file_input, File dir_output) { ZipInputStream zip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); zip_in_stream = new ZipInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; do { try { ZipEntry zip_entry = zip_in_stream.getNextEntry(); if (zip_entry == null) break; File output_file = new File(dir_output, zip_entry.getName()); FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = zip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } } while (true); try { zip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: @Test public void testSecondary() throws Exception { ConnectionFactoryIF cf = new DefaultConnectionFactory(PropertyUtils.loadProperties(StreamUtils.getInputStream(propfile)), false); Connection conn = cf.requestConnection(); try { Statement stm = conn.createStatement(); stm.executeUpdate("drop table if exists first"); stm.executeUpdate("drop table if exists first_changes"); stm.executeUpdate("drop table if exists second"); stm.executeUpdate("drop table if exists second_changes"); stm.executeUpdate("create table first (a integer, b varchar, c integer, d date)"); stm.executeUpdate("create table first_changes (a integer, b varchar, c integer, d date, ct varchar, cd integer)"); stm.executeUpdate("create table second (a integer, b varchar, c integer, d date)"); stm.executeUpdate("create table second_changes (a integer, b varchar, c integer, d date, ct varchar, cd integer)"); stm.executeUpdate("insert into first (a,b,c,d) values (1,'a',10, date '2007-01-01')"); stm.executeUpdate("insert into first (a,b,c,d) values (2,'b',20, date '2007-01-02')"); stm.executeUpdate("insert into first (a,b,c,d) values (3,'c',30, date '2007-01-03')"); stm.executeUpdate("insert into first (a,b,c,d) values (4,'d',40, date '2007-01-04')"); stm.executeUpdate("insert into second (a,b,c,d) values (1,'e',50, date '2007-02-01')"); stm.executeUpdate("insert into second (a,b,c,d) values (2,'f',60, date '2007-02-02')"); stm.executeUpdate("insert into second (a,b,c,d) values (3,'g',70, date '2007-02-03')"); stm.executeUpdate("insert into second (a,b,c,d) values (4,'h',80, date '2007-02-04')"); conn.commit(); RelationMapping mapping = RelationMapping.readFromClasspath("net/ontopia/topicmaps/db2tm/JDBCDataSourceTest-secondary.xml"); TopicMapStoreIF store = new InMemoryTopicMapStore(); LocatorIF baseloc = URIUtils.getURILocator("base:foo"); store.setBaseAddress(baseloc); TopicMapIF topicmap = store.getTopicMap(); Processor.addRelations(mapping, null, topicmap, baseloc); exportTopicMap(topicmap, "after-first-sync"); stm.executeUpdate("insert into second_changes (a,b,c,d,ct,cd) values (2,'f',60,date '2007-02-02', 'r', 2)"); stm.executeUpdate("delete from second where a = 2"); conn.commit(); Processor.synchronizeRelations(mapping, null, topicmap, baseloc); exportTopicMap(topicmap, "after-second-sync"); mapping.close(); stm.executeUpdate("drop table first"); stm.executeUpdate("drop table first_changes"); stm.executeUpdate("drop table second"); stm.executeUpdate("drop table second_changes"); stm.close(); store.close(); conn.commit(); } catch (Exception e) { conn.rollback(); throw e; } finally { conn.close(); } }
11
Code Sample 1: public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } Code Sample 2: private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); }
00
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: protected void doRequest(HttpServletRequest request, HttpServletResponse response, boolean inGet) throws ServletException, IOException { response.setHeader("Server", WebConsoleServlet.SERVER_STRING); try { String requestedFilename = request.getRequestURI().substring(1); URL url = new URL(getJarFileName() + "/"); JarURLConnection jarConnection = (JarURLConnection) (url.openConnection()); JarFile jarFile = jarConnection.getJarFile(); String negotiatedFilename = null; ZipEntry zipEntry = null; zipEntry = negotiateImageFile(jarFile, requestedFilename, isIE6OrEarlier(request.getHeader("User-Agent"))); if (zipEntry == null) { zipEntry = jarFile.getEntry(requestedFilename); } else { negotiatedFilename = zipEntry.getName(); } if (zipEntry == null || zipEntry.isDirectory()) { handleFileNotFound(inGet, request, response); return; } int fileSize = (int) zipEntry.getSize(); response.setContentLength(fileSize); if (negotiatedFilename != null) { response.setContentType(getContentType(negotiatedFilename)); } else { response.setContentType(getContentType(request.getRequestURI())); } InputStream in = jarFile.getInputStream(zipEntry); BufferedInputStream bufferedInputStream = new BufferedInputStream(in); byte[] file = new byte[fileSize]; int bytesRead = bufferedInputStream.read(file); bufferedInputStream.close(); if (bytesRead == fileSize && cachingEnabled) { SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z"); java.util.Date today = new java.util.Date(); String date = formatter.format(GenericUtils.addOrSubstractDaysFromDate(today, 365)); response.setHeader("Expires", date); } OutputStream outputStream = response.getOutputStream(); outputStream.write(file); } catch (FileNotFoundException e) { handleFileNotFound(inGet, request, response); } catch (IOException e) { } catch (Throwable t) { Application.getApplication().logExceptionEvent(EventLogMessage.EventType.WEB_ERROR, t); } }
11
Code Sample 1: public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath()); LOGGER.debug("Output stream: " + out.toString()); if (ServerConfiguration.isDynamicSEL()) { LOGGER.error("IS DINAMIC SEL????"); } else { } if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while downloading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } else { } } Code Sample 2: @TestTargets({ @TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies that the ObjectInputStream constructor calls checkPermission on security manager.", method = "ObjectInputStream", args = { InputStream.class }) }) public void test_ObjectInputStream2() throws IOException { class TestSecurityManager extends SecurityManager { boolean called; Permission permission; void reset() { called = false; permission = null; } @Override public void checkPermission(Permission permission) { if (permission instanceof SerializablePermission) { called = true; this.permission = permission; } } } class TestObjectInputStream extends ObjectInputStream { TestObjectInputStream(InputStream s) throws StreamCorruptedException, IOException { super(s); } } class TestObjectInputStream_readFields extends ObjectInputStream { TestObjectInputStream_readFields(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public GetField readFields() throws IOException, ClassNotFoundException, NotActiveException { return super.readFields(); } } class TestObjectInputStream_readUnshared extends ObjectInputStream { TestObjectInputStream_readUnshared(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public Object readUnshared() throws IOException, ClassNotFoundException { return super.readUnshared(); } } long id = new java.util.Date().getTime(); String filename = "SecurityPermissionsTest_" + id; File f = File.createTempFile(filename, null); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f)); oos.writeObject(new Node()); oos.flush(); oos.close(); f.deleteOnExit(); TestSecurityManager s = new TestSecurityManager(); System.setSecurityManager(s); s.reset(); new ObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream_readFields(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readFields", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); s.reset(); new TestObjectInputStream_readUnshared(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readUnshared", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); }
00
Code Sample 1: public void xtestURL2() throws Exception { URL url = new URL(IOTest.URL); InputStream inputStream = url.openStream(); OutputStream outputStream = new FileOutputStream("C:/Temp/testURL2.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } Code Sample 2: public static String genDigest(String info) { MessageDigest alga; byte[] digesta = null; try { alga = MessageDigest.getInstance("SHA-1"); alga.update(info.getBytes()); digesta = alga.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return byte2hex(digesta); }
00
Code Sample 1: public static final boolean checkForUpdate(final String currentVersion, final String updateURL, boolean noLock) throws Exception { try { final String parentFDTConfDirName = System.getProperty("user.home") + File.separator + ".fdt"; final String fdtUpdateConfFileName = "update.properties"; final File confFile = createOrGetRWFile(parentFDTConfDirName, fdtUpdateConfFileName); if (confFile != null) { long lastCheck = 0; Properties updateProperties = new Properties(); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(confFile); updateProperties.load(fis); final String lastCheckProp = (String) updateProperties.get("LastCheck"); lastCheck = 0; if (lastCheckProp != null) { try { lastCheck = Long.parseLong(lastCheckProp); } catch (Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Got exception parsing LastCheck param", t); } lastCheck = 0; } } } catch (Throwable t) { logger.log(Level.WARNING, "Cannot load update properties file: " + confFile, t); } finally { closeIgnoringExceptions(fos); closeIgnoringExceptions(fis); } final long now = System.currentTimeMillis(); boolean bHaveUpdates = false; checkAndSetInstanceID(updateProperties); if (lastCheck + FDT.UPDATE_PERIOD < now) { lastCheck = now; try { logger.log("\n\nChecking for remote updates ... This may be disabled using -noupdates flag."); bHaveUpdates = updateFDT(currentVersion, updateURL, false, noLock); if (bHaveUpdates) { logger.log("FDT may be updated using: java -jar fdt.jar -update"); } else { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "No updates available"); } } } catch (Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.WARNING, "Got exception", t); } } updateProperties.put("LastCheck", "" + now); try { fos = new FileOutputStream(confFile); updateProperties.store(fos, null); } catch (Throwable t1) { logger.log(Level.WARNING, "Cannot store update properties file", t1); } finally { closeIgnoringExceptions(fos); } return bHaveUpdates; } } else { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, " [ checkForUpdate ] Cannot read or write the update conf file: " + parentFDTConfDirName + File.separator + fdtUpdateConfFileName); } return false; } } catch (Throwable t) { logger.log(Level.WARNING, "Got exception checking for updates", t); } return false; } Code Sample 2: public static String getUserToken(String userName) { if (userName != null && userName.trim().length() > 0) try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update((userName + seed).getBytes("ISO-8859-1")); return BaseController.bytesToHex(md.digest()); } catch (NullPointerException npe) { } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } return null; }
11
Code Sample 1: public static void main(String args[]) throws Exception { File file = new File("D:/work/love.txt"); @SuppressWarnings("unused") ZipFile zipFile = new ZipFile("D:/work/test1.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("D:/work/test1.zip")); zos.setEncoding("GBK"); ZipEntry entry = null; if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); int readLen = 0; byte[] buf = new byte[2048]; if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 2048)) != -1) { zos.write(buf, 0, readLen); } in.close(); } zos.close(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: @Override public void sendData(String serverUrl, String fileName, String type, InputStream is) throws IOException { ClientSession clientSession = null; try { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + serverUrl); } clientSession = (ClientSession) Connector.open(serverUrl); HeaderSet hsConnectReply = clientSession.connect(clientSession.createHeaderSet()); if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Connect Error " + hsConnectReply.getResponseCode()); } HeaderSet hsOperation = clientSession.createHeaderSet(); hsOperation.setHeader(HeaderSet.NAME, fileName); if (type != null) { hsOperation.setHeader(HeaderSet.TYPE, type); } hsOperation.setHeader(HeaderSet.LENGTH, new Long(is.available())); Operation po = clientSession.put(hsOperation); OutputStream os = po.openOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); if (logger.isDebugEnabled()) { logger.debug("put responseCode " + po.getResponseCode()); } po.close(); HeaderSet hsDisconnect = clientSession.disconnect(null); if (logger.isDebugEnabled()) { logger.debug("disconnect responseCode " + hsDisconnect.getResponseCode()); } if (hsDisconnect.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Send Error " + hsConnectReply.getResponseCode()); } } finally { if (clientSession != null) { try { clientSession.close(); } catch (IOException ignore) { if (logger.isDebugEnabled()) { logger.debug("IOException during clientSession.close()", ignore); } } } clientSession = null; } } Code Sample 2: private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
11
Code Sample 1: @Override public byte[] read(String path) throws PersistenceException { path = fmtPath(path); try { S3Object fileObj = s3Service.getObject(bucketObj, path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(fileObj.getDataInputStream(), out); return out.toByteArray(); } catch (Exception e) { throw new PersistenceException("fail to read s3 file - " + path, e); } } Code Sample 2: PackageFileImpl(PackageDirectoryImpl dir, String name, InputStream data) throws IOException { this.dir = dir; this.name = name; this.updates = dir.getUpdates(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IOUtils.copy(data, stream); updates.setNewData(getFullName(), stream.toByteArray()); stream.close(); }
00
Code Sample 1: public void testManageSources() throws Exception { this.getTestTool().manageSources(this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getModule("Module"), this.getTestSourcesDirectory()); final File implementationDirectory = this.getTestSourcesDirectory(); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); final File specificationDirectory = this.getTestSourcesDirectory(); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("IllegalImplementationSource.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); IOUtils.copy(this.getClass().getResourceAsStream("IllegalSpecificationSource.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); try { this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); Assert.fail("Expected IOException not thrown."); } catch (IOException e) { Assert.assertNotNull(e.getMessage()); System.out.println(e.toString()); } try { this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); Assert.fail("Expected IOException not thrown."); } catch (IOException e) { Assert.assertNotNull(e.getMessage()); System.out.println(e.toString()); } this.getTestTool().setProfile("DOES_NOT_EXIST"); this.getTestTool().manageSources(this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getModule("Module"), this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), this.getTestSourcesDirectory()); } Code Sample 2: @Override public void setOntology2Document(URL url2) throws IllegalArgumentException { if (url2 == null) throw new IllegalArgumentException("Input parameter URL for ontology 2 is null."); try { ont2 = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(url2.openStream()); } catch (IOException e) { throw new IllegalArgumentException("Cannot open stream for ontology 2 from given URL."); } catch (OWLOntologyCreationException e) { throw new IllegalArgumentException("Cannot load ontology 2 from given URL."); } }
11
Code Sample 1: private void recvMessage(String from, String to) throws Exception { ConnectionFactoryImpl factory = new ConnectionFactoryImpl(); Receiver receiver = null; ProviderConnection connection = factory.createConnection(from, to); Connection conn = DBUtil.getConnection(); PreparedStatement pstmt = null; ResultSet rs = null; String sql = ""; try { receiver = Receiver.createReceiver(connection); receiver.open(); EXTSSPMessage message = (EXTSSPMessage) receiver.receiveEX(); if (message == null) { System.out.println("no message"); } else { conn.setAutoCommit(false); EXTSSPHeader header = message.getEXHeader(); UUIDHexGenerator u = new UUIDHexGenerator(); String id = u.generate().toString(); pstmt = conn.prepareStatement(drawOutRecvSql(header, id)); pstmt.executeUpdate(); String xml = ""; TSSPBody body = message.getBody(); xml = body.getDomAsString(); xml = xml.replaceAll("ns1:", ""); saveClobMessage(pstmt, conn, rs, xml, id); String notify_id = ""; Iterator iter = message.getAttachments(); while (iter.hasNext()) { AttachmentPart a = (AttachmentPart) iter.next(); String contentId = a.getContentId(); if (contentId.startsWith(Constant.PREFIX_PERSON)) { DataHandler dh = a.getDataHandler(); InputStream is = dh.getInputStream(); byte[] temp = FileCopyUtils.copyToByteArray(is); String content = new String(temp); RecvDto recv = (RecvDto) XStreamConvert.xmlToBean(content); if (recv == null) throw new Exception("接收方信息对象转换错误!请检查存入的信息对象xml字符串是否正确:" + content); if (notify_id.equals("")) { notify_id = u.generate().toString(); header.setType(Constant.MESSAGETYPE_NOTIFY); pstmt = conn.prepareStatement(drawOutRecvSql(header, notify_id)); pstmt.executeUpdate(); String notify_content = header.getNotifyContent(); if (notify_content == null) notify_content = "接收到新的esb消息,但未定义通知消息内容!"; saveClobMessage(pstmt, conn, rs, notify_content, notify_id); } savePersonInfo(pstmt, conn, recv, notify_id); } else { DataHandler dh = a.getDataHandler(); InputStream is = dh.getInputStream(); String attid = u.generate().toString(); sql = "insert into message_recv_attachment(ATTACHMENTID," + "VERSION,MRECVID,BUSS_ID,ATTACHMENT) values('" + attid + "',0,'" + id + "','" + contentId + "',empty_blob())"; pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); sql = "select attachment from message_recv_attachment" + " where attachmentid = '" + attid + "' for update"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); rs.next(); Blob blob = rs.getBlob(1); OutputStream blobOutputStream = ((oracle.sql.BLOB) blob).getBinaryOutputStream(); FileCopyUtils.copy(is, blobOutputStream); is.close(); blobOutputStream.close(); } } conn.commit(); conn.setAutoCommit(true); } receiver.commit(); } catch (Exception e) { e.printStackTrace(); try { System.out.println("received message, rollback"); if (receiver != null) { receiver.rollback(); } } catch (JAXMException e1) { e1.printStackTrace(); } } finally { DBUtil.close(rs, pstmt, conn); if (receiver != null) { try { receiver.close(); } catch (JAXMException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (JAXMException e) { e.printStackTrace(); } } } } Code Sample 2: public void insertArchiveEntries(ArchiveEntry entries[]) throws WeatherMonitorException { String sql = null; try { Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rslt = null; con.setAutoCommit(false); for (int i = 0; i < entries.length; i++) { if (!sanityCheck(entries[i])) { } else { sql = getSelectSql(entries[i]); rslt = stmt.executeQuery(sql); if (rslt.next()) { if (rslt.getInt(1) == 0) { sql = getInsertSql(entries[i]); if (stmt.executeUpdate(sql) != 1) { con.rollback(); System.out.println("rolling back sql"); throw new WeatherMonitorException("exception on insert"); } } } } } con.commit(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new WeatherMonitorException(e.getMessage()); } }
11
Code Sample 1: private void readAnnotations() throws IOException { final BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); try { String line = null; while ((line = in.readLine()) != null) { lineNumber++; if (line.startsWith("ANNOTATE")) { readAnnotationBlock(in); } } } catch (IOException e) { throw e; } finally { in.close(); } } Code Sample 2: public void handler(List<GoldenBoot> gbs, TargetPage target) { try { URL url = new URL(target.getUrl()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; String include = "Top Scorers"; while ((line = reader.readLine()) != null) { if (line.indexOf(include) != -1) { buildGildenBoot(line, gbs); break; } } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
11
Code Sample 1: public static String get(String strUrl) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(true); conn.setAllowUserInteraction(true); conn.setFollowRedirects(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-Agent:", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; de-de) AppleWebKit/523.12.2 (KHTML, like Gecko) Version/3.0.4 Safari/523.12.2"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += '\n' + s; } return sRet; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } Code Sample 2: private String getXml(String url) throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); String results = null; if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { results = EntityUtils.toString(entity); } else { } } return (results); }
00
Code Sample 1: public byte[] downloadAttachmentContent(Attachment issueAttachment) throws IOException { byte[] result = null; URL url = new URL(issueAttachment.getContentURL()); BufferedReader inputReader = null; try { inputReader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder contentBuilder = new StringBuilder(); String line; while ((line = inputReader.readLine()) != null) { contentBuilder.append(line); } result = contentBuilder.toString().getBytes(); } finally { if (inputReader != null) { inputReader.close(); } } return result; } Code Sample 2: public static String doPost(String url, Map mapa) { try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = getParams(mapa); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpresponse = httpclient.execute(httpPost); HttpEntity httpentity = httpresponse.getEntity(); if (httpentity != null) { InputStream is = httpentity.getContent(); return Funcoes.readString(is); } } catch (IOException e) { Log.e("HttpClientImpl.doPost", e.getMessage()); } return url; }
00
Code Sample 1: private static byte[] createHash(EHashType hashType, String string) { MessageDigest md; try { md = MessageDigest.getInstance(hashType.getJavaHashType()); md.reset(); md.update(string.getBytes()); byte[] byteResult = md.digest(); return byteResult; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } Code Sample 2: public void sort(int[] order, double[] values) { int temp = 0; boolean done = false; for (int i = 0; i < values.length; i++) { order[i] = i; } if (desendingValues) { while (!done) { done = true; for (int i = values.length - 2; i >= 0; i--) { if (values[order[i]] < values[order[i + 1]]) { done = false; temp = order[i]; order[i] = order[i + 1]; order[i + 1] = temp; } } } } else { while (!done) { done = true; for (int i = values.length - 2; i >= 0; i--) { if (values[order[i]] > values[order[i + 1]]) { done = false; temp = order[i]; order[i] = order[i + 1]; order[i + 1] = temp; } } } } }
00
Code Sample 1: private static void fileUpload() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:\\Rock Lee.jpg"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("file", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into bayfiles.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } System.out.println("Upload response : " + uploadresponse); downloadlink = parseResponse(uploadresponse, "\"downloadUrl\":\"", "\""); downloadlink = downloadlink.replaceAll("\\\\", ""); deletelink = parseResponse(uploadresponse, "\"deleteUrl\":\"", "\""); deletelink = deletelink.replaceAll("\\\\", ""); System.out.println("Download link : " + downloadlink); System.out.println("Delete link : " + deletelink); } Code Sample 2: public static void copyFile(String from, String to, boolean append) throws IOException { FileChannel in = new FileInputStream(from).getChannel(); FileChannel out = new FileOutputStream(to, append).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(BSIZE); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } }
11
Code Sample 1: public static void appendFile(String namePrefix, File baseDir, File file, ZipOutputStream zipOut) throws IOException { Assert.Arg.notNull(baseDir, "baseDir"); Assert.Arg.notNull(file, "file"); Assert.Arg.notNull(zipOut, "zipOut"); if (namePrefix == null) namePrefix = ""; String path = FileSystemUtils.getRelativePath(baseDir, file); ZipEntry zipEntry = new ZipEntry(namePrefix + path); zipOut.putNextEntry(zipEntry); InputStream fileInput = FileUtils.openInputStream(file); try { org.apache.commons.io.IOUtils.copyLarge(fileInput, zipOut); } finally { fileInput.close(); } } Code Sample 2: public static void copyResourceFileTo(String destFileName, String resourceFileName) { if (destFileName == null || resourceFileName == null) throw new IllegalArgumentException("Argument cannot be null."); try { FileInputStream in = null; FileOutputStream out = null; URL url = HelperMethods.class.getResource(resourceFileName); if (url == null) { System.out.println("URL " + resourceFileName + " cannot be created."); return; } String fileName = url.getFile(); fileName = fileName.replaceAll("%20", " "); File resourceFile = new File(fileName); if (!resourceFile.isFile()) { System.out.println(fileName + " cannot be opened."); return; } in = new FileInputStream(resourceFile); out = new FileOutputStream(new File(destFileName)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ex) { ex.printStackTrace(); } }
00
Code Sample 1: public static JSONObject delete(String uid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(DELETE_URI + "?uid=" + uid); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); return new JSONObject(res); } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); } Code Sample 2: public boolean actualizarEstadoDivision(division div) { int intResult = 0; String sql = "UPDATE divisionxTorneo " + " SET terminado = '1' " + " WHERE idDivisionxTorneo = " + div.getidDivision(); try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); }
11
Code Sample 1: public static BufferedReader getUserInfoStream(String name) throws IOException { BufferedReader in; try { URL url = new URL("http://www.spoj.pl/users/" + name.toLowerCase() + "/"); in = new BufferedReader(new InputStreamReader(url.openStream())); } catch (MalformedURLException e) { in = null; throw e; } return in; } Code Sample 2: @SuppressWarnings("unchecked") private List<String> getWordList() { IConfiguration config = Configurator.getDefaultConfigurator().getConfig(CONFIG_ID); List<String> wList = (List<String>) config.getObject("word_list"); if (wList == null) { wList = new ArrayList<String>(); InputStream resrc = null; try { resrc = new URL(list_url).openStream(); } catch (Exception e) { e.printStackTrace(); } if (resrc != null) { BufferedReader br = new BufferedReader(new InputStreamReader(resrc)); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() != 0) { wList.add(line); } } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } } } return wList; }
00
Code Sample 1: protected boolean exists(String filename) { try { URL url = new URL(base, filename); URLConnection conn = url.openConnection(); conn.connect(); conn.getInputStream().close(); return true; } catch (IOException ex) { return false; } } Code Sample 2: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
00
Code Sample 1: static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } } Code Sample 2: private void readFromStorableInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); StorableInput input = new StorableInput(stream); fDrawing.release(); fDrawing = (Drawing) input.readStorable(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error:" + e); } }
11
Code Sample 1: public Controller(String m_hostname, String team, boolean m_shouldexit) throws InternalException { m_received_messages = new ConcurrentLinkedQueue<ReceivedMessage>(); m_fragmsgs = new ArrayList<String>(); m_customizedtaunts = new HashMap<Integer, String>(); m_nethandler = new CachingNetHandler(); m_drawingpanel = GLDrawableFactory.getFactory().createGLCanvas(new GLCapabilities()); m_user = System.getProperty("user.name"); m_chatbuffer = new StringBuffer(); this.m_shouldexit = m_shouldexit; isChatPaused = false; isRunning = true; m_lastbullet = 0; try { BufferedReader in = new BufferedReader(new FileReader(HogsConstants.FRAGMSGS_FILE)); String str; while ((str = in.readLine()) != null) { m_fragmsgs.add(str); } in.close(); } catch (IOException e) { e.printStackTrace(); } String newFile = PathFinder.getCustsFile(); boolean exists = (new File(newFile)).exists(); Reader reader = null; if (exists) { try { reader = new FileReader(newFile); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } else { Object[] options = { "Yes, create a .hogsrc file", "No, use default taunts" }; int n = JOptionPane.showOptionDialog(m_window, "You do not have customized taunts in your home\n " + "directory. Would you like to create a customizable file?", "Hogs Customization", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (n == 0) { try { FileChannel srcChannel = new FileInputStream(HogsConstants.CUSTS_TEMPLATE).getChannel(); FileChannel dstChannel; dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); reader = new FileReader(newFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { try { reader = new FileReader(HogsConstants.CUSTS_TEMPLATE); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } } try { m_netengine = NetEngine.forHost(m_user, m_hostname, 1820, m_nethandler); m_netengine.start(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (NetException e) { e.printStackTrace(); } m_gamestate = m_netengine.getCurrentState(); m_gamestate.setInChatMode(false); m_gamestate.setController(this); try { readFromFile(reader); } catch (NumberFormatException e3) { e3.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } catch (InternalException e3) { e3.printStackTrace(); } GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice m_graphicsdevice = ge.getDefaultScreenDevice(); m_window = new GuiFrame(m_drawingpanel, m_gamestate); m_graphics = null; try { m_graphics = new GraphicsEngine(m_drawingpanel, m_gamestate); } catch (InternalException e1) { e1.printStackTrace(); System.exit(0); } m_drawingpanel.addGLEventListener(m_graphics); m_physics = new Physics(); if (team == null) { team = HogsConstants.TEAM_NONE; } if (!(team.toLowerCase().equals(HogsConstants.TEAM_NONE) || team.toLowerCase().equals(HogsConstants.TEAM_RED) || team.toLowerCase().equals(HogsConstants.TEAM_BLUE))) { throw new InternalException("Invalid team name!"); } String orig_team = team; Craft local_craft = m_gamestate.getLocalCraft(); if (m_gamestate.getNumCrafts() == 0) { local_craft.setTeamname(team); } else if (m_gamestate.isInTeamMode()) { if (team == HogsConstants.TEAM_NONE) { int red_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_RED); int blue_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_BLUE); String new_team; if (red_craft > blue_craft) { new_team = HogsConstants.TEAM_BLUE; } else if (red_craft < blue_craft) { new_team = HogsConstants.TEAM_RED; } else { new_team = Math.random() > 0.5 ? HogsConstants.TEAM_BLUE : HogsConstants.TEAM_RED; } m_gamestate.getLocalCraft().setTeamname(new_team); } else { local_craft.setTeamname(team); } } else { local_craft.setTeamname(HogsConstants.TEAM_NONE); if (orig_team != null) { m_window.displayText("You cannot join a team, this is an individual game."); } } if (!local_craft.getTeamname().equals(HogsConstants.TEAM_NONE)) { m_window.displayText("You are joining the " + local_craft.getTeamname() + " team."); } m_drawingpanel.setSize(m_drawingpanel.getWidth(), m_drawingpanel.getHeight()); m_middlepos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); m_curpos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); GuiKeyListener k_listener = new GuiKeyListener(); GuiMouseListener m_listener = new GuiMouseListener(); m_window.addKeyListener(k_listener); m_drawingpanel.addKeyListener(k_listener); m_window.addMouseListener(m_listener); m_drawingpanel.addMouseListener(m_listener); m_window.addMouseMotionListener(m_listener); m_drawingpanel.addMouseMotionListener(m_listener); m_drawingpanel.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.requestFocus(); } Code Sample 2: public static boolean copy(File source, File dest) { 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); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
00
Code Sample 1: @Test public void shouldSetAlias() throws Exception { HttpResponse response = executePost("/yum/alias/snapshots/testAlias", new StringEntity(VERSION_1)); assertEquals(VERSION_1, EntityUtils.toString(response.getEntity())); assertEquals(VERSION_1, executeGet("/yum/alias/snapshots/testAlias")); response = executePost("/yum/alias/snapshots/testAlias", new StringEntity(VERSION_2)); assertEquals(VERSION_2, EntityUtils.toString(response.getEntity())); assertEquals(VERSION_2, executeGet("/yum/alias/snapshots/testAlias")); } Code Sample 2: private static InputSource getInputSourceFromURI(String uri, String username, String password) throws IOException, ProtocolException, UnsupportedEncodingException { URL wsdlurl = null; try { wsdlurl = new URL(uri); } catch (MalformedURLException e) { return new InputSource(uri); } if (username == null && wsdlurl.getUserInfo() == null) { return new InputSource(uri); } if (!wsdlurl.getProtocol().startsWith("http")) { return new InputSource(uri); } URLConnection connection = wsdlurl.openConnection(); if (!(connection instanceof HttpURLConnection)) { return new InputSource(uri); } HttpURLConnection uconn = (HttpURLConnection) connection; String userinfo = wsdlurl.getUserInfo(); uconn.setRequestMethod("GET"); uconn.setAllowUserInteraction(false); uconn.setDefaultUseCaches(false); uconn.setDoInput(true); uconn.setDoOutput(false); uconn.setInstanceFollowRedirects(true); uconn.setUseCaches(false); String auth = null; if (userinfo != null) { auth = userinfo; } else if (username != null) { auth = (password == null) ? username : username + ":" + password; } if (auth != null) { uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(httpAuthCharEncoding))); } uconn.connect(); return new InputSource(uconn.getInputStream()); }
11
Code Sample 1: public void notifyIterationEnds(final IterationEndsEvent event) { log.info("moving files..."); File source = new File("deqsim.log"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log to its iteration directory."); } } int parallelCnt = 0; source = new File("deqsim.log." + parallelCnt); while (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log." + parallelCnt)); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log." + parallelCnt + " to its iteration directory."); } parallelCnt++; source = new File("deqsim.log." + parallelCnt); } source = new File("loads_out.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("loads_out.txt")); try { IOUtils.copyFile(source, destination); } catch (FileNotFoundException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } catch (IOException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } destination = new File("loads_in.txt"); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move loads_out.txt to loads_in.txt."); } } source = new File("linkprocs.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("linkprocs.txt")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move linkprocs.txt to its iteration directory."); } } } Code Sample 2: public void writeTo(File f) throws IOException { if (state != STATE_OK) throw new IllegalStateException("Upload failed"); if (tempLocation == null) throw new IllegalStateException("File already saved"); if (f.isDirectory()) f = new File(f, filename); FileInputStream fis = new FileInputStream(tempLocation); FileOutputStream fos = new FileOutputStream(f); byte[] buf = new byte[BUFFER_SIZE]; try { int i = 0; while ((i = fis.read(buf)) != -1) fos.write(buf, 0, i); } finally { deleteTemporaryFile(); fis.close(); fos.close(); } }
00
Code Sample 1: @RequestMapping("/download") public void download(HttpServletRequest request, HttpServletResponse response) { InputStream input = null; ServletOutputStream output = null; try { String savePath = request.getSession().getServletContext().getRealPath("/upload"); String fileType = ".log"; String dbFileName = "83tomcat日志测试哦"; String downloadFileName = dbFileName + fileType; String finalPath = "\\2011-12\\01\\8364b45f-244d-41b6-bbf48df32064a935"; downloadFileName = new String(downloadFileName.getBytes("GBK"), "ISO-8859-1"); File downloadFile = new File(savePath + finalPath); if (!downloadFile.getParentFile().exists()) { downloadFile.getParentFile().mkdirs(); } if (!downloadFile.isFile()) { FileUtils.touch(downloadFile); } response.setContentType("aapplication/vnd.ms-excel ;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("content-disposition", "attachment; filename=" + downloadFileName); input = new FileInputStream(downloadFile); output = response.getOutputStream(); IOUtils.copy(input, output); output.flush(); } catch (Exception e) { logger.error("Exception: ", e); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } } Code Sample 2: public static void processString(String text) throws Exception { MessageDigest md5 = MessageDigest.getInstance(MD5_DIGEST); md5.reset(); md5.update(text.getBytes()); displayResult(null, md5.digest()); }
00
Code Sample 1: public static String hash(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes()); byte[] digest = md.digest(); StringBuffer sb = new StringBuffer(digest.length * 2); for (int i = 0; i < digest.length; ++i) { byte b = digest[i]; int high = (b & 0xF0) >> 4; int low = b & 0xF; sb.append(DECIMAL_HEX[high]); sb.append(DECIMAL_HEX[low]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { throw new NonBusinessException("Error hashing string", e); } } Code Sample 2: public List<String> query(String query) throws IOException { List<String> list = new LinkedList<String>(); query = URLEncoder.encode(query, "UTF-8"); String queryurl = baseurl + "?type=tuples&lang=itql&format=csv&query=" + query; URL url = new URL(queryurl); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = reader.readLine(); while (line != null) { list.add(line); line = reader.readLine(); } reader.close(); return list; }
00
Code Sample 1: private static String deviceIdFromCombined_Device_ID(Context context) { StringBuilder builder = new StringBuilder(); builder.append(deviceIdFromIMEI(context)); builder.append(deviceIdFromPseudo_Unique_Id()); builder.append(deviceIdFromAndroidId(context)); builder.append(deviceIdFromWLAN_MAC_Address(context)); builder.append(deviceIdFromBT_MAC_Address(context)); String m_szLongID = builder.toString(); MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(m_szLongID.getBytes(), 0, m_szLongID.length()); byte p_md5Data[] = m.digest(); String m_szUniqueID = new String(); for (int i = 0; i < p_md5Data.length; i++) { int b = (0xFF & p_md5Data[i]); if (b <= 0xF) m_szUniqueID += "0"; m_szUniqueID += Integer.toHexString(b); } return m_szUniqueID; } Code Sample 2: public void process(String number) { try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Constants.TRAIN_INFO_URL.value()); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair(Constants.TRAIN_NUMBER_POST_PARAM_NAME.value(), number)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httpPost); InputStream is = response.getEntity().getContent(); Document doc = getDocument(is); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(Constants.XPATH_TRAIN_STOPS_INFO.value()); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; List<String> list = new ArrayList<String>(); for (int i = 0; i < nodes.getLength(); i++) { list.add(nodes.item(i).getNodeValue()); } parse(list); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } }
00
Code Sample 1: private void setup() { env = new EnvAdvanced(); try { URL url = Sysutil.getURL("world.env"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { String[] fields = line.split(","); if (fields[0].equalsIgnoreCase("skybox")) { env.setRoom(new EnvSkyRoom(fields[1])); } else if (fields[0].equalsIgnoreCase("camera")) { env.setCameraXYZ(Double.parseDouble(fields[1]), Double.parseDouble(fields[2]), Double.parseDouble(fields[3])); env.setCameraYaw(Double.parseDouble(fields[4])); env.setCameraPitch(Double.parseDouble(fields[5])); } else if (fields[0].equalsIgnoreCase("terrain")) { terrain = new EnvTerrain(fields[1]); terrain.setTexture(fields[2]); env.addObject(terrain); } else if (fields[0].equalsIgnoreCase("object")) { GameObject n = (GameObject) Class.forName(fields[10]).newInstance(); n.setX(Double.parseDouble(fields[1])); n.setY(Double.parseDouble(fields[2])); n.setZ(Double.parseDouble(fields[3])); n.setScale(Double.parseDouble(fields[4])); n.setRotateX(Double.parseDouble(fields[5])); n.setRotateY(Double.parseDouble(fields[6])); n.setRotateZ(Double.parseDouble(fields[7])); n.setTexture(fields[9]); n.setModel(fields[8]); n.setEnv(env); env.addObject(n); } } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static boolean verify(final String password, final 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 (final 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 (final 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 (final 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 (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } final byte[] data = Base64.decode(base64.toCharArray()); final 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); }
00
Code Sample 1: public void delete(Channel channel) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); String[] selfDefinePath = getSelfDefinePath(channel.getPath(), "1", connection, preparedStatement, resultSet); selfDefineDelete(selfDefinePath, connection, preparedStatement); String sqlStr = "delete from t_ip_channel where channel_path=?"; preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); sqlStr = "delete from t_ip_channel_order where channel_order_site = ?"; preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException ex) { connection.rollback(); log.error("ɾ��Ƶ��ʧ�ܣ�channelPath=" + channel.getPath(), ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } } Code Sample 2: public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) res += "0" + tmp; else res += tmp; } } catch (NoSuchAlgorithmException ex) { } return res; }
00
Code Sample 1: public void SetRoles(Connection conn, User user, String[] roles) throws NpsException { if (!IsSysAdmin() && !IsLocalAdmin()) throw new NpsException(ErrorHelper.ACCESS_NOPRIVILEGE); PreparedStatement pstmt = null; ResultSet rs = null; try { String sql = "delete from userrole where userid=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.id); pstmt.executeUpdate(); if (roles != null && roles.length > 0) { try { pstmt.close(); } catch (Exception e1) { } sql = "insert into userrole(userid,roleid) values(?,?)"; pstmt = conn.prepareStatement(sql); for (int i = 0; i < roles.length; i++) { if (roles[i] != null && roles[i].length() > 0) { pstmt.setString(1, user.GetId()); pstmt.setString(2, roles[i]); pstmt.executeUpdate(); } } } try { pstmt.close(); } catch (Exception e1) { } if (user.roles_by_name != null) user.roles_by_name.clear(); if (user.roles_by_id != null) user.roles_by_id.clear(); if (roles != null && roles.length > 0) { sql = "select b.* from UserRole a,Role b where a.roleid = b.id and a.userid=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.id); rs = pstmt.executeQuery(); while (rs.next()) { if (user.roles_by_name == null) user.roles_by_name = new Hashtable(); if (user.roles_by_id == null) user.roles_by_id = new Hashtable(); user.roles_by_name.put(rs.getString("name"), rs.getString("id")); user.roles_by_id.put(rs.getString("id"), rs.getString("name")); } } } catch (Exception e) { try { conn.rollback(); } catch (Exception e1) { } com.microfly.util.DefaultLog.error(e); } finally { if (rs != null) try { rs.close(); } catch (Exception e) { } if (pstmt != null) try { pstmt.close(); } catch (Exception e1) { } } } Code Sample 2: @Override public String compute_hash(String plaintext) { MessageDigest d; try { d = MessageDigest.getInstance(get_algorithm_name()); d.update(plaintext.getBytes()); byte[] hash = d.digest(); StringBuffer sb = new StringBuffer(); for (byte b : hash) sb.append(String.format("%02x", b)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
11
Code Sample 1: private static void prepare() { System.err.println("PREPARING-----------------------------------------"); deleteHome(); InputStream configStream = null; FileOutputStream tempStream = null; try { configStream = AllTests.class.getClassLoader().getResourceAsStream("net/sf/archimede/test/resources/repository.xml"); new File("temp").mkdir(); tempStream = new FileOutputStream(new File("temp/repository.xml")); IOUtils.copy(configStream, tempStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (configStream != null) { configStream.close(); } } catch (IOException e) { e.printStackTrace(); } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } String repositoryName = "jackrabbit.repository"; Properties jndiProperties = new Properties(); jndiProperties.put("java.naming.provider.url", "http://sf.net/projects/archimede#1"); jndiProperties.put("java.naming.factory.initial", "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory"); startupUtil = new StartupJcrUtil(REPOSITORY_HOME, "temp/repository.xml", repositoryName, jndiProperties); startupUtil.init(); } Code Sample 2: public static void copyDirectory(File sourceDirectory, File targetDirectory) throws IOException { File[] sourceFiles = sourceDirectory.listFiles(FILE_FILTER); File[] sourceDirectories = sourceDirectory.listFiles(DIRECTORY_FILTER); targetDirectory.mkdirs(); if (sourceFiles != null && sourceFiles.length > 0) { for (int i = 0; i < sourceFiles.length; i++) { File sourceFile = sourceFiles[i]; FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetDirectory + File.separator + sourceFile.getName()); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(8192); long size = fcin.size(); long n = 0; while (n < size) { buf.clear(); if (fcin.read(buf) < 0) { break; } buf.flip(); n += fcout.write(buf); } fcin.close(); fcout.close(); fis.close(); fos.close(); } } if (sourceDirectories != null && sourceDirectories.length > 0) { for (int i = 0; i < sourceDirectories.length; i++) { File directory = sourceDirectories[i]; File newTargetDirectory = new File(targetDirectory, directory.getName()); copyDirectory(directory, newTargetDirectory); } } }
11
Code Sample 1: public static void copyFile(File src, String srcEncoding, File dest, String destEncoding) throws IOException { InputStreamReader in = new InputStreamReader(new FileInputStream(src), srcEncoding); OutputStreamWriter out = new OutputStreamWriter(new RobustFileOutputStream(dest), destEncoding); int c; while ((c = in.read()) != -1) out.write(c); out.flush(); in.close(); out.close(); } Code Sample 2: private static void copy(String sourceName, String destName) throws IOException { File source = new File(sourceName); File dest = new File(destName); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
Code Sample 1: public static String getHashedStringMD5(String value) throws java.security.NoSuchAlgorithmException { java.security.MessageDigest d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(value.getBytes()); byte[] buf = d.digest(); return new String(buf); } Code Sample 2: public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwdInDb = hexStringToByte(passwordInDb); byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); if (Arrays.equals(digest, digestInDb)) { return true; } else { return false; } }
00
Code Sample 1: public ProgramProfilingSymbol updateProgramProfilingSymbol(int id, int configID, int programSymbolID) throws AdaptationException { ProgramProfilingSymbol pps = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "UPDATE ProgramProfilingSymbols SET " + "projectDeploymentConfigurationID = " + configID + ", " + "programSymbolID = " + programSymbolID + ", " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from ProgramProfilingSymbols WHERE " + "id = " + id; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to update program profiling " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } pps = getProfilingSymbol(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in updateProgramProfilingSymbol"; 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 pps; } Code Sample 2: public void retrieveChallenge() throws MalformedURLException, IOException, FBConnectionException, FBErrorException { URL url = new URL(getHost() + getPath()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("X-FB-User", getUser()); conn.setRequestProperty("X-FB-Mode", "GetChallenge"); conn.connect(); Element fbresponse; try { fbresponse = readXML(conn); } catch (FBConnectionException fbce) { error = true; throw fbce; } catch (FBErrorException fbee) { error = true; throw fbee; } catch (Exception e) { error = true; FBConnectionException fbce = new FBConnectionException("XML parsing failed"); fbce.attachSubException(e); throw fbce; } NodeList nl = fbresponse.getElementsByTagName("GetChallengeResponse"); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element && hasError((Element) nl.item(i))) { error = true; FBErrorException e = new FBErrorException(); e.setErrorCode(errorcode); e.setErrorText(errortext); throw e; } } NodeList challenge = fbresponse.getElementsByTagName("Challenge"); for (int i = 0; i < challenge.getLength(); i++) { NodeList children = challenge.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (children.item(j) instanceof Text) { challenges.offer(children.item(j).getNodeValue()); } } } }
11
Code Sample 1: public Object read(InputStream inputStream, Map metadata) throws IOException, ClassNotFoundException { if (log.isTraceEnabled()) log.trace("Read input stream with metadata=" + metadata); Integer resCode = (Integer) metadata.get(HTTPMetadataConstants.RESPONSE_CODE); String resMessage = (String) metadata.get(HTTPMetadataConstants.RESPONSE_CODE_MESSAGE); if (resCode != null && validResponseCodes.contains(resCode) == false) throw new RuntimeException("Invalid HTTP server response [" + resCode + "] - " + resMessage); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); String soapMessage = new String(baos.toByteArray(), charsetEncoding); if (isTraceEnabled) { String prettySoapMessage = DOMWriter.printNode(DOMUtils.parse(soapMessage), true); log.trace("Incoming Response SOAPMessage\n" + prettySoapMessage); } return soapMessage; } Code Sample 2: public static File copy(String inFileName, String outFileName) throws IOException { File inputFile = new File(inFileName); File outputFile = new File(outFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return outputFile; }
00
Code Sample 1: public void copyServer(int id) throws Exception { File in = new File("servers" + File.separatorChar + "server_" + id); File serversDir = new File("servers" + File.separatorChar); int newNumber = serversDir.listFiles().length + 1; System.out.println("New File Number: " + newNumber); File out = new File("servers" + File.separatorChar + "server_" + newNumber); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (Exception e) { e.printStackTrace(); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } getServer(newNumber - 1); } Code Sample 2: @Override public int deleteStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); int result = statement.executeUpdate(sql.toString()); if (result == 0) log.warn(sql + " result row count is 0"); getConnection().commit(); return result; } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); throw new RuntimeException(); } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
00
Code Sample 1: public void copy(File source, File dest) throws IOException { System.out.println("copy " + source + " -> " + dest); FileInputStream in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { out.close(); } } finally { in.close(); } } Code Sample 2: public void write(URL output, String model, String mainResourceClass) throws InfoUnitIOException { InfoUnitXMLData iur = new InfoUnitXMLData(STRUCTURE_RDF); rdf = iur.load("rdf"); rdfResource = rdf.ft("resource"); rdfParseType = rdf.ft("parse type"); try { PrintWriter outw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(output.getFile()), "UTF-8")); URL urlModel = new URL(model); BufferedReader inr = new BufferedReader(new InputStreamReader(urlModel.openStream())); String finalTag = "</" + rdf.ft("main") + ">"; String line = inr.readLine(); while (line != null && !line.equalsIgnoreCase(finalTag)) { outw.println(line); line = inr.readLine(); } inr.close(); InfoNode nodeType = infoRoot.path(rdf.ft("constraint")); String type = null; if (nodeType != null) { type = nodeType.getValue().toString(); try { infoRoot.removeChildNode(nodeType); } catch (InvalidChildInfoNode error) { } } else if (mainResourceClass != null) type = mainResourceClass; else type = rdf.ft("description"); outw.println(" <" + type + " " + rdf.ft("about") + "=\"" + ((infoNamespaces == null) ? infoRoot.getLabel() : infoNamespaces.convertEntity(infoRoot.getLabel().toString())) + "\">"); Set<InfoNode> nl = infoRoot.getChildren(); writeNodeList(nl, outw, 5); outw.println(" </" + type + ">"); if (line != null) outw.println(finalTag); outw.close(); } catch (IOException error) { throw new InfoUnitIOException(error.getMessage()); } }
00
Code Sample 1: public List<String> addLine(String username, String URL, int page) { List<String> rss = new ArrayList<String>(); try { URL url = new URL(URL + page); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; System.out.println(reader.readLine()); while ((line = reader.readLine()) != null) { String string = "<text>"; String string1 = "</text>"; if (line.contains(string) && !line.contains("@") && !line.contains("http")) { String tweet = line.replace(string, "").replace(string1, "").replace("'", "").trim(); final Tweets tweets = new Tweets(username, tweet, page, false); int save = tweets.save(); tweets.setId((long) save); Thread thread = new Thread(new Runnable() { @Override public void run() { Main.addRow(tweets); } }); thread.start(); System.out.println(tweet); } } reader.close(); } catch (MalformedURLException e) { Log.put(e.toString()); System.out.println(e.toString()); } catch (IOException e) { Log.put(e.toString()); System.out.println(e.toString()); } catch (Exception e) { Log.put(e.toString()); System.out.println(e.toString()); } return rss; } Code Sample 2: public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
11
Code Sample 1: public int delete(BusinessObject o) throws DAOException { int delete = 0; Item item = (Item) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_ITEM")); pst.setInt(1, item.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; } Code Sample 2: public int editRecipe(int oldRecipeId, Recipe newRecipe) throws Exception { PreparedStatement pst1 = null; PreparedStatement pst2 = null; ResultSet rs = null; int retVal = -1; try { conn = getConnection(); pst1 = conn.prepareStatement("UPDATE recipes SET name = ?, instructions = ?, category_id =? WHERE recipe_id = ?"); pst1.setString(1, newRecipe.getName()); pst1.setString(2, newRecipe.getInstructions()); pst1.setInt(3, newRecipe.getCategoryId()); pst1.setInt(4, oldRecipeId); int rsVal = pst1.executeUpdate(); conn.commit(); if (rsVal > 0) { updateIngredients(newRecipe, oldRecipeId); MainFrame.recipePanel.update(); retVal = oldRecipeId; } else { retVal = -1; } conn.commit(); } catch (Exception e) { conn.rollback(); throw new Exception("Can't edit recipe, the exception was " + e.getMessage()); } finally { try { if (rs != null) rs.close(); rs = null; if (pst1 != null) pst1.close(); pst1 = null; if (pst2 != null) pst2.close(); pst2 = null; } catch (SQLException sqle) { MainFrame.appendStatusText("Can't close database connection."); } } return retVal; }
00
Code Sample 1: public static URLConnection openRemoteDescriptionFile(String urlstr) throws MalformedURLException { URL url = new URL(urlstr); try { URLConnection conn = url.openConnection(); conn.connect(); return conn; } catch (Exception e) { Config conf = Config.loadConfig(); SimpleSocketAddress localServAddr = conf.getLocalProxyServerAddress(); Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(localServAddr.host, localServAddr.port)); URLConnection conn; try { conn = url.openConnection(proxy); conn.connect(); return conn; } catch (IOException e1) { logger.error("Failed to retrive desc file:" + url, e1); } } return null; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: protected HttpURLConnection openConnection(final String url) throws IOException { final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("User-Agent", userAgent); connection.setRequestProperty("Accept", "application/xhtml+xml,application/xml,text/xml;q=0.9,*/*;q=0.8"); connection.setRequestProperty("Accept-Language", "ja,en-us;q=0.7,en;q=0.3"); connection.setRequestProperty("Accept-Encoding", "deflate"); connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setRequestProperty("Authorization", "Basic ".concat(base64Encode((username.concat(":").concat(password)).getBytes("UTF-8")))); return connection; } Code Sample 2: @Override public TDSScene loadScene(URL url) throws IOException, IncorrectFormatException, ParsingErrorException { boolean baseURLWasNull = setBaseURLFromModelURL(url); TDSScene scene = loadScene(url.openStream()); if (baseURLWasNull) { popBaseURL(); } return (scene); }
00
Code Sample 1: private String loadStatusResult() { try { URL url = new URL(getServerUrl()); InputStream input = url.openStream(); InputStreamReader is = new InputStreamReader(input, "utf-8"); BufferedReader reader = new BufferedReader(is); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (MalformedURLException e1) { e1.printStackTrace(); return null; } catch (IOException e2) { e2.printStackTrace(); return null; } } Code Sample 2: public static boolean copyFile(String fromfile, String tofile) { File from = new File(fromfile); File to = new File(tofile); if (!from.exists()) return false; if (to.exists()) { log.error(tofile + "exists already"); return false; } BufferedInputStream in = null; BufferedOutputStream out = null; FileInputStream fis = null; FileOutputStream ois = null; boolean flag = true; try { to.createNewFile(); fis = new FileInputStream(from); ois = new FileOutputStream(to); in = new BufferedInputStream(fis); out = new BufferedOutputStream(ois); byte[] buf = new byte[2048]; int readBytes = 0; while ((readBytes = in.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, readBytes); } } catch (IOException e) { log.error(e); flag = false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { log.error(e); flag = false; } } return flag; }
11
Code Sample 1: public void copyFile(String source_file_path, String destination_file_path) { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(source_file_path); fw = new FileWriter(destination_file_path); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(source_file_path); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { System.out.println(source_file_path + " does not exist!"); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel channelSrc = fis.getChannel(); FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } Code Sample 2: private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
11
Code Sample 1: public void importarHistoricoDoPIB(Andamento pAndamento) throws FileNotFoundException, SQLException, Exception { pAndamento.delimitarIntervaloDeVariacao(0, 49); PIB[] valoresPendentesDoPIB = obterValoresPendentesDoPIB(pAndamento); pAndamento.delimitarIntervaloDeVariacao(50, 100); if (valoresPendentesDoPIB != null && valoresPendentesDoPIB.length > 0) { String sql = "INSERT INTO tmp_TB_PIB(ULTIMO_DIA_DO_MES, PIB_ACUM_12MESES_REAL, PIB_ACUM_12MESES_DOLAR) VALUES(:ULTIMO_DIA_DO_MES, :PIB_ACUM_12MESES_REAL, :PIB_ACUM_12MESES_DOLAR)"; OraclePreparedStatement stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosASeremImportados = valoresPendentesDoPIB.length; try { int quantidadeDeRegistrosImportados = 0; int numeroDoRegistro = 0; final BigDecimal MILHAO = new BigDecimal("1000000"); for (PIB valorPendenteDoPIB : valoresPendentesDoPIB) { ++numeroDoRegistro; stmtDestino.clearParameters(); java.sql.Date vULTIMO_DIA_DO_MES = new java.sql.Date(obterUltimoDiaDoMes(valorPendenteDoPIB.mesEAno).getTime()); BigDecimal vPIB_ACUM_12MESES_REAL = valorPendenteDoPIB.valorDoPIBEmReais.multiply(MILHAO).setScale(0, RoundingMode.DOWN); BigDecimal vPIB_ACUM_12MESES_DOLAR = valorPendenteDoPIB.valorDoPIBEmDolares.multiply(MILHAO).setScale(0, RoundingMode.DOWN); stmtDestino.setDateAtName("ULTIMO_DIA_DO_MES", vULTIMO_DIA_DO_MES); stmtDestino.setBigDecimalAtName("PIB_ACUM_12MESES_REAL", vPIB_ACUM_12MESES_REAL); stmtDestino.setBigDecimalAtName("PIB_ACUM_12MESES_DOLAR", vPIB_ACUM_12MESES_DOLAR); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosASeremImportados * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); throw ex; } finally { if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } } pAndamento.setPercentualCompleto(100); } Code Sample 2: public synchronized long nextValue(final Session session) { if (sequence < seqLimit) { return ++sequence; } else { final MetaDatabase db = MetaTable.DATABASE.of(table); Connection connection = null; ResultSet res = null; String sql = null; PreparedStatement statement = null; StringBuilder out = new StringBuilder(64); try { connection = session.getSeqConnection(db); String tableName = db.getDialect().printFullTableName(getTable(), true, out).toString(); out.setLength(0); out.setLength(0); sql = db.getDialect().printSequenceNextValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); int i = statement.executeUpdate(); if (i == 0) { out.setLength(0); sql = db.getDialect().printSequenceInit(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.executeUpdate(); } out.setLength(0); sql = db.getDialect().printSequenceCurrentValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); res = statement.executeQuery(); res.next(); seqLimit = res.getLong(1); int step = res.getInt(2); maxValue = res.getLong(3); sequence = (seqLimit - step) + 1; if (maxValue != 0L) { if (seqLimit > maxValue) { seqLimit = maxValue; if (sequence > maxValue) { String msg = "The sequence '" + tableName + "' needs to raise the maximum value: " + maxValue; throw new IllegalStateException(msg); } statement.close(); sql = db.getDialect().printSetMaxSequence(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.execute(); } if (maxValue > Long.MAX_VALUE - step) { String msg = "The sequence attribute '" + tableName + ".maxValue' is too hight," + " the recommended maximal value is: " + (Long.MAX_VALUE - step) + " (Long.MAX_VALUE-step)"; LOGGER.log(Level.WARNING, msg); } } connection.commit(); } catch (Throwable e) { if (connection != null) try { connection.rollback(); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "Rollback fails"); } IllegalStateException exception = e instanceof IllegalStateException ? (IllegalStateException) e : new IllegalStateException("ILLEGAL SQL: " + sql, e); throw exception; } finally { MetaDatabase.close(null, statement, res, true); } return sequence; } }
11
Code Sample 1: public static final boolean copy(File source, File target, boolean overwrite) { if (!overwrite && target.exists()) { LOGGER.error("Target file exist and it not permitted to overwrite it !"); return false; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } finally { try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } } return true; } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static final void main(String[] args) throws Exception { final HttpHost target = new HttpHost("issues.apache.org", 443, "https"); final HttpHost proxy = new HttpHost("127.0.0.1", 8666, "http"); setup(); HttpClient client = createHttpClient(); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); HttpRequest req = createRequest(); System.out.println("executing request to " + target + " via " + proxy); HttpEntity entity = null; try { HttpResponse rsp = client.execute(target, req); entity = rsp.getEntity(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); Header[] headers = rsp.getAllHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); } System.out.println("----------------------------------------"); if (rsp.getEntity() != null) { System.out.println(EntityUtils.toString(rsp.getEntity())); } } finally { if (entity != null) entity.consumeContent(); } } Code Sample 2: public void run() { String baseUrl; if (_rdoSRTM3FtpUrl.getSelection()) { } else { baseUrl = _txtSRTM3HttpUrl.getText().trim(); try { final URL url = new URL(baseUrl); final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.connect(); final int response = urlConn.getResponseCode(); final String responseMessage = urlConn.getResponseMessage(); final String message = response == HttpURLConnection.HTTP_OK ? NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionOK_message, baseUrl) : NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionFAILED_message, new Object[] { baseUrl, Integer.toString(response), responseMessage == null ? UI.EMPTY_STRING : responseMessage }); MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, message); } catch (final IOException e) { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, NLS.bind(Messages.prefPage_srtm_checkHTTPConnection_message, baseUrl)); e.printStackTrace(); } } }
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 { int maxCount = 67076096; long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }
00
Code Sample 1: protected Drawing loadDrawing(ProgressIndicator progress) throws IOException { Drawing drawing = createDrawing(); if (getParameter("datafile") != null) { URL url = new URL(getDocumentBase(), getParameter("datafile")); URLConnection uc = url.openConnection(); if (uc instanceof HttpURLConnection) { ((HttpURLConnection) uc).setUseCaches(false); } int contentLength = uc.getContentLength(); InputStream in = uc.getInputStream(); try { if (contentLength != -1) { in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); progress.setIndeterminate(false); } BufferedInputStream bin = new BufferedInputStream(in); bin.mark(512); IOException formatException = null; for (InputFormat format : drawing.getInputFormats()) { try { bin.reset(); } catch (IOException e) { uc = url.openConnection(); in = uc.getInputStream(); in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); bin = new BufferedInputStream(in); bin.mark(512); } try { bin.reset(); format.read(bin, drawing, true); formatException = null; break; } catch (IOException e) { formatException = e; } } if (formatException != null) { throw formatException; } } finally { in.close(); } } return drawing; } Code Sample 2: public static void download(String address, String localFileName, String rawClass, double newVer, int newStage) { OutputStream out = null; URLConnection conn = null; InputStream in = null; int totalBytes = 0; int dlBytes = 0; try { if (!Main.Updates.current.hasFile(rawClass)) { Main.Updates.current.addFile(newVer, newStage, rawClass); } Main.Updates.current.getFile(rawClass).downloading = true; Main.Updates.setImage(rawClass, "refresh.png"); java.io.File folder = new java.io.File(localFileName); folder.createNewFile(); URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); totalBytes = conn.getContentLength(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; double incr = java.lang.Math.floor(totalBytes / 1000); Main.Interface.Update.prgStatus.setMaximum(1000); Main.Interface.Update.prgStatus.setString("0.0%"); while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; dlBytes += numRead; int newVal = (dlBytes != totalBytes ? (int) java.lang.Math.floor(dlBytes / incr) : 1000); Main.Interface.Update.prgStatus.setValue(newVal); Main.Interface.Update.prgStatus.setString((newVal / 10) + "." + (newVal % 10) + "%"); } Main.Updates.current.getFile(rawClass).downloading = false; Main.Updates.current.getFile(rawClass).version = newVer; Main.Updates.current.getFile(rawClass).stage = newStage; Main.Updates.setImage(rawClass, "updater.png"); Main.Updates.updateTable(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ioe) { } } }
00
Code Sample 1: public static String hash(final String text) { try { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return Sha1.convertToHex(sha1hash); } catch (NoSuchAlgorithmException e) { return null; } catch (UnsupportedEncodingException e) { return null; } } Code Sample 2: private NodeList getNodeListForDataFile(String fileName, String dataType) { NodeList list = null; try { URL url = new URL(WEBSITE_PROTOCAL, WEBSITE_HOST, "/" + fileName + ".xml"); InputStream is = url.openStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document document = builder.parse(is); list = document.getElementsByTagName(dataType); } catch (SAXException e) { log.error("Error reading " + dataType + " data", e); } catch (IOException e) { log.error("Error reading " + dataType + " data", e); } catch (ParserConfigurationException e) { log.error("Error reading " + dataType + " data", e); } return list; }
00
Code Sample 1: private long generateNativeInstallExe(File nativeInstallFile, String instTemplate, File instClassFile) throws IOException { InputStream reader = getClass().getResourceAsStream("/" + instTemplate); ByteArrayOutputStream content = new ByteArrayOutputStream(); String installClassVarStr = "000000000000"; byte[] buf = new byte[installClassVarStr.length()]; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassVarStr.length()); int installClassStopPos = 0; long installClassOffset = reader.available(); int position = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallExe")); reader.read(buf, 0, buf.length); position = 1; for (int n = 0; n < 3; n++) { while ((!new String(buf).equals("clname_here_")) && (!new String(buf).equals("clstart_here")) && (!new String(buf).equals("clstop_here_"))) { content.write(buf[0]); int nextb = reader.read(); position++; shiftArray(buf); buf[buf.length - 1] = (byte) nextb; } if (new String(buf).equals("clname_here_")) { VAGlobals.printDebug(" clname_here_ found at " + (position - 1)); StringBuffer clnameBuffer = new StringBuffer(64); clnameBuffer.append(instClassName_); for (int i = clnameBuffer.length() - 1; i < 64; i++) { clnameBuffer.append('.'); } byte[] clnameBytes = clnameBuffer.toString().getBytes(); for (int i = 0; i < 64; i++) { content.write(clnameBytes[i]); position++; } reader.skip(64 - buf.length); reader.read(buf, 0, buf.length); } else if (new String(buf).equals("clstart_here")) { VAGlobals.printDebug(" clstart_here found at " + (position - 1)); buf = nf.format(installClassOffset).getBytes(); for (int i = 0; i < buf.length; i++) { content.write(buf[i]); position++; } reader.read(buf, 0, buf.length); } else if (new String(buf).equals("clstop_here_")) { VAGlobals.printDebug(" clstop_here_ found at " + (position - 1)); installClassStopPos = position - 1; content.write(buf); position += 12; reader.read(buf, 0, buf.length); } } content.write(buf); buf = new byte[2048]; int read = reader.read(buf); while (read > 0) { content.write(buf, 0, read); read = reader.read(buf); } reader.close(); FileInputStream classStream = new FileInputStream(instClassFile); read = classStream.read(buf); while (read > 0) { content.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); content.close(); byte[] contentBytes = content.toByteArray(); installClassVarStr = nf.format(contentBytes.length); byte[] installClassVarBytes = installClassVarStr.getBytes(); for (int i = 0; i < installClassVarBytes.length; i++) { contentBytes[installClassStopPos + i] = installClassVarBytes[i]; } FileOutputStream out = new FileOutputStream(nativeInstallFile); out.write(contentBytes); out.close(); return installClassOffset; } Code Sample 2: private String calculateMD5(String value) { String finalString; try { MessageDigest md5Alg = MessageDigest.getInstance("MD5"); md5Alg.reset(); md5Alg.update(value.getBytes()); byte messageDigest[] = md5Alg.digest(); StringBuilder hexString = new StringBuilder(256); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } finalString = hexString.toString(); } catch (NoSuchAlgorithmException exc) { throw new RuntimeException("Hashing error happened:", exc); } return finalString; }
11
Code Sample 1: public static int proxy(java.net.URI uri, HttpServletRequest req, HttpServletResponse res) throws IOException { final HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost(uri.getHost()); HttpMethodBase httpMethod = null; if (HttpRpcServer.METHOD_GET.equalsIgnoreCase(req.getMethod())) { httpMethod = new GetMethod(uri.toString()); httpMethod.setFollowRedirects(true); } else if (HttpRpcServer.METHOD_POST.equalsIgnoreCase(req.getMethod())) { httpMethod = new PostMethod(uri.toString()); final Enumeration parameterNames = req.getParameterNames(); if (parameterNames != null) while (parameterNames.hasMoreElements()) { final String parameterName = (String) parameterNames.nextElement(); for (String parameterValue : req.getParameterValues(parameterName)) ((PostMethod) httpMethod).addParameter(parameterName, parameterValue); } ((PostMethod) httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream())); } if (httpMethod == null) throw new IllegalArgumentException("Unsupported http request method"); final int responseCode; final Enumeration headers = req.getHeaderNames(); if (headers != null) while (headers.hasMoreElements()) { final String headerName = (String) headers.nextElement(); final Enumeration headerValues = req.getHeaders(headerName); while (headerValues.hasMoreElements()) { httpMethod.setRequestHeader(headerName, (String) headerValues.nextElement()); } } final HttpState httpState = new HttpState(); if (req.getCookies() != null) for (Cookie cookie : req.getCookies()) { String host = req.getHeader("Host"); if (StringUtils.isEmpty(cookie.getDomain())) cookie.setDomain(StringUtils.isEmpty(host) ? req.getServerName() + ":" + req.getServerPort() : host); if (StringUtils.isEmpty(cookie.getPath())) cookie.setPath("/"); httpState.addCookie(new org.apache.commons.httpclient.Cookie(cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge(), cookie.getSecure())); } httpMethod.setQueryString(req.getQueryString()); responseCode = (new HttpClient()).executeMethod(hostConfig, httpMethod, httpState); if (responseCode < 0) { httpMethod.releaseConnection(); return responseCode; } if (httpMethod.getResponseHeaders() != null) for (Header header : httpMethod.getResponseHeaders()) res.setHeader(header.getName(), header.getValue()); final InputStream in = httpMethod.getResponseBodyAsStream(); final OutputStream out = res.getOutputStream(); IOUtils.copy(in, out); out.flush(); out.close(); in.close(); httpMethod.releaseConnection(); return responseCode; } Code Sample 2: public static boolean copyFile(String src, String dst) { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(new File(src)).getChannel(); outChannel = new FileOutputStream(new File(dst)).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (FileNotFoundException e) { e.printStackTrace(); MessageGenerator.briefError("ERROR could not find/access file(s): " + src + " and/or " + dst); return false; } catch (IOException e) { MessageGenerator.briefError("ERROR copying file: " + src + " to " + dst); return false; } finally { try { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } catch (IOException e) { MessageGenerator.briefError("Error closing files involved in copying: " + src + " and " + dst); return false; } } return true; }
00
Code Sample 1: protected QName _getServiceName(String wsdlLocation) throws IOException, WSDLException { URL url = new URL(wsdlLocation); InputStream is = null; QName service = null; try { is = url.openStream(); WSDLReader reader = WSDLFactory.newInstance().newWSDLReader(); Definition def = reader.readWSDL(null, new InputSource(is)); Map services = def.getServices(); if (services.size() == 1) { javax.wsdl.Service se = (javax.wsdl.Service) services.values().iterator().next(); service = se.getQName(); } } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } return service; } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(sid); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { } }
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: public static void main(String[] args) { try { boolean readExp = Utils.getFlag('l', args); final boolean writeExp = Utils.getFlag('s', args); final String expFile = Utils.getOption('f', args); if ((readExp || writeExp) && (expFile.length() == 0)) { throw new Exception("A filename must be given with the -f option"); } Experiment exp = null; if (readExp) { FileInputStream fi = new FileInputStream(expFile); ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(fi)); exp = (Experiment) oi.readObject(); oi.close(); } else { exp = new Experiment(); } System.err.println("Initial Experiment:\n" + exp.toString()); final JFrame jf = new JFrame("Weka Experiment Setup"); jf.getContentPane().setLayout(new BorderLayout()); final SetupPanel sp = new SetupPanel(); jf.getContentPane().add(sp, BorderLayout.CENTER); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.err.println("\nFinal Experiment:\n" + sp.m_Exp.toString()); if (writeExp) { try { FileOutputStream fo = new FileOutputStream(expFile); ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(fo)); oo.writeObject(sp.m_Exp); oo.close(); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Couldn't write experiment to: " + expFile + '\n' + ex.getMessage()); } } jf.dispose(); System.exit(0); } }); jf.pack(); jf.setVisible(true); System.err.println("Short nap"); Thread.currentThread().sleep(3000); System.err.println("Done"); sp.setExperiment(exp); } catch (Exception ex) { ex.printStackTrace(); System.err.println(ex.getMessage()); } }
11
Code Sample 1: @Test public void testFromFile() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor_float.net"), new FileOutputStream(temp)); Fann fann = new Fann(temp.getPath()); assertEquals(2, fann.getNumInputNeurons()); assertEquals(1, fann.getNumOutputNeurons()); assertEquals(-1f, fann.run(new float[] { -1, -1 })[0], .2f); assertEquals(1f, fann.run(new float[] { -1, 1 })[0], .2f); assertEquals(1f, fann.run(new float[] { 1, -1 })[0], .2f); assertEquals(-1f, fann.run(new float[] { 1, 1 })[0], .2f); fann.close(); } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public boolean setCliente(int IDcliente, String nombre, String paterno, String materno, String ocupacion, String rfc) { boolean inserto = false; try { stm = conexion.prepareStatement("insert into clientes values( '" + IDcliente + "' , '" + nombre.toUpperCase() + "' , '" + paterno.toUpperCase() + "' , '" + materno.toUpperCase() + "' , '" + ocupacion.toUpperCase() + "' , '" + rfc + "' )"); stm.executeUpdate(); conexion.commit(); inserto = true; } catch (SQLException e) { System.out.println("error al insertar registro en la tabla clientes general " + e.getMessage()); try { conexion.rollback(); } catch (SQLException ee) { System.out.println(ee.getMessage()); } return inserto = false; } return inserto; } Code Sample 2: private boolean get(String surl, File dst, Get get) throws IOException { boolean ret = false; InputStream is = null; OutputStream os = null; try { try { if (surl.startsWith("file://")) { is = new FileInputStream(surl.substring(7)); } else { URL url = new URL(surl); is = url.openStream(); } if (is != null) { os = new FileOutputStream(dst); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } } catch (ConnectException ex) { log("Connect exception " + ex.getMessage(), ex, 3); if (dst.exists()) dst.delete(); } catch (UnknownHostException ex) { log("Unknown host " + ex.getMessage(), ex, 3); } catch (FileNotFoundException ex) { log("File not found: " + ex.getMessage(), 3); } } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } if (ret) { try { is = new FileInputStream(dst); os = new FileOutputStream(getCachedFile(get)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; }
11
Code Sample 1: public void _testConvertIntoOneFile() { File csvFile = new File("C:/DE311/solution_workspace/WorkbookTaglib/WorkbookTagDemoWebapp/src/main/resources/csv/google.csv"); try { Charset guessedCharset = com.glaforge.i18n.io.CharsetToolkit.guessEncoding(csvFile, 4096); CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), guessedCharset))); Writer writer = new FileWriter("/temp/test.html"); int nbLines = CsvConverterUtils.countLines(new BufferedReader(new FileReader(csvFile))); HtmlConverter conv = new HtmlConverter(); conv.convert(reader, writer, nbLines); } catch (Exception e) { fail(e.getMessage()); } } Code Sample 2: public void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true); fileInputStream.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public static void bubbleSort(String[] a) { Collator myCollator = Collator.getInstance(); boolean switched = true; for (int pass = 0; pass < a.length - 1 && switched; pass++) { switched = false; for (int i = 0; i < a.length - pass - 1; i++) { if (myCollator.compare(a[i], a[i + 1]) > 0) { switched = true; String temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } } } Code Sample 2: public String identify(String baseURL) throws OAIException { PrefixResolverDefault prefixResolver; XPath xpath; XPathContext xpathSupport; int ctxtNode; XObject list; Node node; boolean v2 = false; priCheckBaseURL(); try { URL url = new URL(baseURL + "?verb=Identify"); HttpURLConnection http = (HttpURLConnection) url.openConnection(); http = frndTrySend(http); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); if (validation == VALIDATION_VERY_STRICT) { docFactory.setValidating(true); } else { docFactory.setValidating(false); } DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document xml = null; try { xml = docBuilder.parse(http.getInputStream()); } catch (IllegalArgumentException iae) { throw new OAIException(OAIException.CRITICAL_ERR, iae.getMessage()); } catch (SAXException se) { if (validation != VALIDATION_LOOSE) { throw new OAIException(OAIException.XML_PARSE_ERR, se.getMessage()); } else { try { url = new URL(baseURL + "?verb=Identify"); http.disconnect(); http = (HttpURLConnection) url.openConnection(); http = frndTrySend(http); xml = docBuilder.parse(priCreateDummyIdentify(http.getInputStream())); } catch (SAXException se2) { throw new OAIException(OAIException.XML_PARSE_ERR, se2.getMessage()); } } } try { descrNamespaceNode = xml.createElement("Identify"); descrNamespaceNode.setAttribute("xmlns:oai_id", XMLNS_OAI + "Identify"); descrNamespaceNode.setAttribute("xmlns:id", XMLNS_ID); descrNamespaceNode.setAttribute("xmlns:epr", XMLNS_EPR); prefixResolver = new PrefixResolverDefault(descrNamespaceNode); xpathSupport = new XPathContext(); ctxtNode = xpathSupport.getDTMHandleFromNode(xml); xpath = new XPath("/oai_id:Identify", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node == null) { descrNamespaceNode.setAttribute("xmlns:oai_id", XMLNS_OAI_2_0); descrNamespaceNode.setAttribute("xmlns:id", XMLNS_ID_2_0); descrNamespaceNode.setAttribute("xmlns:epr", XMLNS_EPR); prefixResolver = new PrefixResolverDefault(descrNamespaceNode); xpath = new XPath("/oai_id:OAI-PMH", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node == null) { descrNamespaceNode.setAttribute("xmlns:oai_id", XMLNS_OAI_1_0 + "Identify"); descrNamespaceNode.setAttribute("xmlns:id", XMLNS_ID_1_0); descrNamespaceNode.setAttribute("xmlns:epr", XMLNS_EPR_1_0); prefixResolver = new PrefixResolverDefault(descrNamespaceNode); } else { xpath = new XPath("oai_id:OAI-PMH/oai_id:error", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); ixmlErrors = list.nodelist(); if (getLastOAIErrorCount() > 0) { strProtocolVersion = "2"; throw new OAIException(OAIException.OAI_ERR, getLastOAIError().getCode() + ": " + getLastOAIError().getReason()); } v2 = true; } } xpath = new XPath("//oai_id:repositoryName", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strRepositoryName = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strRepositoryName = "UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing repositoryName"); } } xpath = new XPath("//oai_id:baseURL", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strBaseURL = node.getFirstChild().getNodeValue(); } else { if (validation != VALIDATION_LOOSE) { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing baseURL"); } } xpath = new XPath("//oai_id:protocolVersion", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strProtocolVersion = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strProtocolVersion = "UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing protocolVersion"); } } xpath = new XPath("//oai_id:adminEmail", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); NodeList nl = list.nodelist(); if (nl.getLength() > 0) { strAdminEmail = new String[nl.getLength()]; for (int i = 0; i < nl.getLength(); i++) { strAdminEmail[i] = nl.item(i).getFirstChild().getNodeValue(); } } else { if (validation == VALIDATION_LOOSE) { strAdminEmail = new String[1]; strAdminEmail[0] = "mailto:UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing adminEmail"); } } if (v2) { xpath = new XPath("//oai_id:earliestDatestamp", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strEarliestDatestamp = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strEarliestDatestamp = "UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing earliestDatestamp"); } } xpath = new XPath("//oai_id:deletedRecord", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strDeletedRecord = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strDeletedRecord = "UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing deletedRecordp"); } } xpath = new XPath("//oai_id:granularity", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strGranularity = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strGranularity = "UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing granularity"); } } xpath = new XPath("//oai_id:compression", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); nl = list.nodelist(); if (nl.getLength() > 0) { strCompression = new String[nl.getLength()]; for (int i = 0; i < nl.getLength(); i++) { strCompression[i] = nl.item(i).getFirstChild().getNodeValue(); } } } xpath = new XPath("//oai_id:description", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); ixmlDescriptions = list.nodelist(); xpath = new XPath("//oai_id:responseDate", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strResponseDate = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strResponseDate = ""; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "GetRecord missing responseDate"); } } xpath = new XPath("//oai_id:requestURL | //oai_id:request", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { ixmlRequest = node; } else { if (validation == VALIDATION_LOOSE) { ixmlRequest = null; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "GetRecord missing requestURL"); } } state = STATE_IDENTIFIED; xpath = null; prefixResolver = null; xpathSupport = null; list = null; } catch (TransformerException te) { throw new OAIException(OAIException.CRITICAL_ERR, te.getMessage()); } url = null; docFactory = null; docBuilder = null; } catch (IOException ie) { throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage()); } catch (FactoryConfigurationError fce) { throw new OAIException(OAIException.CRITICAL_ERR, fce.getMessage()); } catch (ParserConfigurationException pce) { throw new OAIException(OAIException.CRITICAL_ERR, pce.getMessage()); } return strRepositoryName; }
11
Code Sample 1: public static String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { logger.error("NoSuchAlgorithmException:" + e); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncodingException:" + e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public static String encodeString(String encodeType, String str) { if (encodeType.equals("md5of16")) { MD5 m = new MD5(); return m.getMD5ofStr16(str); } else if (encodeType.equals("md5of32")) { MD5 m = new MD5(); return m.getMD5ofStr(str); } else { try { MessageDigest gv = MessageDigest.getInstance(encodeType); gv.update(str.getBytes()); return new BASE64Encoder().encode(gv.digest()); } catch (java.security.NoSuchAlgorithmException e) { logger.error("BASE64加密失败", e); return null; } } }
00
Code Sample 1: private void inject(int x, int y) throws IOException { Tag source = data.getTag(); Log.event(Log.DEBUG_INFO, "source: " + source.getString()); if (source == Tag.ORGANISM) { String seed = data.readString(); data.readTag(Tag.STREAM); injectCodeTape(data.getIn(), seed, x, y); } else if (source == Tag.URL) { String url = data.readString(); String seed = url.substring(url.lastIndexOf('.') + 1); BufferedReader urlIn = null; try { urlIn = new BufferedReader(new InputStreamReader(new URL(url).openStream())); injectCodeTape(urlIn, seed, x, y); } finally { if (urlIn != null) urlIn.close(); } } else data.writeString("unknown organism source: " + source.getString()); } Code Sample 2: public void postData(Reader data, Writer output) { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) solrUrl.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new PostException("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + POST_ENCODING); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, POST_ENCODING); pipe(data, writer); writer.close(); } catch (IOException e) { throw new PostException("IOException while posting data", e); } finally { if (out != null) out.close(); } InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); } catch (IOException e) { throw new PostException("IOException while reading response", e); } finally { if (in != null) in.close(); } } catch (IOException e) { try { fatal("Solr returned an error: " + urlc.getResponseMessage()); } catch (IOException f) { } fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e); } finally { if (urlc != null) urlc.disconnect(); } }
11
Code Sample 1: protected void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
11
Code Sample 1: protected static void copyDeleting(File source, File dest) throws ErrorCodeException { byte[] buf = new byte[8 * 1024]; FileInputStream in = null; try { in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { int count; while ((count = in.read(buf)) >= 0) out.write(buf, 0, count); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new ErrorCodeException(e); } } Code Sample 2: public static boolean copyFile(File from, File to) { try { FileChannel fromChannel = new FileInputStream(from).getChannel(); FileChannel toChannel = new FileOutputStream(to).getChannel(); toChannel.transferFrom(fromChannel, 0, fromChannel.size()); fromChannel.close(); toChannel.close(); } catch (IOException e) { log.error("failed to copy " + from.getAbsolutePath() + " to " + to.getAbsolutePath() + ": caught exception", e); return false; } return true; }
11
Code Sample 1: public void verRecordatorio() { try { cantidadArchivos = obtenerCantidad() + 1; boolean existe = false; String filenametxt = ""; String filenamezip = ""; String hora = ""; String lugar = ""; String actividad = ""; String linea = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (dia == Integer.parseInt(identificarDato(datoSeleccionado))) { existe = true; hora = input.readLine(); lugar = input.readLine(); while ((linea = input.readLine()) != null) actividad += linea + "\n"; verRecordatorioInterfaz(hora, lugar, actividad); hora = ""; lugar = ""; actividad = ""; } input.close(); } if (!existe) JOptionPane.showMessageDialog(null, "No existe un recordatorio guardado\n" + "para el " + identificarDato(datoSeleccionado) + " de " + meses[mesTemporal].toLowerCase() + " del a�o " + anoTemporal, "No existe", JOptionPane.INFORMATION_MESSAGE); table.clearSelection(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } } Code Sample 2: public static void copyFile(File srcFile, File destFile) throws IOException { if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath()); if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[4096]; int no = 0; try { while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no); } finally { in.close(); out.close(); } }
00
Code Sample 1: public static void loadConfig(URL urlFile) throws CacheException { Document document; try { document = Utilities.getDocument(urlFile.openStream()); } catch (IOException e) { throw new CacheException("Could not open '" + urlFile.getFile() + "'", e); } catch (JAnalyticsException e) { throw new CacheException("Could not open '" + urlFile.getFile() + "'", e); } Element element = (Element) document.getElementsByTagName(DOCUMENT_CACHE_ELEMENT_NAME).item(0); if (element != null) { String className = element.getAttribute(CLASSNAME_ATTRIBUTE_NAME); if (className != null) { Properties config = new Properties(); NodeList nodes = element.getElementsByTagName(PARAM_ELEMENT_NAME); if (nodes != null) { for (int i = 0, count = nodes.getLength(); i < count; i++) { Node node = nodes.item(i); if (node instanceof Element) { Element n = (Element) node; String name = n.getAttribute(NAME_ATTRIBUTE_NAME); String value = n.getAttribute(VALUE_ATTRIBUTE_NAME); config.put(name, value); } } } loadConfig(className, config); } } } Code Sample 2: private void publishZip(LWMap map) { try { if (map.getFile() == null) { VueUtil.alert(VueResources.getString("dialog.mapsave.message"), VueResources.getString("dialog.mapsave.title")); return; } File savedCMap = PublishUtil.createZip(map, Publisher.resourceVector); InputStream istream = new BufferedInputStream(new FileInputStream(savedCMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(ActionUtil.selectFile("Export to Zip File", "zip"))); int fileLength = (int) savedCMap.length(); byte bytes[] = new byte[fileLength]; while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); istream.close(); ostream.close(); } catch (Exception ex) { System.out.println(ex); VueUtil.alert(VUE.getDialogParent(), VueResources.getString("dialog.export.message") + ex.getMessage(), VueResources.getString("dialog.export.title"), JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } }
11
Code Sample 1: private void write(File src, File dst, byte id3v1Tag[], byte id3v2HeadTag[], byte id3v2TailTag[]) throws IOException { if (src == null || !src.exists()) throw new IOException(Debug.getDebug("missing src", src)); if (!src.getName().toLowerCase().endsWith(".mp3")) throw new IOException(Debug.getDebug("src not mp3", src)); if (dst == null) throw new IOException(Debug.getDebug("missing dst", dst)); if (dst.exists()) { dst.delete(); if (dst.exists()) throw new IOException(Debug.getDebug("could not delete dst", dst)); } boolean hasId3v1 = new MyID3v1().hasID3v1(src); long id3v1Length = hasId3v1 ? ID3_V1_TAG_LENGTH : 0; long id3v2HeadLength = new MyID3v2().findID3v2HeadLength(src); long id3v2TailLength = new MyID3v2().findID3v2TailLength(src, hasId3v1); OutputStream os = null; InputStream is = null; try { dst.getParentFile().mkdirs(); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); if (!skipId3v2Head && !skipId3v2 && id3v2HeadTag != null) os.write(id3v2HeadTag); is = new FileInputStream(src); is = new BufferedInputStream(is); is.skip(id3v2HeadLength); long total_to_read = src.length(); total_to_read -= id3v1Length; total_to_read -= id3v2HeadLength; total_to_read -= id3v2TailLength; byte buffer[] = new byte[1024]; long total_read = 0; while (total_read < total_to_read) { int remainder = (int) (total_to_read - total_read); int readSize = Math.min(buffer.length, remainder); int read = is.read(buffer, 0, readSize); if (read <= 0) throw new IOException("unexpected EOF"); os.write(buffer, 0, read); total_read += read; } if (!skipId3v2Tail && !skipId3v2 && id3v2TailTag != null) os.write(id3v2TailTag); if (!skipId3v1 && id3v1Tag != null) os.write(id3v1Tag); } finally { try { if (is != null) is.close(); } catch (Throwable e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (Throwable e) { Debug.debug(e); } } } Code Sample 2: public void copy(File source, File dest) throws IOException { System.out.println("copy " + source + " -> " + dest); FileInputStream in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { out.close(); } } finally { in.close(); } }
11
Code Sample 1: public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); } 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 Vector split() { File nextFile = new File(filename); long fileSize = nextFile.length(); long parts = fileSize / splitSize; Vector vec = new Vector(new Long(parts).intValue()); if (debug) { System.out.println("File: " + nextFile.getName() + "\nfileSize: " + fileSize + "\nsplitSize: " + splitSize + "\nparts: " + parts); } if (fileSize % splitSize > 0) { parts++; } try { FileInputStream fis = new FileInputStream(nextFile); DataInputStream dis = new DataInputStream(fis); long bytesRead = 0; File destinationDirectory = new File(nextFile.getParent()); if (!destinationDirectory.exists()) { destinationDirectory.mkdir(); } for (long k = 0; k < parts; k++) { if (debug) { System.out.println("Splitting parts: " + nextFile.getName() + " into part " + k); } String filePartName = nextFile.getName(); filePartName = filePartName + "." + String.valueOf(k); File outputFile = new File(destinationDirectory, filePartName); FileOutputStream fos = new FileOutputStream(outputFile); DataOutputStream dos = new DataOutputStream(fos); long bytesWritten = 0; while ((bytesWritten < splitSize) && (bytesRead < fileSize)) { dos.writeByte(dis.readByte()); bytesRead++; bytesWritten++; } dos.close(); vec.addElement(outputFile.getAbsolutePath()); if (debug) { System.out.println("Wrote " + bytesWritten + " bytes." + outputFile.getName() + " created."); } } } catch (FileNotFoundException fnfe) { System.err.println("FileNotFoundException: " + fnfe.getMessage()); vec = null; } catch (IOException ioe) { System.err.println("IOException: " + ioe.getMessage()); vec = null; } return vec; } Code Sample 2: public static String compressFile(String fileName) throws IOException { String newFileName = fileName + ".gz"; FileInputStream fis = new FileInputStream(fileName); FileOutputStream fos = new FileOutputStream(newFileName); GZIPOutputStream gzos = new GZIPOutputStream(fos); byte[] buf = new byte[10000]; int bytesRead; while ((bytesRead = fis.read(buf)) > 0) gzos.write(buf, 0, bytesRead); fis.close(); gzos.close(); return newFileName; }
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 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 static void copyFile(File sourceFile, File targetFile) throws FileSaveException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileSaveException(exceptionMessage, ioException); } } Code Sample 2: @Override protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String filename = ServletRequestUtils.getRequiredStringParameter(request, "id"); final File file = new File(path, filename + ".html"); logger.debug("Getting static content from: " + file.getPath()); final InputStream is = getServletContext().getResourceAsStream(file.getPath()); OutputStream out = null; if (is != null) { try { out = response.getOutputStream(); IOUtils.copy(is, out); } catch (IOException ioex) { logger.error(ioex); } finally { is.close(); if (out != null) { out.close(); } } } return null; }
00
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: protected String doIt() throws java.lang.Exception { StringBuffer sql = null; int no = 0; String clientCheck = " AND AD_Client_ID=" + m_AD_Client_ID; String[] strFields = new String[] { "Value", "Name", "Description", "DocumentNote", "Help", "UPC", "SKU", "Classification", "ProductType", "Discontinued", "DiscontinuedBy", "ImageURL", "DescriptionURL" }; for (int i = 0; i < strFields.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(strFields[i]).append(" = (SELECT ").append(strFields[i]).append(" FROM M_Product p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product p WHERE " + strFields[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + strFields[i] + " - default from existing Product=" + no); } } String[] numFields = new String[] { "C_UOM_ID", "M_Product_Category_ID", "Volume", "Weight", "ShelfWidth", "ShelfHeight", "ShelfDepth", "UnitsPerPallet", "M_Product_Family_ID" }; for (int i = 0; i < numFields.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFields[i]).append(" = (SELECT ").append(numFields[i]).append(" FROM M_Product p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product p WHERE " + numFields[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFields[i] + " default from existing Product=" + no); } } String[] strFieldsPO = new String[] { "UPC", "PriceEffective", "VendorProductNo", "VendorCategory", "Manufacturer", "Discontinued", "DiscontinuedBy" }; for (int i = 0; i < strFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(strFieldsPO[i]).append(" = (SELECT ").append(strFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product_PO p WHERE " + strFieldsPO[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + strFieldsPO[i] + " default from existing Product PO=" + no); } } String[] numFieldsPO = new String[] { "C_UOM_ID", "C_Currency_ID", "RoyaltyAmt", "Order_Min", "Order_Pack", "CostPerOrder", "DeliveryTime_Promised" }; for (int i = 0; i < numFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFieldsPO[i]).append(" = (SELECT ").append(numFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product_PO p WHERE " + numFieldsPO[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFieldsPO[i] + " default from existing Product PO=" + no); } } numFieldsPO = new String[] { "PriceList", "PricePO" }; for (int i = 0; i < numFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFieldsPO[i]).append(" = (SELECT ").append(numFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND (").append(numFieldsPO[i]).append(" IS NULL OR ").append(numFieldsPO[i]).append("=0)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFieldsPO[i] + " default from existing Product PO=" + no); } } sql = new StringBuffer("UPDATE I_Product i " + "SET X12DE355 = " + "(SELECT X12DE355 FROM C_UOM u WHERE u.IsDefault='Y' AND u.AD_Client_ID IN (0,i.AD_Client_ID) AND ROWNUM=1) " + "WHERE X12DE355 IS NULL AND C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set UOM Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET C_UOM_ID = (SELECT C_UOM_ID FROM C_UOM u WHERE u.X12DE355=i.X12DE355 AND u.AD_Client_ID IN (0,i.AD_Client_ID)) " + "WHERE C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - Set UOM=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid UOM, ' " + "WHERE C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid UOM=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET ProductCategory_Value=(SELECT Value FROM M_Product_Category" + " WHERE IsDefault='Y' AND AD_Client_ID=").append(m_AD_Client_ID).append(" AND ROWNUM=1) " + "WHERE ProductCategory_Value IS NULL AND M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set Category Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET M_Product_Category_ID=(SELECT M_Product_Category_ID FROM M_Product_Category c" + " WHERE i.ProductCategory_Value=c.Value AND i.AD_Client_ID=c.AD_Client_ID) " + "WHERE M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - Set Category=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid ProdCategorty,' " + "WHERE M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid Category=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET ISO_Code=(SELECT ISO_Code FROM C_Currency c" + " INNER JOIN C_AcctSchema a ON (a.C_Currency_ID=c.C_Currency_ID)" + " INNER JOIN AD_ClientInfo fo ON (a.C_AcctSchema_ID=fo.C_AcctSchema1_ID)" + " WHERE fo.AD_Client_ID=i.AD_Client_ID) " + "WHERE C_Currency_ID IS NULL AND ISO_Code IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set Currency Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET C_Currency_ID=(SELECT C_Currency_ID FROM C_Currency c" + " WHERE i.ISO_Code=c.ISO_Code AND c.AD_Client_ID IN (0,i.AD_Client_ID)) " + "WHERE C_Currency_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt- Set Currency=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Currency,' " + "WHERE C_Currency_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid Currency=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid ProductType,' " + "WHERE ProductType NOT IN ('I','S')" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid ProductType=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Value not unique,' " + "WHERE I_IsImported<>'Y'" + " AND Value IN (SELECT Value FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY Value HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique Value=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=UPC not unique,' " + "WHERE I_IsImported<>'Y'" + " AND UPC IN (SELECT UPC FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY UPC HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique UPC=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Mandatory Value,' " + "WHERE Value IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - No Mandatory Value=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET VendorProductNo=Value " + "WHERE C_BPartner_ID IS NOT NULL AND VendorProductNo IS NULL" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - VendorProductNo Set to Value=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=VendorProductNo not unique,' " + "WHERE I_IsImported<>'Y'" + " AND C_BPartner_ID IS NOT NULL" + " AND (C_BPartner_ID, VendorProductNo) IN " + " (SELECT C_BPartner_ID, VendorProductNo FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY C_BPartner_ID, VendorProductNo HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique VendorProductNo=" + no); } int C_TaxCategory_ID = 0; try { PreparedStatement pstmt = DB.prepareStatement("SELECT C_TaxCategory_ID FROM C_TaxCategory WHERE IsDefault='Y'" + clientCheck); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { C_TaxCategory_ID = rs.getInt(1); } rs.close(); pstmt.close(); } catch (SQLException e) { throw new Exception("doIt - TaxCategory", e); } log.fine("doIt - C_TaxCategory_ID=" + C_TaxCategory_ID); int noInsert = 0; int noUpdate = 0; int noInsertPO = 0; int noUpdatePO = 0; log.fine("doIt - start inserting/updating ..."); sql = new StringBuffer("SELECT I_Product_ID, M_Product_ID, C_BPartner_ID " + "FROM I_Product WHERE I_IsImported='N'").append(clientCheck); Connection conn = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); try { PreparedStatement pstmt_insertProduct = conn.prepareStatement("INSERT INTO M_Product (M_Product_ID," + "AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," + "Value,Name,Description,DocumentNote,Help," + "UPC,SKU,C_UOM_ID,IsSummary,M_Product_Category_ID,C_TaxCategory_ID," + "ProductType,ImageURL,DescriptionURL,M_Product_Family_ID) " + "SELECT ?," + "AD_Client_ID,AD_Org_ID,'Y',CURRENT_TIMESTAMP,CreatedBy,CURRENT_TIMESTAMP,UpdatedBy," + "Value,Name,Description,DocumentNote,Help," + "UPC,SKU,C_UOM_ID,'N',M_Product_Category_ID," + C_TaxCategory_ID + "," + "ProductType,ImageURL,DescriptionURL,M_Product_Category_ID " + "FROM I_Product " + "WHERE I_Product_ID=?"); PreparedStatement pstmt_updateProduct = conn.prepareStatement("UPDATE M_PRODUCT " + "SET Value=aux.value" + ",Name=aux.Name" + ",Description=aux.Description" + ",DocumentNote=aux.DocumentNote" + ",Help=aux.Help" + ",UPC=aux.UPC" + ",SKU=aux.SKU" + ",C_UOM_ID=aux.C_UOM_ID" + ",M_Product_Category_ID=aux.M_Product_Category_ID" + ",Classification=aux.Classification" + ",ProductType=aux.ProductType" + ",Volume=aux.Volume" + ",Weight=aux.Weight" + ",ShelfWidth=aux.ShelfWidth" + ",ShelfHeight=aux.ShelfHeight" + ",ShelfDepth=aux.ShelfDepth" + ",UnitsPerPallet=aux.UnitsPerPallet" + ",Discontinued=aux.Discontinued" + ",DiscontinuedBy=aux.DiscontinuedBy" + ",Updated=current_timestamp" + ",UpdatedBy=aux.UpdatedBy" + " from (SELECT Value,Name,Description,DocumentNote,Help,UPC,SKU,C_UOM_ID,M_Product_Category_ID,Classification,ProductType,Volume,Weight,ShelfWidth,ShelfHeight,ShelfDepth,UnitsPerPallet,Discontinued,DiscontinuedBy,UpdatedBy FROM I_Product WHERE I_Product_ID=?) as aux" + " WHERE M_Product_ID=?"); PreparedStatement pstmt_updateProductPO = conn.prepareStatement("UPDATE M_Product_PO " + "SET IsCurrentVendor='Y'" + ",C_UOM_ID=aux1.C_UOM_ID" + ",C_Currency_ID=aux1.C_Currency_ID" + ",UPC=aux1.UPC" + ",PriceList=aux1.PriceList" + ",PricePO=aux1.PricePO" + ",RoyaltyAmt=aux1.RoyaltyAmt" + ",PriceEffective=aux1.PriceEffective" + ",VendorProductNo=aux1.VendorProductNo" + ",VendorCategory=aux1.VendorCategory" + ",Manufacturer=aux1.Manufacturer" + ",Discontinued=aux1.Discontinued" + ",DiscontinuedBy=aux1.DiscontinuedBy" + ",Order_Min=aux1.Order_Min" + ",Order_Pack=aux1.Order_Pack" + ",CostPerOrder=aux1.CostPerOrder" + ",DeliveryTime_Promised=aux1.DeliveryTime_Promised" + ",Updated=current_timestamp" + ",UpdatedBy=aux1.UpdatedBy" + " from (SELECT 'Y',C_UOM_ID,C_Currency_ID,UPC,PriceList,PricePO,RoyaltyAmt,PriceEffective,VendorProductNo,VendorCategory,Manufacturer,Discontinued,DiscontinuedBy,Order_Min,Order_Pack,CostPerOrder,DeliveryTime_Promised,UpdatedBy FROM I_Product WHERE I_Product_ID=?) as aux1" + " WHERE M_Product_ID=? AND C_BPartner_ID=?"); PreparedStatement pstmt_insertProductPO = conn.prepareStatement("INSERT INTO M_Product_PO (M_Product_ID,C_BPartner_ID, " + "AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," + "IsCurrentVendor,C_UOM_ID,C_Currency_ID,UPC," + "PriceList,PricePO,RoyaltyAmt,PriceEffective," + "VendorProductNo,VendorCategory,Manufacturer," + "Discontinued,DiscontinuedBy,Order_Min,Order_Pack," + "CostPerOrder,DeliveryTime_Promised) " + "SELECT ?,?, " + "AD_Client_ID,AD_Org_ID,'Y',d,CreatedBy,CURRENT_TIMESTAMP,UpdatedBy," + "'Y',C_UOM_ID,C_Currency_ID,UPC," + "PriceList,PricePO,RoyaltyAmt,PriceEffective," + "VendorProductNo,VendorCategory,Manufacturer," + "Discontinued,DiscontinuedBy,Order_Min,Order_Pack," + "CostPerOrder,DeliveryTime_Promised " + "FROM I_Product " + "WHERE I_Product_ID=?"); PreparedStatement pstmt_setImported = conn.prepareStatement("UPDATE I_Product SET I_IsImported='Y', M_Product_ID=?, " + "Updated=CURRENT_TIMESTAMP, Processed='Y' WHERE I_Product_ID=?"); PreparedStatement pstmt = DB.prepareStatement(sql.toString()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int I_Product_ID = rs.getInt(1); int M_Product_ID = rs.getInt(2); int C_BPartner_ID = rs.getInt(3); boolean newProduct = M_Product_ID == 0; log.fine("I_Product_ID=" + I_Product_ID + ", M_Product_ID=" + M_Product_ID + ", C_BPartner_ID=" + C_BPartner_ID); if (newProduct) { M_Product_ID = DB.getNextID(m_AD_Client_ID, "M_Product", null); pstmt_insertProduct.setInt(1, M_Product_ID); pstmt_insertProduct.setInt(2, I_Product_ID); try { no = pstmt_insertProduct.executeUpdate(); log.finer("Insert Product = " + no); noInsert++; } catch (SQLException ex) { log.warning("Insert Product - " + ex.toString()); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Insert Product: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } else { pstmt_updateProduct.setInt(1, I_Product_ID); pstmt_updateProduct.setInt(2, M_Product_ID); try { no = pstmt_updateProduct.executeUpdate(); log.finer("Update Product = " + no); noUpdate++; } catch (SQLException ex) { log.warning("Update Product - " + ex.toString()); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Update Product: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } if (C_BPartner_ID != 0) { no = 0; if (!newProduct) { pstmt_updateProductPO.setInt(1, I_Product_ID); pstmt_updateProductPO.setInt(2, M_Product_ID); pstmt_updateProductPO.setInt(3, C_BPartner_ID); try { no = pstmt_updateProductPO.executeUpdate(); log.finer("Update Product_PO = " + no); noUpdatePO++; } catch (SQLException ex) { log.warning("Update Product_PO - " + ex.toString()); noUpdate--; conn.rollback(); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Update Product_PO: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } if (no == 0) { pstmt_insertProductPO.setInt(1, M_Product_ID); pstmt_insertProductPO.setInt(2, C_BPartner_ID); pstmt_insertProductPO.setInt(3, I_Product_ID); try { no = pstmt_insertProductPO.executeUpdate(); log.finer("Insert Product_PO = " + no); noInsertPO++; } catch (SQLException ex) { log.warning("Insert Product_PO - " + ex.toString()); noInsert--; conn.rollback(); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Insert Product_PO: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } } pstmt_setImported.setInt(1, M_Product_ID); pstmt_setImported.setInt(2, I_Product_ID); no = pstmt_setImported.executeUpdate(); conn.commit(); } rs.close(); pstmt.close(); pstmt_insertProduct.close(); pstmt_updateProduct.close(); pstmt_insertProductPO.close(); pstmt_updateProductPO.close(); pstmt_setImported.close(); conn.close(); conn = null; } catch (SQLException e) { try { if (conn != null) { conn.close(); } conn = null; } catch (SQLException ex) { } log.log(Level.SEVERE, "doIt", e); throw new Exception("doIt", e); } finally { if (conn != null) { conn.close(); } conn = null; } sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='N', Updated=CURRENT_TIMESTAMP " + "WHERE I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); StringBuffer infoReturn = new StringBuffer(""); infoReturn.append("<tr><td>@Errors@</td><td>").append(no).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@: @Inserted@</td><td>").append(noInsert).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@: @Updated@</td><td>").append(noUpdate).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@ @Purchase@: @Inserted@</td><td>").append(noInsertPO).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@ @Purchase@: @Updated@</td><td>").append(noUpdatePO).append("</td></tr>"); return infoReturn.toString(); }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private void createWar() throws IOException, XMLStreamException { String appName = this.fileout.getName(); int i = appName.indexOf("."); if (i != -1) appName = appName.substring(0, i); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(this.fileout)); { ZipEntry entry = new ZipEntry("WEB-INF/web.xml"); zout.putNextEntry(entry); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter w = factory.createXMLStreamWriter(zout, "ASCII"); w.writeStartDocument("ASCII", "1.0"); w.writeStartElement("web-app"); w.writeAttribute("xsi", XSI, "schemaLocation", "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml /ns/javaee/web-app_2_5.xsd"); w.writeAttribute("version", "2.5"); w.writeAttribute("xmlns", J2EE); w.writeAttribute("xmlns:xsi", XSI); w.writeStartElement("description"); w.writeCharacters("Site maintenance for " + appName); w.writeEndElement(); w.writeStartElement("display-name"); w.writeCharacters(appName); w.writeEndElement(); w.writeStartElement("servlet"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("jsp-file"); w.writeCharacters("/WEB-INF/jsp/down.jsp"); w.writeEndElement(); w.writeEndElement(); w.writeStartElement("servlet-mapping"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("url-pattern"); w.writeCharacters("/*"); w.writeEndElement(); w.writeEndElement(); w.writeEndElement(); w.writeEndDocument(); w.flush(); zout.closeEntry(); } { ZipEntry entry = new ZipEntry("WEB-INF/jsp/down.jsp"); zout.putNextEntry(entry); PrintWriter w = new PrintWriter(zout); if (this.messageFile != null) { IOUtils.copyTo(new FileReader(this.messageFile), w); } else if (this.messageString != null) { w.print("<html><body>" + this.messageString + "</body></html>"); } else { w.print("<html><body><div style='text-align:center;font-size:500%;'>Oh No !<br/><b>" + appName + "</b><br/>is down for maintenance!</div></body></html>"); } w.flush(); zout.closeEntry(); } zout.finish(); zout.flush(); zout.close(); }
00
Code Sample 1: private FTPClient getFTPConnection(String strUser, String strPassword, String strServer, boolean binaryTransfer, String connectionNote, boolean passiveMode) { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(strServer); ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Connected to " + strServer + ", " + connectionNote); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP server refused connection."); return null; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { return null; } } ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP Could not connect to server."); ResourcePool.LogException(e, this); return null; } try { if (!ftp.login(strUser, strPassword)) { ftp.logout(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP login failed."); return null; } ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Remote system is " + ftp.getSystemName() + ", " + connectionNote); if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } else { ftp.setFileType(FTP.ASCII_FILE_TYPE); } if (passiveMode) { ftp.enterLocalPassiveMode(); } else { ftp.enterLocalActiveMode(); } } catch (FTPConnectionClosedException e) { ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "Server closed connection."); ResourcePool.LogException(e, this); return null; } catch (IOException e) { ResourcePool.LogException(e, this); return null; } return ftp; } Code Sample 2: public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = MessageLocalizer.getMessage("SCHEMA_CREATED_BY_OBJECT") + " [" + objectControlller + "] " + MessageLocalizer.getMessage("WITH_BOUI") + " [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (SCHEMA,OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } }
00
Code Sample 1: 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); } Code Sample 2: public HTTPResponse makeRequest(BasicHttpRequest request) throws IOException { try { if (!conn.isOpen()) { logger.warn(ApacheHTTP.class, "Creating socket"); Socket socket = getSocket(host.getHostName(), host.getPort(), ssl, true); conn.bind(socket, params); } HttpContext context = new BasicHttpContext(null); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); context.setAttribute(ExecutionContext.HTTP_REQUEST, request); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); httpexecutor.postProcess(response, httpproc, context); if (!connStrategy.keepAlive(response, context)) keepAlive = false; int statusCode = response.getStatusLine().getStatusCode(); HttpEntity resp = response.getEntity(); if (statusCode >= 400) { HTTPEntityInfo info = new HTTPEntityInfo((int) resp.getContentLength(), "", resp.getContentType().getValue()); byte[] bytes = IOUtil.toByteArray(resp.getContent()); throw new HTTPErrorResponse(response.getStatusLine().getReasonPhrase(), statusCode + "", bytes, info); } else { Header lastmodHeader = response.getLastHeader("last-modified"); String lastmod = lastmodHeader == null ? "" : lastmodHeader.getValue(); Header contentType = resp.getContentType(); HTTPEntityInfo info = new HTTPEntityInfo((int) resp.getContentLength(), lastmod, contentType == null ? null : contentType.getValue()); return new HTTPResponse(info, resp.getContent()); } } catch (HttpException he) { throw new IOException(he); } }