label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
private void initStreams() throws IOException { if (audio != null) { audio.close(); } if (url != null) { audio = new OggInputStream(url.openStream()); } else { audio = new OggInputStream(ResourceLoader.getResourceAsStream(ref)); } }
Code Sample 2:
public static byte[] expandPasswordToKeySSHCom(String password, int keyLen) { try { if (password == null) { password = ""; } MessageDigest md5 = MessageDigest.getInstance("MD5"); int digLen = md5.getDigestLength(); byte[] buf = new byte[((keyLen + digLen) / digLen) * digLen]; int cnt = 0; while (cnt < keyLen) { md5.update(password.getBytes()); if (cnt > 0) { md5.update(buf, 0, cnt); } md5.digest(buf, cnt, digLen); cnt += digLen; } byte[] key = new byte[keyLen]; System.arraycopy(buf, 0, key, 0, keyLen); return key; } catch (Exception e) { throw new Error("Error in SSH2KeyPairFile.expandPasswordToKeySSHCom: " + e); } }
|
11
|
Code Sample 1:
public BufferedImage extract() throws DjatokaException { boolean useRegion = false; int left = 0; int top = 0; int width = 50; int height = 50; boolean useleftDouble = false; Double leftDouble = 0.0; boolean usetopDouble = false; Double topDouble = 0.0; boolean usewidthDouble = false; Double widthDouble = 0.0; boolean useheightDouble = false; Double heightDouble = 0.0; if (params.getRegion() != null) { StringTokenizer st = new StringTokenizer(params.getRegion(), "{},"); String token; if ((token = st.nextToken()).contains(".")) { topDouble = Double.parseDouble(token); usetopDouble = true; } else top = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { leftDouble = Double.parseDouble(token); useleftDouble = true; } else left = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { heightDouble = Double.parseDouble(token); useheightDouble = true; } else height = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { widthDouble = Double.parseDouble(token); usewidthDouble = true; } else width = Integer.parseInt(token); useRegion = true; } try { if (is != null) { File f = File.createTempFile("tmp", ".jp2"); f.deleteOnExit(); FileOutputStream fos = new FileOutputStream(f); sourceFile = f.getAbsolutePath(); IOUtils.copyStream(is, fos); is.close(); fos.close(); } } catch (IOException e) { throw new DjatokaException(e); } try { Jp2_source inputSource = new Jp2_source(); Kdu_compressed_source input = null; Jp2_family_src jp2_family_in = new Jp2_family_src(); Jp2_locator loc = new Jp2_locator(); jp2_family_in.Open(sourceFile, true); inputSource.Open(jp2_family_in, loc); inputSource.Read_header(); input = inputSource; Kdu_codestream codestream = new Kdu_codestream(); codestream.Create(input); Kdu_channel_mapping channels = new Kdu_channel_mapping(); if (inputSource.Exists()) channels.Configure(inputSource, false); else channels.Configure(codestream); int ref_component = channels.Get_source_component(0); Kdu_coords ref_expansion = getReferenceExpansion(ref_component, channels, codestream); Kdu_dims image_dims = new Kdu_dims(); codestream.Get_dims(ref_component, image_dims); Kdu_coords imageSize = image_dims.Access_size(); Kdu_coords imagePosition = image_dims.Access_pos(); if (useleftDouble) left = imagePosition.Get_x() + (int) Math.round(leftDouble * imageSize.Get_x()); if (usetopDouble) top = imagePosition.Get_y() + (int) Math.round(topDouble * imageSize.Get_y()); if (useheightDouble) height = (int) Math.round(heightDouble * imageSize.Get_y()); if (usewidthDouble) width = (int) Math.round(widthDouble * imageSize.Get_x()); if (useRegion) { imageSize.Set_x(width); imageSize.Set_y(height); imagePosition.Set_x(left); imagePosition.Set_y(top); } int reduce = 1 << params.getLevelReductionFactor(); imageSize.Set_x(imageSize.Get_x() * ref_expansion.Get_x()); imageSize.Set_y(imageSize.Get_y() * ref_expansion.Get_y()); imagePosition.Set_x(imagePosition.Get_x() * ref_expansion.Get_x() / reduce - ((ref_expansion.Get_x() / reduce - 1) / 2)); imagePosition.Set_y(imagePosition.Get_y() * ref_expansion.Get_y() / reduce - ((ref_expansion.Get_y() / reduce - 1) / 2)); Kdu_dims view_dims = new Kdu_dims(); view_dims.Assign(image_dims); view_dims.Access_size().Set_x(imageSize.Get_x()); view_dims.Access_size().Set_y(imageSize.Get_y()); int region_buf_size = imageSize.Get_x() * imageSize.Get_y(); int[] region_buf = new int[region_buf_size]; Kdu_region_decompressor decompressor = new Kdu_region_decompressor(); decompressor.Start(codestream, channels, -1, params.getLevelReductionFactor(), 16384, image_dims, ref_expansion, new Kdu_coords(1, 1), false, Kdu_global.KDU_WANT_OUTPUT_COMPONENTS); Kdu_dims new_region = new Kdu_dims(); Kdu_dims incomplete_region = new Kdu_dims(); Kdu_coords viewSize = view_dims.Access_size(); incomplete_region.Assign(image_dims); int[] imgBuffer = new int[viewSize.Get_x() * viewSize.Get_y()]; int[] kduBuffer = null; while (decompressor.Process(region_buf, image_dims.Access_pos(), 0, 0, region_buf_size, incomplete_region, new_region)) { Kdu_coords newOffset = new_region.Access_pos(); Kdu_coords newSize = new_region.Access_size(); newOffset.Subtract(view_dims.Access_pos()); kduBuffer = region_buf; int imgBuffereIdx = newOffset.Get_x() + newOffset.Get_y() * viewSize.Get_x(); int kduBufferIdx = 0; int xDiff = viewSize.Get_x() - newSize.Get_x(); for (int j = 0; j < newSize.Get_y(); j++, imgBuffereIdx += xDiff) { for (int i = 0; i < newSize.Get_x(); i++) { imgBuffer[imgBuffereIdx++] = kduBuffer[kduBufferIdx++]; } } } BufferedImage image = new BufferedImage(imageSize.Get_x(), imageSize.Get_y(), BufferedImage.TYPE_INT_RGB); image.setRGB(0, 0, viewSize.Get_x(), viewSize.Get_y(), imgBuffer, 0, viewSize.Get_x()); if (params.getRotationDegree() > 0) { image = ImageProcessingUtils.rotate(image, params.getRotationDegree()); } decompressor.Native_destroy(); channels.Native_destroy(); if (codestream.Exists()) codestream.Destroy(); inputSource.Native_destroy(); input.Native_destroy(); jp2_family_in.Native_destroy(); return image; } catch (KduException e) { e.printStackTrace(); throw new DjatokaException(e); } catch (Exception e) { e.printStackTrace(); throw new DjatokaException(e); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
Code Sample 2:
private static void addFile(File file, ZipArchiveOutputStream zaos) throws IOException { String filename = null; filename = file.getName(); ZipArchiveEntry zae = new ZipArchiveEntry(filename); zae.setSize(file.length()); zaos.putArchiveEntry(zae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, zaos); zaos.closeArchiveEntry(); }
|
00
|
Code Sample 1:
public static void copyFile(String oldPath, String newPath) throws IOException { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); } }
Code Sample 2:
public static String getWebpage(String url) { String content = ""; if (!url.trim().toLowerCase().startsWith("http://")) { url = "http://" + url; } try { BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line; while ((line = reader.readLine()) != null) { content += line + "\n"; } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e2) { e2.printStackTrace(); } return content; }
|
11
|
Code Sample 1:
public static String md5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(value.getBytes()); return bytesToString(messageDigest.digest()); } catch (Exception ex) { Tools.logException(Tools.class, ex, value); } return value; }
Code Sample 2:
public static String crypt(String passwd, boolean pad) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(passwd.getBytes()); String c = new String(sha.digest()); return toNumeric(c, pad, true); } catch (java.security.NoSuchAlgorithmException e) { Log.error(Login.class, "couldn't crypt()", e); return ""; } }
|
11
|
Code Sample 1:
public String generateKey(String className, String methodName, String text, String meaning) { if (text == null) { return null; } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error initializing MD5", e); } try { md5.update(text.getBytes("UTF-8")); if (meaning != null) { md5.update(meaning.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unsupported", e); } return StringUtils.toHexString(md5.digest()); }
Code Sample 2:
public static String encryptStringWithSHA2(String input) { String output = null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(input.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } output = sb.toString(); return output; }
|
00
|
Code Sample 1:
void copyFile(String from, String to) throws IOException { File destFile = new File(to); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(from).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:
public static String checkUpdate() { URL url = null; try { url = new URL("http://googlemeupdate.bravehost.com/"); } catch (MalformedURLException ex) { ex.printStackTrace(); } InputStream html = null; try { html = url.openStream(); int c = 0; String Buffer = ""; String Code = ""; while (c != -1) { try { c = html.read(); } catch (IOException ex) { } Buffer = Buffer + (char) c; } return Buffer.substring(Buffer.lastIndexOf("Google.mE Version: ") + 19, Buffer.indexOf("||")); } catch (IOException ex) { ex.printStackTrace(); return ""; } }
|
00
|
Code Sample 1:
public static BufferedReader openForReading(String name, URI base, ClassLoader classLoader) throws IOException { if ((name == null) || name.trim().equals("")) { return null; } if (name.trim().equals("System.in")) { if (STD_IN == null) { STD_IN = new BufferedReader(new InputStreamReader(System.in)); } return STD_IN; } URL url = nameToURL(name, base, classLoader); if (url == null) { throw new IOException("Could not convert \"" + name + "\" with base \"" + base + "\" to a URL."); } InputStreamReader inputStreamReader = null; try { inputStreamReader = new InputStreamReader(url.openStream()); } catch (IOException ex) { try { URL possibleJarURL = ClassUtilities.jarURLEntryResource(url.toString()); if (possibleJarURL != null) { inputStreamReader = new InputStreamReader(possibleJarURL.openStream()); } return new BufferedReader(inputStreamReader); } catch (Exception ex2) { try { if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException ex3) { } IOException ioException = new IOException("Failed to open \"" + url + "\"."); ioException.initCause(ex); throw ioException; } } return new BufferedReader(inputStreamReader); }
Code Sample 2:
protected static String hashPassword(String password, String salt) throws NoSuchAlgorithmException { String s = salt + password; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes()); byte bs[] = md.digest(); String s1 = BASE64Encoder.encode(bs); return new StringBuffer(salt).append(':').append(s1).toString(); }
|
00
|
Code Sample 1:
public String installCode(String serviceName, String location) throws DeploymentException { FileOutputStream out = null; mLog.debug("overwriteWarFile = " + overwriteWarFile); String fileData = null; String filepath = location; String[] splitString = filepath.split("/"); String filename = splitString[splitString.length - 1]; int fileNameLength = filename.length(); warname = filename.substring(0, fileNameLength - 4); mLog.debug("WAR file name = " + warname); String filepath2 = warDesination + File.separator + filename; ret = "http://" + containerAddress + "/" + warname + "/services/" + serviceName; mLog.debug("filepath2 = " + filepath2); mLog.debug("ret = " + ret); mLog.debug("filepath = " + filepath); boolean warExists = new File(filepath2).exists(); boolean webAppExists = true; try { String webAppName = filepath2.substring(0, (filepath2.length() - 4)); mLog.debug("Web Application Name = " + webAppName); webAppExists = new File(webAppName).isDirectory(); if (!webAppExists) { URL url = new URL(filepath); File targetFile = new File(filepath2); if (!targetFile.exists()) { targetFile.createNewFile(); } InputStream in = null; try { in = url.openStream(); out = new FileOutputStream(targetFile); } catch (Exception e) { e.printStackTrace(); throw new DeploymentException("couldn't open stream due to: " + e.getMessage()); } URLConnection con = url.openConnection(); int fileLength = con.getContentLength(); ReadableByteChannel channelIn = Channels.newChannel(in); FileChannel channelOut = out.getChannel(); channelOut.transferFrom(channelIn, 0, fileLength); channelIn.close(); channelOut.close(); out.flush(); out.close(); in.close(); long time = System.currentTimeMillis(); check(ret, time, STARTCONTROL); } } catch (Exception e) { webAppExists = false; } mLog.debug("webAppExists = " + webAppExists); return (ret); }
Code Sample 2:
public static String httpGetJson(final List<NameValuePair> nameValuePairs) { HttpClient httpclient = null; String data = ""; URI uri = null; try { final String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); if (HTTPS) { final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final HttpParams params = new BasicHttpParams(); final SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry); httpclient = new DefaultHttpClient(mgr, params); uri = new URI(DEADDROPS_SERVER_URL_HTTPS + "?" + paramString); } else { httpclient = new DefaultHttpClient(); uri = new URI(DEADDROPS_SERVER_URL + "?" + paramString); } final HttpGet request = new HttpGet(); request.setURI(uri); final HttpResponse response = httpclient.execute(request); final BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) data += inputLine; in.close(); } catch (final URISyntaxException e) { e.printStackTrace(); return null; } catch (final ClientProtocolException e) { e.printStackTrace(); return null; } catch (final IOException e) { e.printStackTrace(); return null; } return data; }
|
11
|
Code Sample 1:
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; }
Code Sample 2:
protected static URL[] createUrls(URL jarUrls[]) { ArrayList<URL> additionalUrls = new ArrayList<URL>(Arrays.asList(jarUrls)); for (URL ju : jarUrls) { try { JarFile jar = new JarFile(ju.getFile()); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry j = entries.nextElement(); if (j.isDirectory()) continue; if (j.getName().startsWith("lib/") && j.getName().endsWith(".jar")) { URL url = new URL("jar:" + ju.getProtocol() + ":" + ju.getFile() + "!/" + j.getName()); InputStream is = url.openStream(); File tmpFile = File.createTempFile("SCDeploy", ".jar"); FileOutputStream fos = new FileOutputStream(tmpFile); IOUtils.copy(is, fos); is.close(); fos.close(); additionalUrls.add(new URL("file://" + tmpFile.getAbsolutePath())); } } } catch (IOException e) { } } return additionalUrls.toArray(new URL[] {}); }
|
11
|
Code Sample 1:
public static void fileCopy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
Code Sample 2:
private void handleFile(File file, HttpServletRequest request, HttpServletResponse response) throws Exception { String filename = file.getName(); long filesize = file.length(); String mimeType = getMimeType(filename); response.setContentType(mimeType); if (filesize > getDownloadThreshhold()) { response.setHeader("Content-Disposition", "attachment; filename=" + filename); } response.setContentLength((int) filesize); ServletOutputStream out = response.getOutputStream(); IOUtils.copy(new FileInputStream(file), out); out.flush(); }
|
00
|
Code Sample 1:
private void createProperty(String objectID, String value, String propertyID, Long userID) throws JspTagException { ClassProperty classProperty = new ClassProperty(new Long(propertyID)); String newValue = value; if (classProperty.getName().equals("Password")) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.update(value.getBytes()); byte digest[] = crypt.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(hexDigit(digest[i])); } newValue = hexString.toString(); crypt.reset(); } catch (NoSuchAlgorithmException e) { System.err.println("jspShop: Could not get instance of MD5 algorithm. Please fix this!" + e.getMessage()); e.printStackTrace(); throw new JspTagException("Error crypting password!: " + e.getMessage()); } } Properties properties = new Properties(new Long(objectID), userID); try { Property property = properties.create(new Long(propertyID), newValue); pageContext.setAttribute(getId(), property); } catch (CreateException e) { throw new JspTagException("Could not create PropertyValue, CreateException: " + e.getMessage()); } }
Code Sample 2:
public static void refresh() { URL[] urls = Constants.Wiki2xhtml.getUpdateURLs(); content.setLength(0); InputStream is = null; BufferedReader br = null; for (int i = 0; i < urls.length; i++) { try { is = urls[i].openStream(); br = new BufferedReader(new InputStreamReader(is)); String s; while ((s = br.readLine()) != null) { if (s.length() == 0) continue; if (s.startsWith("--")) break; content.append(s + '\n'); } is.close(); break; } catch (FileNotFoundException e) { System.err.println("File not found: " + urls[i].getHost() + urls[i].getPath()); } catch (IOException e) { System.err.println("Error: " + e.getMessage()); } } }
|
00
|
Code Sample 1:
public static File copyFile(File srcFile, File destFolder, FileCopyListener copyListener) { File dest = new File(destFolder, srcFile.getName()); try { FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; long totalSize = srcFile.length(); boolean canceled = false; if (copyListener == null) { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } } else { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); if (!copyListener.updateCheck(readLength, totalSize)) { canceled = true; break; } } } in.close(); out.close(); if (canceled) { dest.delete(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
Code Sample 2:
private void getServiceReponse(String service, NameSpaceDefinition nsDefinition) throws Exception { Pattern pattern = Pattern.compile("(?i)(?:.*(xmlns(?:\\:\\w+)?=\\\"http\\:\\/\\/www\\.ivoa\\.net\\/.*" + service + "[^\\\"]*\\\").*)"); pattern = Pattern.compile(".*xmlns(?::\\w+)?=(\"[^\"]*(?i)(?:" + service + ")[^\"]*\").*"); logger.debug("read " + this.url + service); BufferedReader in = new BufferedReader(new InputStreamReader((new URL(this.url + service)).openStream())); String inputLine; BufferedWriter bfw = new BufferedWriter(new FileWriter(this.baseDirectory + service + ".xml")); boolean found = false; while ((inputLine = in.readLine()) != null) { if (!found) { Matcher m = pattern.matcher(inputLine); if (m.matches()) { nsDefinition.init("xmlns:vosi=" + m.group(1)); found = true; } } bfw.write(inputLine + "\n"); } in.close(); bfw.close(); }
|
11
|
Code Sample 1:
private GmailContact convertContactToGmailContact(Contact contact) throws GmailManagerException { boolean homePhone = false, homePhone2 = false, homeFax = false, homeMobile = false, homePager = false; boolean businessPhone = false, businessPhone2 = false, businessFax = false, businessMobile = false, businessPager = false; boolean otherPhone = false, otherFax = false; if (log.isTraceEnabled()) log.trace("Converting Foundation contact to Gmail contact: Name:" + contact.getName().getFirstName().getPropertyValueAsString()); try { GmailContact gmailContact = new GmailContact(); gmailContact.setId(contact.getUid()); Name name = contact.getName(); if (name != null) if (name.getFirstName() != null && name.getFirstName().getPropertyValueAsString() != null) { StringBuffer buffer = new StringBuffer(); buffer.append(name.getFirstName().getPropertyValueAsString()).append(" "); if (name.getMiddleName() != null && name.getMiddleName().getPropertyValueAsString() != null) buffer.append(name.getMiddleName().getPropertyValueAsString()).append(" "); if (name.getLastName() != null && name.getLastName().getPropertyValueAsString() != null) buffer.append(name.getLastName().getPropertyValueAsString()).append(" "); if (log.isDebugEnabled()) log.debug("NAME: " + buffer.toString().trim()); gmailContact.setName(buffer.toString().trim()); } if (contact.getPersonalDetail() != null) { if (contact.getPersonalDetail().getEmails() != null && contact.getPersonalDetail().getEmails().size() > 0) { if (contact.getPersonalDetail().getEmails().get(0) != null) { Email email1 = (Email) contact.getPersonalDetail().getEmails().get(0); if (email1.getPropertyValueAsString() != null && email1.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL1: " + email1.getPropertyValueAsString()); gmailContact.setEmail(email1.getPropertyValueAsString()); } } if (contact.getPersonalDetail().getEmails().size() > 1 && contact.getPersonalDetail().getEmails().get(1) != null) { Email email2 = (Email) contact.getPersonalDetail().getEmails().get(1); if (email2.getPropertyValueAsString() != null && email2.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL2: " + email2.getPropertyValueAsString()); gmailContact.setEmail2(email2.getPropertyValueAsString()); } } } Address address = contact.getPersonalDetail().getAddress(); if (address != null) if (address.getStreet() != null) if (address.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(address.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("HOME_ADDRESS: " + addressBuffer.toString()); gmailContact.setHomeAddress(addressBuffer.toString()); } Address addressOther = contact.getPersonalDetail().getOtherAddress(); if (addressOther != null) if (addressOther.getStreet() != null) if (addressOther.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(addressOther.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("OTHER_ADDRESS: " + addressBuffer.toString()); gmailContact.setOtherAddress(addressBuffer.toString()); } if (contact.getPersonalDetail().getPhones() != null && contact.getPersonalDetail().getPhones().size() > 0) { for (int i = 0; i < contact.getPersonalDetail().getPhones().size(); i++) { Phone phone = (Phone) contact.getPersonalDetail().getPhones().get(i); if (log.isDebugEnabled()) log.debug("PERSONAL_PHONE: " + phone.getPropertyValueAsString() + " type:" + phone.getPhoneType()); if (phone.getPhoneType().equals(SIFC.HOME_TELEPHONE_NUMBER) && homePhone == false) { gmailContact.setHomePhone(phone.getPropertyValueAsString()); homePhone = true; } else if (phone.getPhoneType().equals(SIFC.HOME2_TELEPHONE_NUMBER) && homePhone2 == false) { gmailContact.setHomePhone2(phone.getPropertyValueAsString()); homePhone2 = true; } else if (phone.getPhoneType().equals(SIFC.HOME_FAX_NUMBER) && homeFax == false) { gmailContact.setHomeFax(phone.getPropertyValueAsString()); homeFax = true; } else if ((phone.getPhoneType().equals(SIFC.MOBILE_TELEPHONE_NUMBER) || phone.getPhoneType().equals(SIFC.MOBILE_HOME_TELEPHONE_NUMBER)) && homeMobile == false) { gmailContact.setMobilePhone(phone.getPropertyValueAsString()); homeMobile = true; } else if (phone.getPhoneType().equals(SIFC.PAGER_NUMBER) && homePager == false) { gmailContact.setPager(phone.getPropertyValueAsString()); homePager = true; } else if (phone.getPhoneType().equals(SIFC.OTHER_TELEPHONE_NUMBER) && otherPhone == false) { gmailContact.setOtherPhone(phone.getPropertyValueAsString()); otherPhone = true; } else if (phone.getPhoneType().equals(SIFC.OTHER_FAX_NUMBER) && otherFax == false) { gmailContact.setOtherFax(phone.getPropertyValueAsString()); otherFax = true; } else { if (log.isDebugEnabled()) log.debug("GOOGLE - Whoops - Personal Phones UNKNOWN TYPE:" + phone.getPhoneType() + " VALUE:" + phone.getPropertyValueAsString()); } } } } if (contact.getBusinessDetail() != null) { if (contact.getBusinessDetail().getEmails() != null && contact.getBusinessDetail().getEmails().size() > 0) { if (contact.getBusinessDetail().getEmails().get(0) != null) { Email email3 = (Email) contact.getBusinessDetail().getEmails().get(0); if (email3.getPropertyValueAsString() != null && email3.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL3: " + email3.getPropertyValueAsString()); gmailContact.setEmail3(email3.getPropertyValueAsString()); } } } Address address = contact.getBusinessDetail().getAddress(); if (address != null) if (address.getStreet() != null) if (address.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(address.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("BUSINESS_ADDRESS: " + addressBuffer.toString()); gmailContact.setBusinessAddress(addressBuffer.toString()); } if (contact.getBusinessDetail().getPhones() != null && contact.getBusinessDetail().getPhones().size() > 0) { for (int i = 0; i < contact.getBusinessDetail().getPhones().size(); i++) { Phone phone = (Phone) contact.getBusinessDetail().getPhones().get(i); if (log.isDebugEnabled()) log.debug("BUSINESS_PHONE: " + phone.getPropertyValueAsString() + " type:" + phone.getPhoneType()); if (phone.getPhoneType().equals(SIFC.BUSINESS_TELEPHONE_NUMBER) && businessPhone == false) { gmailContact.setBusinessPhone(phone.getPropertyValueAsString()); businessPhone = true; } else if (phone.getPhoneType().equals(SIFC.BUSINESS2_TELEPHONE_NUMBER) && businessPhone2 == false) { gmailContact.setBusinessPhone2(phone.getPropertyValueAsString()); businessPhone2 = true; } else if (phone.getPhoneType().equals(SIFC.BUSINESS_FAX_NUMBER) && businessFax == false) { gmailContact.setBusinessFax(phone.getPropertyValueAsString()); businessFax = true; } else if (phone.getPhoneType().equals(SIFC.MOBILE_BUSINESS_TELEPHONE_NUMBER) && homeMobile == false && businessMobile == false) { gmailContact.setMobilePhone(phone.getPropertyValueAsString()); businessMobile = true; } else if (phone.getPhoneType().equals(SIFC.PAGER_NUMBER) && homePager == false && businessPager == false) { gmailContact.setPager(phone.getPropertyValueAsString()); businessPager = true; } else { if (log.isDebugEnabled()) log.debug("GOOGLE - Whoops - Business Phones UNKNOWN TYPE:" + phone.getPhoneType() + " VALUE:" + phone.getPropertyValueAsString()); } } } if (contact.getBusinessDetail().getCompany() != null) if (contact.getBusinessDetail().getCompany().getPropertyValueAsString() != null) { if (log.isDebugEnabled()) log.debug("COMPANY: " + contact.getBusinessDetail().getCompany().getPropertyValueAsString()); gmailContact.setCompany(contact.getBusinessDetail().getCompany().getPropertyValueAsString()); } if (contact.getBusinessDetail().getTitles() != null && contact.getBusinessDetail().getTitles().size() > 0) { if (contact.getBusinessDetail().getTitles().get(0) != null) { Title title = (Title) contact.getBusinessDetail().getTitles().get(0); if (log.isDebugEnabled()) log.debug("TITLE: " + title.getPropertyValueAsString()); gmailContact.setJobTitle(title.getPropertyValueAsString()); } } } if (contact.getNotes() != null && contact.getNotes().size() > 0) { if (contact.getNotes().get(0) != null) { Note notes = (Note) contact.getNotes().get(0); if (notes.getPropertyValueAsString() != null && notes.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("NOTES: " + notes.getPropertyValueAsString()); gmailContact.setNotes(notes.getPropertyValueAsString()); } } } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(contact.toString().getBytes()); gmailContact.setMd5Hash(new BigInteger(m.digest()).toString()); return gmailContact; } catch (Exception e) { throw new GmailManagerException("GOOGLE Gmail - convertContactToGmailContact error: " + e.getMessage()); } }
Code Sample 2:
private final String createMD5(String pwd) throws Exception { MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone(); md.update(pwd.getBytes("UTF-8")); byte[] pd = md.digest(); StringBuffer app = new StringBuffer(); for (int i = 0; i < pd.length; i++) { String s2 = Integer.toHexString(pd[i] & 0xFF); app.append((s2.length() == 1) ? "0" + s2 : s2); } return app.toString(); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { File fileIn = new File("D:\\zz_c\\study2\\src\\study\\io\\A.java"); InputStream fin = new FileInputStream(fileIn); PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(); pout.connect(pin); IoRead i = new IoRead(); i.setIn(pin); File fileOU1 = new File("D:\\zz_c\\study2\\src\\study\\io\\A1.java"); File fileOU2 = new File("D:\\zz_c\\study2\\src\\study\\io\\A2.java"); File fileOU3 = new File("D:\\zz_c\\study2\\src\\study\\io\\A3.java"); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU1))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU2))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU3))); PipedInputStream pin2 = new PipedInputStream(); PipedOutputStream pout2 = new PipedOutputStream(); i.addOut(pout2); pout2.connect(pin2); i.start(); int read; try { read = fin.read(); while (read != -1) { pout.write(read); read = fin.read(); } fin.close(); pout.close(); } catch (IOException e) { e.printStackTrace(); } int c = pin2.read(); while (c != -1) { System.out.print((char) c); c = pin2.read(); } pin2.close(); }
Code Sample 2:
public static File createTempFile(InputStream contentStream, String ext) throws IOException { ExceptionUtils.throwIfNull(contentStream, "contentStream"); File file = File.createTempFile("test", ext); FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copy(contentStream, fos, false); } finally { fos.close(); } return file; }
|
11
|
Code Sample 1:
public static void copy(File file, File dir, boolean overwrite) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); File out = new File(dir, file.getName()); if (out.exists() && !overwrite) { throw new IOException("File: " + out + " already exists."); } FileOutputStream fos = new FileOutputStream(out, false); byte[] block = new byte[4096]; int read = bis.read(block); while (read != -1) { fos.write(block, 0, read); read = bis.read(block); } }
Code Sample 2:
private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static final String computeHash(String stringToCompile) { String retVal = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(stringToCompile.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } retVal = hexString.toString(); if (log.isDebugEnabled()) log.debug("MD5 hash for \"" + stringToCompile + "\" is: " + retVal); } catch (Exception exe) { log.error(exe.getMessage(), exe); } return retVal; }
Code Sample 2:
public boolean ReadFile() { boolean ret = false; FilenameFilter FileFilter = null; File dir = new File(fDir); String[] FeeFiles; int Lines = 0; BufferedReader FeeFile = null; PreparedStatement DelSt = null, InsSt = null; String Line = null, Term = null, CurTerm = null, TermType = null, Code = null; double[] Fee = new double[US_D + 1]; double FeeAm = 0; String UpdateSt = "INSERT INTO reporter.term_fee (TERM, TERM_TYPE, THEM_VC, THEM_VE, THEM_EC, THEM_EE, THEM_D," + "BA_VC, BA_VE, BA_EC, BA_EE, BA_D," + "US_VC, US_VE, US_EC, US_EE, US_D)" + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; try { FileFilter = new FilenameFilter() { public boolean accept(File dir, String name) { if ((new File(dir, name)).isDirectory()) return false; else return (name.matches(fFileMask)); } }; FeeFiles = dir.list(FileFilter); java.util.Arrays.sort(FeeFiles); System.out.println(FeeFiles[FeeFiles.length - 1] + " " + (new SimpleDateFormat("dd.MM.yy HH:mm:ss")).format(new Date())); Log.info(String.format("Load = %1s", fDir + FeeFiles[FeeFiles.length - 1])); FeeFile = new BufferedReader(new FileReader(fDir + FeeFiles[FeeFiles.length - 1])); FeeZero(Fee); DelSt = cnProd.prepareStatement("delete from reporter.term_fee"); DelSt.executeUpdate(); InsSt = cnProd.prepareStatement(UpdateSt); WriteTerm(FeeFiles[FeeFiles.length - 1] + " " + (new SimpleDateFormat("dd.MM.yy HH:mm:ss")).format(new Date()), "XXX", Fee, InsSt); while ((Line = FeeFile.readLine()) != null) { Lines++; if (!Line.matches("\\d{15}\\s+��������.+")) continue; Term = Line.substring(7, 15); if ((CurTerm == null) || !Term.equals(CurTerm)) { if (CurTerm != null) { WriteTerm(CurTerm, TermType, Fee, InsSt); } CurTerm = Term; if (Line.indexOf("���") > 0) TermType = "���"; else TermType = "���"; FeeZero(Fee); } Code = Line.substring(64, 68).trim().toUpperCase(); if (Code.equals("ST") || Code.equals("AC") || Code.equals("8110") || Code.equals("8160")) continue; FeeAm = new Double(Line.substring(140, 160)).doubleValue(); if (Line.indexOf("�� ����� ������") > 0) SetFee(Fee, CARD_THEM, Code, FeeAm); else if (Line.indexOf("�� ������ �����") > 0) SetFee(Fee, CARD_BA, Code, FeeAm); else if (Line.indexOf("�� ������ ��") > 0) SetFee(Fee, CARD_US, Code, FeeAm); else throw new Exception("������ ���� ����.:" + Line); } WriteTerm(CurTerm, TermType, Fee, InsSt); cnProd.commit(); ret = true; } catch (Exception e) { System.out.printf("Err = %1s\r\n", e.getMessage()); Log.error(String.format("Err = %1s", e.getMessage())); Log.error(String.format("Line = %1s", Line)); try { cnProd.rollback(); } catch (Exception ee) { } ; } finally { try { if (FeeFile != null) FeeFile.close(); } catch (Exception ee) { } } try { if (DelSt != null) DelSt.close(); if (InsSt != null) InsSt.close(); cnProd.setAutoCommit(true); } catch (Exception ee) { } Log.info(String.format("Lines = %1d", Lines)); return (ret); }
|
00
|
Code Sample 1:
public static void loginSkyDrive() throws Exception { System.out.println("login "); u = new URL(loginurl); uc = (HttpURLConnection) u.openConnection(); uc.setRequestProperty("Cookie", msprcookie + ";" + mspokcookie); uc.setDoOutput(true); uc.setRequestMethod("POST"); uc.setInstanceFollowRedirects(false); pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()), true); pw.print("login=dinesh007007%40hotmail.com&passwd=&SI=Sign+in&type=11&LoginOptions=3&NewUser=1&MEST=&PPSX=Passpor&PPFT=" + ppft + "&PwdPad=&sso=&i1=&i2=1&i3=10524&i4=&i12=1&i13=&i14=437&i15=624&i16=3438"); pw.flush(); pw.close(); System.out.println(uc.getResponseCode()); Map<String, List<String>> headerFields = uc.getHeaderFields(); if (headerFields.containsKey("Set-Cookie")) { List<String> header = headerFields.get("Set-Cookie"); for (int i = 0; i < header.size(); i++) { tmp = header.get(i); System.out.println(tmp); } } location = uc.getHeaderField("Location"); System.out.println("Location : " + location); System.out.println("going to open paaport page"); DefaultHttpClient d = new DefaultHttpClient(); HttpGet hg = new HttpGet("https://skydrive.live.com"); hg.setHeader("Cookie", msprcookie + ";" + mspokcookie); HttpResponse execute = d.execute(hg); HttpEntity entity = execute.getEntity(); System.out.println(EntityUtils.toString(entity)); System.out.println(execute.getStatusLine()); Header[] allHeaders = execute.getAllHeaders(); for (int i = 0; i < allHeaders.length; i++) { System.out.println(allHeaders[i].getName() + " : " + allHeaders[i].getValue()); } }
Code Sample 2:
public static URL getWikipediaPage(String concept, String language) throws MalformedURLException, IOException { String url = "http://" + language + ".wikipedia.org/wiki/Special:Search?search=" + URLEncoder.encode(concept, UTF_8_ENCODING) + "&go=Go"; HttpURLConnection.setFollowRedirects(false); HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.connect(); int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return null; } else if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM) { return new URL(httpConnection.getHeaderField("Location")); } else { logger.warn("Unexpected response code (" + responseCode + ")."); return null; } } finally { if (httpConnection != null) { httpConnection.disconnect(); } } }
|
00
|
Code Sample 1:
private TupleQueryResult evaluate(String location, String query, QueryLanguage queryLn) throws Exception { location += "?query=" + URLEncoder.encode(query, "UTF-8") + "&queryLn=" + queryLn.getName(); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Accept", TupleQueryResultFormat.SPARQL.getDefaultMIMEType()); conn.connect(); try { int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return QueryResultIO.parse(conn.getInputStream(), TupleQueryResultFormat.SPARQL); } else { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); throw new RuntimeException(response); } } finally { conn.disconnect(); } }
Code Sample 2:
public void copyFile(String source, String destination, String description, boolean recursive) throws Exception { File sourceFile = new File(source); File destinationFile = new File(destination); if (!sourceFile.exists()) { throw new Exception("source file (" + source + ") does not exist!"); } if (!sourceFile.isFile()) { throw new Exception("source file (" + source + ") is not a file!"); } if (!sourceFile.canRead()) { throw new Exception("source file (" + source + ") is not readable!"); } if (destinationFile.exists()) { m_out.print(" - " + destination + " exists, removing... "); if (destinationFile.delete()) { m_out.println("REMOVED"); } else { m_out.println("FAILED"); throw new Exception("unable to delete existing file: " + sourceFile); } } m_out.print(" - copying " + source + " to " + destination + "... "); if (!destinationFile.getParentFile().exists()) { if (!destinationFile.getParentFile().mkdirs()) { throw new Exception("unable to create directory: " + destinationFile.getParent()); } } if (!destinationFile.createNewFile()) { throw new Exception("unable to create file: " + destinationFile); } FileChannel from = null; FileChannel to = null; try { from = new FileInputStream(sourceFile).getChannel(); to = new FileOutputStream(destinationFile).getChannel(); to.transferFrom(from, 0, from.size()); } catch (FileNotFoundException e) { throw new Exception("unable to copy " + sourceFile + " to " + destinationFile, e); } finally { if (from != null) { from.close(); } if (to != null) { to.close(); } } m_out.println("DONE"); }
|
11
|
Code Sample 1:
private byte[] digestFile(File file, MessageDigest digest) throws IOException { DigestInputStream in = new DigestInputStream(new FileInputStream(file), digest); IOUtils.copy(in, new NullOutputStream()); in.close(); return in.getMessageDigest().digest(); }
Code Sample 2:
public GetMessages(String messageType) { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetMessages"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "messages.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&messagetype=" + messageType + "&filename=" + URLEncoder.encode(username, "UTF-8") + "messages.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("message"); int num = nodelist.getLength(); messages = new String[num][7]; for (int i = 0; i < num; i++) { messages[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageid")); messages[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "subject")); messages[i][2] = (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "firstname"))) + " " + (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "lastname"))); messages[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagedatetime")); messages[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagefrom")); messages[i][5] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageto")); messages[i][6] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } }
|
11
|
Code Sample 1:
public static Photo createPhoto(String title, String userLogin, String pathToPhoto, String basePathImage) throws NoSuchAlgorithmException, IOException { String id = CryptSHA1.genPhotoID(userLogin, title); String extension = pathToPhoto.substring(pathToPhoto.lastIndexOf(".")); String destination = basePathImage + id + extension; FileInputStream fis = new FileInputStream(pathToPhoto); FileOutputStream fos = new FileOutputStream(destination); FileChannel fci = fis.getChannel(); FileChannel fco = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int read = fci.read(buffer); if (read == -1) break; buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); fco.close(); fos.close(); fis.close(); ImageIcon image; ImageIcon thumb; String destinationThumb = basePathImage + "thumb/" + id + extension; image = new ImageIcon(destination); int maxSize = 150; int origWidth = image.getIconWidth(); int origHeight = image.getIconHeight(); if (origWidth > origHeight) { thumb = new ImageIcon(image.getImage().getScaledInstance(maxSize, -1, Image.SCALE_SMOOTH)); } else { thumb = new ImageIcon(image.getImage().getScaledInstance(-1, maxSize, Image.SCALE_SMOOTH)); } BufferedImage bi = new BufferedImage(thumb.getIconWidth(), thumb.getIconHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.drawImage(thumb.getImage(), 0, 0, null); try { ImageIO.write(bi, "JPG", new File(destinationThumb)); } catch (IOException ioe) { System.out.println("Error occured saving thumbnail"); } Photo photo = new Photo(id); photo.setTitle(title); photo.basePathImage = basePathImage; return photo; }
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 static XMLShowInfo NzbSearch(TVRageShowInfo tvrage, XMLShowInfo xmldata, int latestOrNext) { String newzbin_query = "", csvData = "", hellaQueueDir = "", newzbinUsr = "", newzbinPass = ""; String[] tmp; DateFormat tvRageDateFormat = new SimpleDateFormat("MMM/dd/yyyy"); DateFormat tvRageDateFormatFix = new SimpleDateFormat("yyyy-MM-dd"); newzbin_query = "?q=" + xmldata.showName + "+"; if (latestOrNext == 0) { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.latestSeasonNum + "x" + tvrage.latestEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.latestSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.latestAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.latestTitle; } else { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.nextSeasonNum + "x" + tvrage.nextEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.nextSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.nextAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.nextTitle; } newzbin_query += "&searchaction=Search"; newzbin_query += "&fpn=p"; newzbin_query += "&category=8category=11"; newzbin_query += "&area=-1"; newzbin_query += "&u_nfo_posts_only=0"; newzbin_query += "&u_url_posts_only=0"; newzbin_query += "&u_comment_posts_only=0"; newzbin_query += "&u_v3_retention=1209600"; newzbin_query += "&ps_rb_language=" + xmldata.language; newzbin_query += "&sort=ps_edit_date"; newzbin_query += "&order=desc"; newzbin_query += "&areadone=-1"; newzbin_query += "&feed=csv"; newzbin_query += "&ps_rb_video_format=" + xmldata.format; newzbin_query = newzbin_query.replaceAll(" ", "%20"); System.out.println("http://v3.newzbin.com/search/" + newzbin_query); try { URL url = new URL("http://v3.newzbin.com/search/" + newzbin_query); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); csvData = in.readLine(); if (csvData != null) { JavaNZB.searchCount++; if (searchCount == 6) { searchCount = 0; System.out.println("Sleeping for 60 seconds"); try { Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } tmp = csvData.split(","); tmp[2] = tmp[2].substring(1, tmp[2].length() - 1); tmp[3] = tmp[3].substring(1, tmp[3].length() - 1); Pattern p = Pattern.compile("[\\\\</:>?\\[|\\]\"]"); Matcher matcher = p.matcher(tmp[3]); tmp[3] = matcher.replaceAll(" "); tmp[3] = tmp[3].replaceAll("&", "and"); URLConnection urlConn; DataOutputStream printout; url = new URL("http://v3.newzbin.com/api/dnzb/"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String content = "username=" + JavaNZB.newzbinUsr + "&password=" + JavaNZB.newzbinPass + "&reportid=" + tmp[2]; printout.writeBytes(content); printout.flush(); printout.close(); BufferedReader nzbInput = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String format = ""; if (xmldata.format.equals("17")) format = " Xvid"; if (xmldata.format.equals("131072")) format = " x264"; if (xmldata.format.equals("2")) format = " DVD"; if (xmldata.format.equals("4")) format = " SVCD"; if (xmldata.format.equals("8")) format = " VCD"; if (xmldata.format.equals("32")) format = " HDts"; if (xmldata.format.equals("64")) format = " WMV"; if (xmldata.format.equals("128")) format = " Other"; if (xmldata.format.equals("256")) format = " ratDVD"; if (xmldata.format.equals("512")) format = " iPod"; if (xmldata.format.equals("1024")) format = " PSP"; File f = new File(JavaNZB.hellaQueueDir, tmp[3] + format + ".nzb"); BufferedWriter out = new BufferedWriter(new FileWriter(f)); String str; System.out.println("--Downloading " + tmp[3] + format + ".nzb" + " to queue directory--"); while (null != ((str = nzbInput.readLine()))) out.write(str); nzbInput.close(); out.close(); if (latestOrNext == 0) { xmldata.episode = tvrage.latestEpisodeNum; xmldata.season = tvrage.latestSeasonNum; } else { xmldata.episode = tvrage.nextEpisodeNum; xmldata.season = tvrage.nextSeasonNum; } } else System.out.println("No new episode posted"); System.out.println(); } catch (MalformedURLException e) { } catch (IOException e) { System.out.println("IO Exception from NzbSearch"); } return xmldata; }
Code Sample 2:
private static String completeGet(String encodedURLStr) throws IOException { URL url = new URL(encodedURLStr); HttpURLConnection connection = initConnection(url); String result = getReply(url.openStream()); connection.disconnect(); return result; }
|
00
|
Code Sample 1:
public static SimpleDataTable loadDataFromFile(URL urlMetadata, URL urlData) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(urlMetadata.openStream())); List<String> columnNamesList = new ArrayList<String>(); String[] lineParts = null; String line; in.readLine(); while ((line = in.readLine()) != null) { lineParts = line.split(","); columnNamesList.add(lineParts[0]); } String[] columnNamesArray = new String[columnNamesList.size()]; int index = 0; for (String s : columnNamesList) { columnNamesArray[index] = s; index++; } SimpleDataTable table = new SimpleDataTable("tabulka s daty", columnNamesArray); in = new BufferedReader(new InputStreamReader(urlData.openStream())); lineParts = null; line = null; SimpleDataTableRow tableRow; double[] rowData; while ((line = in.readLine()) != null) { lineParts = line.split(","); rowData = new double[columnNamesList.size()]; for (int i = 0; i < columnNamesArray.length; i++) { rowData[i] = Double.parseDouble(lineParts[i + 1]); } tableRow = new SimpleDataTableRow(rowData, lineParts[0]); table.add(tableRow); } return table; }
Code Sample 2:
@Override public DataUpdateResult<Record> archiveRecord(String authToken, Record record, Filter filter, Field sourceField, InputModel inputmodel) throws DataOperationException { validateUserIsSignedOn(authToken); validateUserHasAdminRights(authToken); DataUpdateResult<Record> recordUpdateResult = new DataUpdateResult<Record>(); if (record != null) { Connection connection = null; boolean archived = false; try { long userId = getSignedOnUser(authToken).getUserId(); connection = DatabaseConnector.getConnection(); connection.setAutoCommit(false); recordUpdateResult.setMessage(messages.server_record_delete_success("")); recordUpdateResult.setSuccessful(true); String sql = "update tms.records set archivedtimestamp = now() where recordid = ?"; PreparedStatement updateRecord = connection.prepareStatement(sql); updateRecord.setLong(1, record.getRecordid()); int recordArchived = 0; recordArchived = updateRecord.executeUpdate(); if (recordArchived > 0) AuditTrailManager.updateAuditTrail(connection, AuditTrailManager.createAuditTrailEvent(record, userId, AuditableEvent.EVENTYPE_DELETE), authToken, getSession()); TopicUpdateServiceImpl.archiveRecordTopics(connection, record.getTopics(), record.getRecordid()); ArrayList<RecordAttribute> recordAttributes = record.getRecordattributes(); if (recordAttributes != null && recordAttributes.size() > 0) { Iterator<RecordAttribute> rItr = recordAttributes.iterator(); while (rItr.hasNext()) { RecordAttribute r = rItr.next(); String rAtSql = "update tms.recordattributes set archivedtimestamp = now() where recordattributeid = ?"; PreparedStatement updateRecordAttribute = connection.prepareStatement(rAtSql); updateRecordAttribute.setLong(1, r.getRecordattributeid()); int recordAttribArchived = 0; recordAttribArchived = updateRecordAttribute.executeUpdate(); if (recordAttribArchived > 0) AuditTrailManager.updateAuditTrail(connection, AuditTrailManager.createAuditTrailEvent(r, userId, AuditableEvent.EVENTYPE_DELETE), authToken, getSession()); } } ArrayList<Term> terms = record.getTerms(); Iterator<Term> termsItr = terms.iterator(); while (termsItr.hasNext()) { Term term = termsItr.next(); TermUpdater.archiveTerm(connection, term, userId, authToken, getSession()); } connection.commit(); archived = true; if (filter != null) RecordIdTracker.refreshRecordIdsInSessionByFilter(this.getThreadLocalRequest().getSession(), connection, true, filter, sourceField, authToken); else RecordIdTracker.refreshRecordIdsInSession(this.getThreadLocalRequest().getSession(), connection, false, authToken); RecordRetrievalServiceImpl retriever = new RecordRetrievalServiceImpl(); RecordIdTracker.refreshRecordIdsInSession(this.getThreadLocalRequest().getSession(), connection, false, authToken); Record updatedRecord = retriever.retrieveRecordByRecordId(initSignedOnUser(authToken), record.getRecordid(), this.getThreadLocalRequest().getSession(), false, inputmodel, authToken); recordUpdateResult.setResult(updatedRecord); } catch (Exception e) { if (!archived && connection != null) { try { connection.rollback(); } catch (SQLException e1) { LogUtility.log(Level.SEVERE, getSession(), messages.log_db_rollback(""), e1, authToken); e1.printStackTrace(); } } recordUpdateResult.setFailed(true); if (archived) { recordUpdateResult.setMessage(messages.server_record_delete_retrieve("")); recordUpdateResult.setException(e); LogUtility.log(Level.SEVERE, getSession(), messages.server_record_delete_retrieve(""), e, authToken); } else { recordUpdateResult.setMessage(messages.server_record_delete_fail("")); recordUpdateResult.setException(new PersistenceException(e)); LogUtility.log(Level.SEVERE, getSession(), messages.server_record_delete_fail(""), e, authToken); } GWT.log(recordUpdateResult.getMessage(), e); } finally { try { if (connection != null) { connection.setAutoCommit(true); connection.close(); } } catch (Exception e) { LogUtility.log(Level.SEVERE, getSession(), messages.log_db_close(""), e, authToken); } } } return recordUpdateResult; }
|
00
|
Code Sample 1:
public static final void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.apache.org/"); System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); try { System.out.println(reader.readLine()); } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { httpget.abort(); throw ex; } finally { reader.close(); } } }
Code Sample 2:
public static String hash(final String s) { if (s == null || s.length() == 0) return null; try { final MessageDigest hashEngine = MessageDigest.getInstance("SHA-1"); hashEngine.update(s.getBytes("iso-8859-1"), 0, s.length()); return convertToHex(hashEngine.digest()); } catch (final Exception e) { return null; } }
|
11
|
Code Sample 1:
public static void copy(File source, File destination) throws IOException { InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); in.close(); out.close(); }
Code Sample 2:
public void copyFile() throws Exception { SmbFile file = new SmbFile("smb://elsa:elsa@elsa/Elsa/Desktop/Ficheiros2/04-04-2066/How To Make a Flash Preloader.doc"); println("length: " + file.length()); SmbFileInputStream in = new SmbFileInputStream(file); println("available: " + in.available()); File dest = new File("C:\\Documents and Settings\\Carlos\\Desktop\\Flash Preloader.doc"); FileOutputStream out = new FileOutputStream(dest); int buffer_length = 1024; byte[] buffer = new byte[buffer_length]; while (true) { int bytes_read = in.read(buffer, 0, buffer_length); if (bytes_read <= 0) { break; } out.write(buffer, 0, bytes_read); } in.close(); out.close(); println("done."); }
|
00
|
Code Sample 1:
public static String computeDigest(String str, String alg) { MessageDigest currentAlgorithm = null; try { currentAlgorithm = MessageDigest.getInstance(alg); } catch (NoSuchAlgorithmException e) { return str; } currentAlgorithm.reset(); currentAlgorithm.update(str.getBytes()); byte[] hash = currentAlgorithm.digest(); String d = ""; int usbyte = 0; for (int i = 0; i < hash.length; i++) { usbyte = hash[i] & 0xFF; if (usbyte < 16) d += "0" + Integer.toHexString(usbyte); else d += Integer.toHexString(usbyte); } return d.toUpperCase(); }
Code Sample 2:
private void connect(URL url) throws IOException { String protocol = url.getProtocol(); if (!protocol.equals("http")) throw new IllegalArgumentException("URL must use 'http:' protocol"); int port = url.getPort(); if (port == -1) port = 80; fileName = url.getFile(); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); toServer = new OutputStreamWriter(conn.getOutputStream()); fromServer = conn.getInputStream(); }
|
11
|
Code Sample 1:
public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
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:
protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; }
Code Sample 2:
public static String digest(String ha1, String ha2, String nonce) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(ha1, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(nonce, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(ha2, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
|
11
|
Code Sample 1:
protected String getTextResponse(String address, boolean ignoreResponseCode) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); BufferedReader in = null; try { con.connect(); if (!ignoreResponseCode) { assertEquals(HttpURLConnection.HTTP_OK, con.getResponseCode()); } in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder builder = new StringBuilder(); String inputLine = null; while ((inputLine = in.readLine()) != null) { builder.append(inputLine); } return builder.toString(); } finally { if (in != null) { in.close(); } con.disconnect(); } }
Code Sample 2:
public static String downloadWebpage1(String address) throws MalformedURLException, IOException { URL url = new URL(address); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; String page = ""; while((line = br.readLine()) != null) { page += line + "\n"; } br.close(); return page; }
|
00
|
Code Sample 1:
private <T> Collection<T> loadProviders(final Class<T> providerClass) throws ModelException { try { final String providerNamePrefix = providerClass.getName() + "."; final Map<String, T> providers = new TreeMap<String, T>(new Comparator<String>() { public int compare(final String key1, final String key2) { return key1.compareTo(key2); } }); final File platformProviders = new File(this.getPlatformProviderLocation()); if (platformProviders.exists()) { if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("processing", platformProviders.getAbsolutePath()), null); } InputStream in = null; boolean suppressExceptionOnClose = true; final java.util.Properties p = new java.util.Properties(); try { in = new FileInputStream(platformProviders); p.load(in); suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (suppressExceptionOnClose) { this.log(Level.SEVERE, getMessage(e), e); } else { throw e; } } } for (Map.Entry<Object, Object> e : p.entrySet()) { if (e.getKey().toString().startsWith(providerNamePrefix)) { final String configuration = e.getValue().toString(); if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("providerInfo", platformProviders.getAbsolutePath(), providerClass.getName(), configuration), null); } providers.put(e.getKey().toString(), this.createProviderObject(providerClass, configuration, platformProviders.toURI().toURL())); } } } final Enumeration<URL> classpathProviders = this.findResources(this.getProviderLocation() + '/' + providerClass.getName()); int count = 0; final long t0 = System.currentTimeMillis(); while (classpathProviders.hasMoreElements()) { count++; final URL url = classpathProviders.nextElement(); if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("processing", url.toExternalForm()), null); } BufferedReader reader = null; boolean suppressExceptionOnClose = true; try { reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { if (line.contains("#")) { continue; } if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("providerInfo", url.toExternalForm(), providerClass.getName(), line), null); } providers.put(providerNamePrefix + providers.size(), this.createProviderObject(providerClass, line, url)); } suppressExceptionOnClose = false; } finally { try { if (reader != null) { reader.close(); } } catch (final IOException e) { if (suppressExceptionOnClose) { this.log(Level.SEVERE, getMessage(e), e); } else { throw new ModelException(getMessage(e), e); } } } } if (this.isLoggable(Level.FINE)) { this.log(Level.FINE, getMessage("contextReport", count, this.getProviderLocation() + '/' + providerClass.getName(), Long.valueOf(System.currentTimeMillis() - t0)), null); } return providers.values(); } catch (final IOException e) { throw new ModelException(getMessage(e), e); } }
Code Sample 2:
private HttpURLConnection prepare(URL url, String method) { if (this.username != null && this.password != null) { this.headers.put("Authorization", "Basic " + Codec.encodeBASE64(this.username + ":" + this.password)); } try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); checkFileBody(connection); connection.setRequestMethod(method); for (String key : this.headers.keySet()) { connection.setRequestProperty(key, headers.get(key)); } return connection; } catch (Exception e) { throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
public void execute() { File sourceFile = new File(oarfilePath); File destinationFile = new File(deploymentDirectory + File.separator + sourceFile.getName()); try { FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destinationFile); byte[] readArray = new byte[2048]; while (fis.read(readArray) != -1) { fos.write(readArray); } fis.close(); fos.flush(); fos.close(); } catch (IOException ioe) { logger.severe("failed to copy the file:" + ioe); } }
Code Sample 2:
private void storeFieldMap(WorkingContent c, Connection conn) throws SQLException { SQLDialect dialect = getDatabase().getSQLDialect(); if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(false); } try { Object thisKey = c.getPrimaryKey(); deleteFieldContent(thisKey, conn); PreparedStatement ps = null; StructureItem nextItem; Map fieldMap = c.getFieldMap(); String type; Object value, siKey; for (Iterator i = c.getStructure().getStructureItems().iterator(); i.hasNext(); ) { nextItem = (StructureItem) i.next(); type = nextItem.getDataType().toUpperCase(); siKey = nextItem.getPrimaryKey(); value = fieldMap.get(nextItem.getName()); try { if (type.equals(StructureItem.DATE)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_DATE_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); dialect.setDate(ps, 3, (Date) value); ps.executeUpdate(); } else if (type.equals(StructureItem.INT) || type.equals(StructureItem.FLOAT) || type.equals(StructureItem.VARCHAR)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_" + type + "_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); if (value != null) { ps.setObject(3, value); } else { int sqlType = Types.INTEGER; if (type.equals(StructureItem.FLOAT)) { sqlType = Types.FLOAT; } else if (type.equals(StructureItem.VARCHAR)) { sqlType = Types.VARCHAR; } ps.setNull(3, sqlType); } ps.executeUpdate(); } else if (type.equals(StructureItem.TEXT)) { setTextField(c, siKey, (String) value, conn); } if (ps != null) { ps.close(); ps = null; } } finally { if (ps != null) ps.close(); } } if (TRANSACTIONS_ENABLED) { conn.commit(); } } catch (SQLException e) { if (TRANSACTIONS_ENABLED) { conn.rollback(); } throw e; } finally { if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(true); } } }
|
00
|
Code Sample 1:
private int getRootNodeId(DataSource dataSource) throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; String query = null; try { conn = dataSource.getConnection(); st = conn.createStatement(); query = "select " + col.id + " from " + DB.Tbl.tree + " where " + col.parentId + " is null"; rs = st.executeQuery(query); while (rs.next()) { return rs.getInt(col.id); } query = "insert into " + DB.Tbl.tree + "(" + col.lKey + ", " + col.rKey + ", " + col.level + ") values(1,2,0)"; st.executeUpdate(query, new String[] { col.id }); rs = st.getGeneratedKeys(); while (rs.next()) { int genId = rs.getInt(1); rs.close(); conn.commit(); return genId; } throw new SQLException("Не удается создать корневой элемент для дерева."); } finally { try { rs.close(); } catch (Exception e) { } try { st.close(); } catch (Exception e) { } try { conn.rollback(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } } }
Code Sample 2:
public static void loadPlugins() { Logger.trace("Loading plugins"); Enumeration<URL> urls = null; try { urls = Play.classloader.getResources("play.plugins"); } catch (Exception e) { } while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); Logger.trace("Found one plugins descriptor, %s", url); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { String[] infos = line.split(":"); PlayPlugin plugin = (PlayPlugin) Play.classloader.loadClass(infos[1].trim()).newInstance(); Logger.trace("Loaded plugin %s", plugin); plugin.index = Integer.parseInt(infos[0]); plugins.add(plugin); } } catch (Exception ex) { Logger.error(ex, "Cannot load %s", url); } } Collections.sort(plugins); for (PlayPlugin plugin : new ArrayList<PlayPlugin>(plugins)) { plugin.onLoad(); } }
|
00
|
Code Sample 1:
private boolean importTablesData(Connection conn) { try { boolean status = true; boolean autoCommit = conn.getAutoCommit(); conn.setAutoCommit(false); String dbType = this.getFromSession("database"); List statements = ParseDBDumpFile.parse(SystemGlobals.getValue(ConfigKeys.CONFIG_DIR) + "/database/" + dbType + "/" + dbType + "_data_dump.sql"); for (Iterator iter = statements.iterator(); iter.hasNext(); ) { String query = (String) iter.next(); if (query == null || "".equals(query.trim())) { continue; } query = query.trim(); Statement s = conn.createStatement(); try { if (query.startsWith("UPDATE") || query.startsWith("INSERT") || query.startsWith("SET")) { s.executeUpdate(query); } else if (query.startsWith("SELECT")) { s.executeQuery(query); } else { throw new SQLException("Invalid query: " + query); } } catch (SQLException ex) { status = false; conn.rollback(); logger.error("Error importing data for " + query + ": " + ex, ex); this.context.put("exceptionMessage", ex.getMessage() + "\n" + query); break; } finally { s.close(); } } conn.setAutoCommit(autoCommit); return status; } catch (Exception e) { throw new ForumException(e); } }
Code Sample 2:
public static String getMD5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.toLowerCase().getBytes()); return HexString.bufferToHex(md5.digest()); } catch (NoSuchAlgorithmException e) { System.err.println("Error grave al inicializar MD5"); e.printStackTrace(); return "!!"; } }
|
00
|
Code Sample 1:
public static void main(String[] args) { if (args.length == 0) { System.out.println("Specify name of the file, just one entry per line"); System.exit(0); } File inFile = new File(args[0]); BufferedReader myBR = null; File outFile = new File(args[0] + ".xml"); BufferedWriter myBW = null; try { myBR = new BufferedReader(new FileReader(inFile)); myBW = new BufferedWriter(new FileWriter(outFile)); } catch (Exception ex) { System.out.println("IN: " + inFile.getAbsolutePath()); System.out.println("OUT: " + outFile.getAbsolutePath()); ex.printStackTrace(); System.exit(0); } try { String readLine; while ((readLine = myBR.readLine()) != null) { myBW.write("<dbColumn name=\"" + readLine + "\" display=\"" + readLine + "\" panel=\"CENTER\" >"); myBW.write("\n"); myBW.write("<dbType name=\"text\" maxVal=\"10\" defaultVal=\"\" sizeX=\"5\"/>"); myBW.write("\n"); myBW.write("</dbColumn>"); myBW.write("\n"); } myBW.close(); myBR.close(); } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } System.out.println("OUT: " + outFile.getAbsolutePath()); System.out.println("erzeugt"); }
Code Sample 2:
public Document createDocument(String uri) throws IOException { ParsedURL purl = new ParsedURL(uri); InputStream is = purl.openStream(MimeTypeConstants.MIME_TYPES_SVG); InputSource isrc = new InputSource(is); String contentType = purl.getContentType(); int cindex = -1; if (contentType != null) { contentType = contentType.toLowerCase(); cindex = contentType.indexOf(HTTP_CHARSET); } if (cindex != -1) { int i = cindex + HTTP_CHARSET.length(); int eqIdx = contentType.indexOf('=', i); if (eqIdx != -1) { eqIdx++; String charset; int idx = contentType.indexOf(',', eqIdx); int semiIdx = contentType.indexOf(';', eqIdx); if ((semiIdx != -1) && ((semiIdx < idx) || (idx == -1))) idx = semiIdx; if (idx != -1) charset = contentType.substring(eqIdx, idx); else charset = contentType.substring(eqIdx); isrc.setEncoding(charset.trim()); } } isrc.setSystemId(uri); Document doc = super.createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", uri, isrc); try { ((SVGOMDocument) doc).setURLObject(new URL(purl.toString())); } catch (MalformedURLException mue) { throw new IOException("Malformed URL: " + uri); } return doc; }
|
11
|
Code Sample 1:
@Override public void createCopy(File sourceFile, File destinnationFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinnationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static void copyFile(String fileName, String dstPath) throws IOException { FileChannel sourceChannel = new FileInputStream(fileName).getChannel(); FileChannel destinationChannel = new FileOutputStream(dstPath).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
@Override public User updateUser(User bean) throws SitoolsException { checkUser(); Connection cx = null; try { cx = ds.getConnection(); cx.setAutoCommit(false); PreparedStatement st; int i = 1; if (bean.getSecret() != null && !"".equals(bean.getSecret())) { st = cx.prepareStatement(jdbcStoreResource.UPDATE_USER_WITH_PW); st.setString(i++, bean.getFirstName()); st.setString(i++, bean.getLastName()); st.setString(i++, bean.getSecret()); st.setString(i++, bean.getEmail()); st.setString(i++, bean.getIdentifier()); } else { st = cx.prepareStatement(jdbcStoreResource.UPDATE_USER_WITHOUT_PW); st.setString(i++, bean.getFirstName()); st.setString(i++, bean.getLastName()); st.setString(i++, bean.getEmail()); st.setString(i++, bean.getIdentifier()); } st.executeUpdate(); st.close(); if (bean.getProperties() != null) { deleteProperties(bean.getIdentifier(), cx); createProperties(bean, cx); } if (!cx.getAutoCommit()) { cx.commit(); } } catch (SQLException e) { try { cx.rollback(); } catch (SQLException e1) { throw new SitoolsException("UPDATE_USER ROLLBACK" + e1.getMessage(), e1); } throw new SitoolsException("UPDATE_USER " + e.getMessage(), e); } finally { closeConnection(cx); } return getUserById(bean.getIdentifier()); }
Code Sample 2:
public boolean restore() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/Android/bluebox.bak"; String backupDBPath = "/data/android.bluebox/databases/bluebox.db"; File currentDB = new File(sd, currentDBPath); File backupDB = new File(data, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
|
00
|
Code Sample 1:
public static int validate(String url) { HttpURLConnection con = null; try { con = (HttpURLConnection) (new URL(url)).openConnection(); } catch (MalformedURLException ex) { return -1; } catch (IOException ex) { return -2; } try { if (con != null && con.getResponseCode() != 200) { return con.getResponseCode(); } else if (con == null) { return -3; } } catch (IOException ex) { return -4; } return 1; }
Code Sample 2:
public void sorter() { String inputLine1, inputLine2; String epiNames[] = new String[1000]; String epiEpisodes[] = new String[1000]; int lineCounter = 0; try { String pluginDir = pluginInterface.getPluginDirectoryName(); String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt"; File episodeList = new File(eplist_file); if (!episodeList.isFile()) { episodeList.createNewFile(); } final BufferedReader in = new BufferedReader(new FileReader(episodeList)); while ((inputLine1 = in.readLine()) != null) { if ((inputLine2 = in.readLine()) != null) { epiNames[lineCounter] = inputLine1; epiEpisodes[lineCounter] = inputLine2; lineCounter++; } } in.close(); int epiLength = epiNames.length; for (int i = 0; i < (lineCounter); i++) { for (int j = 0; j < (lineCounter - 1); j++) { if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) { String temp = epiNames[j]; epiNames[j] = epiNames[j + 1]; epiNames[j + 1] = temp; String temp2 = epiEpisodes[j]; epiEpisodes[j] = epiEpisodes[j + 1]; epiEpisodes[j + 1] = temp2; } } } File episodeList2 = new File(eplist_file); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2)); for (int i = 0; i <= lineCounter; i++) { if (epiNames[i] == null) { break; } bufWriter.write(epiNames[i] + "\n"); bufWriter.write(epiEpisodes[i] + "\n"); } bufWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public void method31() { boolean flag = true; while (flag) { flag = false; for (int i = 0; i < anInt772 - 1; i++) if (anIntArray774[i] < anIntArray774[i + 1]) { int j = anIntArray774[i]; anIntArray774[i] = anIntArray774[i + 1]; anIntArray774[i + 1] = j; long l = aLongArray773[i]; aLongArray773[i] = aLongArray773[i + 1]; aLongArray773[i + 1] = l; flag = true; } } }
Code Sample 2:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) dir.mkdir(); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
11
|
Code Sample 1:
public static void copyFile(String source, String destination, TimeSlotTracker timeSlotTracker) { LOG.info("copying [" + source + "] to [" + destination + "]"); BufferedInputStream sourceStream = null; BufferedOutputStream destStream = null; try { File destinationFile = new File(destination); if (destinationFile.exists()) { destinationFile.delete(); } sourceStream = new BufferedInputStream(new FileInputStream(source)); destStream = new BufferedOutputStream(new FileOutputStream(destinationFile)); int readByte; while ((readByte = sourceStream.read()) > 0) { destStream.write(readByte); } Object[] arg = { destinationFile.getName() }; String msg = timeSlotTracker.getString("datasource.xml.copyFile.copied", arg); LOG.fine(msg); } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } finally { try { if (destStream != null) { destStream.close(); } if (sourceStream != null) { sourceStream.close(); } } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } } }
Code Sample 2:
public void end() throws Exception { handle.waitFor(); Calendar endTime = Calendar.getInstance(); File resultsDir = new File(runDir, "results"); if (!resultsDir.isDirectory()) throw new Exception("The results directory not found!"); String resHtml = null; String resTxt = null; String[] resultFiles = resultsDir.list(); for (String resultFile : resultFiles) { if (resultFile.indexOf("html") >= 0) resHtml = resultFile; else if (resultFile.indexOf("txt") >= 0) resTxt = resultFile; } if (resHtml == null) throw new IOException("SPECweb2005 output (html) file not found"); if (resTxt == null) throw new IOException("SPECweb2005 output (txt) file not found"); File resultHtml = new File(resultsDir, resHtml); copyFile(resultHtml.getAbsolutePath(), runDir + "SPECWeb-result.html", false); BufferedReader reader = new BufferedReader(new FileReader(new File(resultsDir, resTxt))); logger.fine("Text file: " + resultsDir + resTxt); Writer writer = new FileWriter(runDir + "summary.xml"); SummaryParser parser = new SummaryParser(getRunId(), startTime, endTime, logger); parser.convert(reader, writer); writer.close(); reader.close(); }
|
11
|
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(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } 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:
public static List<String> getServers() throws Exception { List<String> servers = new ArrayList<String>(); URL url = new URL("http://tfast.org/en/servers.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { if (line.contains("serv=")) { int i = line.indexOf("serv="); servers.add(line.substring(i + 5, line.indexOf("\"", i))); } } in.close(); return servers; }
|
11
|
Code Sample 1:
public static void copy(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 void invoke(InputStream is) throws AgentException { try { addHeader("Content-Type", "application/zip"); addHeader("Content-Length", String.valueOf(is.available())); connection.setDoOutput(true); connection.connect(); OutputStream os = connection.getOutputStream(); boolean success = false; try { IOUtils.copy(is, os); success = true; } finally { try { os.flush(); os.close(); } catch (IOException x) { if (success) throw x; } } connection.disconnect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new AgentException("Failed to execute REST call at " + connection.getURL() + ": " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (ConnectException e) { throw new AgentException("Failed to connect to beehive at " + connection.getURL()); } catch (IOException e) { throw new AgentException("Failed to connect to beehive", e); } }
|
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 createTableIfNotExisting(Connection conn) throws SQLException { String sql = "select * from " + tableName; PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.executeQuery(); } catch (SQLException sqle) { ps.close(); sql = "create table " + tableName + " ( tableName varchar(255) not null primary key, " + " lastId numeric(18) not null)"; ps = conn.prepareStatement(sql); ps.executeUpdate(); } finally { ps.close(); try { if (!conn.getAutoCommit()) conn.commit(); } catch (Exception e) { conn.rollback(); } } }
|
11
|
Code Sample 1:
private String createDefaultRepoConf() throws IOException { InputStream confIn = getClass().getResourceAsStream(REPO_CONF_PATH); File tempConfFile = File.createTempFile("repository", "xml"); tempConfFile.deleteOnExit(); IOUtils.copy(confIn, new FileOutputStream(tempConfFile)); return tempConfFile.getAbsolutePath(); }
Code Sample 2:
protected HttpResponseImpl makeRequest(final HttpMethod m, final String requestId) { try { HttpResponseImpl ri = new HttpResponseImpl(); ri.setRequestMethod(m); ri.setResponseCode(_client.executeMethod(m)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(m.getResponseBodyAsStream(), bos); ri.setResponseBody(bos.toByteArray()); notifyOfRequestSuccess(requestId, m, ri); return ri; } catch (HttpException ex) { notifyOfRequestFailure(requestId, m, ex); } catch (IOException ex) { notifyOfRequestFailure(requestId, m, ex); } return null; }
|
11
|
Code Sample 1:
public void bubbleSort(int[] arr) { BasicProcessor.getInstance().getStartBlock(); BasicProcessor.getInstance().getVarDeclaration(); boolean swapped = true; BasicProcessor.getInstance().getVarDeclaration(); int j = 0; BasicProcessor.getInstance().getVarDeclaration(); int tmp; { BasicProcessor.getInstance().getWhileStatement(); while (swapped) { BasicProcessor.getInstance().getStartBlock(); swapped = false; j++; { BasicProcessor.getInstance().getForStatement(); for (int i = 0; i < arr.length - j; i++) { BasicProcessor.getInstance().getStartBlock(); { BasicProcessor.getInstance().getIfStatement(); if (arr[i] > arr[i + 1]) { BasicProcessor.getInstance().getStartBlock(); tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); }
Code Sample 2:
private void sortWhats(String[] labels, int[] whats, String simplifyString) { int n = whats.length; boolean swapped; do { swapped = false; for (int i = 0; i < n - 1; i++) { int i0_pos = simplifyString.indexOf(labels[whats[i]]); int i1_pos = simplifyString.indexOf(labels[whats[i + 1]]); if (i0_pos > i1_pos) { int temp = whats[i]; whats[i] = whats[i + 1]; whats[i + 1] = temp; swapped = true; } } } while (swapped); }
|
11
|
Code Sample 1:
public 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 File copyFileAs(String path, String newName) { File src = new File(path); File dest = new File(newName); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
|
00
|
Code Sample 1:
public void setRandom(boolean random) { this.random = random; if (random) { possibleScores = new int[NUM_SCORES]; for (int i = 0; i < NUM_SCORES - 1; i++) { getRandomScore: while (true) { int score = (int) (Math.random() * 20) + 1; for (int j = 0; j < i; j++) { if (score == possibleScores[j]) { continue getRandomScore; } } possibleScores[i] = score; break; } } possibleScores[NUM_SCORES - 1] = 25; boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < NUM_SCORES - 1; i++) { if (possibleScores[i] > possibleScores[i + 1]) { int t = possibleScores[i]; possibleScores[i] = possibleScores[i + 1]; possibleScores[i + 1] = t; sorted = false; } } } setPossibleScores(possibleScores); } }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
00
|
Code Sample 1:
public void run() { StringBuffer xml; String tabName; Element guiElement; setBold(monitor.getReading()); setBold(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Working"); HttpMethod method = null; xml = new StringBuffer(); File tempfile = new File(url); if (tempfile.exists()) { try { InputStream in = new FileInputStream(tempfile); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading XML file from local file"); e.printStackTrace(System.err); return; } } else { try { HttpClient client = new HttpClient(); method = new GetMethod(url); int response = client.executeMethod(method); if (response == 200) { InputStream in = method.getResponseBodyAsStream(); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } else { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed. Incorrect response from HTTP Server " + response); return; } } catch (IOException e) { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed, error while reading XML file from HTTP Server"); e.printStackTrace(System.err); return; } } setPlain(monitor.getReading()); setPlain(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Done"); setBold(monitor.getValidating()); setBold(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Working"); DocumentBuilderFactoryImpl factory = new DocumentBuilderFactoryImpl(); try { DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(new ByteArrayInputStream(xml.toString().getBytes())); if (method != null) { method.releaseConnection(); } Element root = document.getDocumentElement(); NodeList temp = root.getElementsByTagName("resource"); for (int j = 0; j < temp.getLength(); j++) { Element resource = (Element) temp.item(j); resources.add(new URL(resource.getAttribute("url"))); } NodeList connections = root.getElementsByTagName("jmxserver"); for (int j = 0; j < connections.getLength(); j++) { Element connection = (Element) connections.item(j); String name = connection.getAttribute("name"); String tempUrl = connection.getAttribute("url"); String auth = connection.getAttribute("auth"); if (tempUrl.indexOf("${host}") != -1) { HostDialog dialog = new HostDialog(Config.getHosts()); String host = dialog.showDialog(); if (host == null) { System.out.println("Host can not be null, unable to create panel."); return; } tempUrl = tempUrl.replaceAll("\\$\\{host\\}", host); Config.addHost(host); } JMXServiceURL jmxUrl = new JMXServiceURL(tempUrl); JmxServerGraph server = new JmxServerGraph(name, jmxUrl, new JmxWorker(false)); if (auth != null && auth.equalsIgnoreCase("true")) { LoginTrueService loginService = new LoginTrueService(); JXLoginPanel.Status status = JXLoginPanel.showLoginDialog(null, loginService); if (status != JXLoginPanel.Status.SUCCEEDED) { return; } server.setUsername(loginService.getName()); server.setPassword(loginService.getPassword()); } servers.put(name, server); NodeList listeners = connection.getElementsByTagName("listener"); for (int i = 0; i < listeners.getLength(); i++) { Element attribute = (Element) listeners.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String filtertype = attribute.getAttribute("filterType"); TaskNotificationListener listener = new TaskNotificationListener(); NotificationFilterSupport filter = new NotificationFilterSupport(); if (filtertype == null || "".equals(filtertype)) { filter = null; } else { filter.enableType(filtertype); } Task task = new Task(-1, Task.LISTEN, server); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); } NodeList attributes = connection.getElementsByTagName("attribute"); for (int i = 0; i < attributes.getLength(); i++) { Element attribute = (Element) attributes.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String attributename = attribute.getAttribute("attributename"); String frequency = attribute.getAttribute("frequency"); String onEvent = attribute.getAttribute("onEvent"); if (frequency.equalsIgnoreCase("onchange")) { TaskNotificationListener listener = new TaskNotificationListener(); AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter(); filter.enableAttribute(attributename); Task task = new Task(-1, Task.LISTEN, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } Task task2 = new Task(-1, Task.GET_ATTRIBUTE, server); task2.setAttribute(att); task2.setMbean(mbean); server.getWorker().addTask(task2); List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); hashTempList.add(task2); tasks.put(taskname, hashTempList); } else { int frequency2 = Integer.parseInt(frequency); Task task = new Task(frequency2, Task.GET_ATTRIBUTE, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); TaskNotificationListener listener = null; if (onEvent != null && !"".equals(onEvent)) { Task tempTask = tasks.get(onEvent).get(0); if (tempTask == null) { System.out.println(onEvent + " was not found."); return; } else { listener = (TaskNotificationListener) tempTask.getListener(); } } if (listener == null) { server.getWorker().addTask(task); } else { listener.addTask(task); } } } } NodeList guiTemp = root.getElementsByTagName("gui"); guiElement = (Element) guiTemp.item(0); tabName = guiElement.getAttribute("name"); if (MonitorServer.contains(tabName)) { JOptionPane.showMessageDialog(null, "This panel is already open, stoping creating of panel.", "Panel already exists", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setTitleAt(i, tabName); break; } } NodeList tempBindings = root.getElementsByTagName("binding"); for (int i = 0; i < tempBindings.getLength(); i++) { Element binding = (Element) tempBindings.item(i); String guiname = binding.getAttribute("guiname"); String tmethod = binding.getAttribute("method"); String taskname = binding.getAttribute("taskname"); String formater = binding.getAttribute("formater"); BindingContainer tempBinding; if (formater == null || (formater != null && formater.equals(""))) { tempBinding = new BindingContainer(guiname, tmethod, taskname); } else { tempBinding = new BindingContainer(guiname, tmethod, taskname, formater); } bindings.add(tempBinding); } } catch (Exception e) { System.err.println("Exception message: " + e.getMessage()); System.out.println("Loading Monitor Failed, couldnt parse XML file."); e.printStackTrace(System.err); return; } setPlain(monitor.getValidating()); setPlain(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Done"); setBold(monitor.getDownload()); setBold(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Working"); List<File> jarFiles = new ArrayList<File>(); File cacheDir = new File(Config.getCacheDir()); if (!cacheDir.exists()) { cacheDir.mkdir(); } for (URL resUrl : resources) { try { HttpClient client = new HttpClient(); HttpMethod methodRes = new GetMethod(resUrl.toString()); int response = client.executeMethod(methodRes); if (response == 200) { int index = resUrl.toString().lastIndexOf("/") + 1; File file = new File(Config.getCacheDir() + resUrl.toString().substring(index)); FileOutputStream out = new FileOutputStream(file); InputStream in = methodRes.getResponseBodyAsStream(); int readTemp = 0; while ((readTemp = in.read()) != -1) { out.write(readTemp); } System.out.println(file.getName() + " downloaded."); methodRes.releaseConnection(); if (file.getName().endsWith(".jar")) { jarFiles.add(file); } } else { methodRes.releaseConnection(); System.out.println("Loading Monitor Failed. Unable to get resource " + url); return; } } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading resource file " + "from HTTP Server"); e.printStackTrace(System.err); return; } } URL[] urls = new URL[jarFiles.size()]; try { for (int i = 0; i < jarFiles.size(); i++) { File file = jarFiles.get(i); File newFile = new File(Config.getCacheDir() + "/" + System.currentTimeMillis() + file.getName()); FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(newFile); int n = 0; byte[] buf = new byte[1024]; while ((n = in.read(buf, 0, 1024)) > -1) { out.write(buf, 0, n); } out.close(); out.close(); in.close(); urls[i] = new URL("file:" + newFile.getAbsolutePath()); } } catch (Exception e1) { System.out.println("Unable to load jar files."); e1.printStackTrace(); } URLClassLoader loader = new URLClassLoader(urls); engine.setClassLoader(loader); setPlain(monitor.getDownload()); setPlain(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Done"); setBold(monitor.getGui()); setBold(monitor.getGuiStatus()); monitor.getGuiStatus().setText(" Working"); Container container; try { String tempXml = xml.toString(); int start = tempXml.indexOf("<gui"); start = tempXml.indexOf('>', start) + 1; int end = tempXml.indexOf("</gui>"); container = engine.render(new StringReader(tempXml.substring(start, end))); } catch (Exception e) { e.printStackTrace(System.err); System.err.println("Exception msg: " + e.getMessage()); System.out.println("Loading Monitor Failed, error creating gui."); return; } for (BindingContainer bcon : bindings) { List<Task> temp = tasks.get(bcon.getTask()); if (temp == null) { System.out.println("Task with name " + bcon.getTask() + " doesnt exist."); } else { for (Task task : temp) { if (task != null) { Object comp = engine.find(bcon.getComponent()); if (comp != null) { if (task.getTaskType() == Task.LISTEN && task.getFilter() instanceof AttributeChangeNotificationFilter) { TaskNotificationListener listener = (TaskNotificationListener) task.getListener(); if (bcon.getFormater() == null) { listener.addResultListener(new Binding(comp, bcon.getMethod())); } else { listener.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } else { if (bcon.getFormater() == null) { task.addResultListener(new Binding(comp, bcon.getMethod())); } else { task.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } } else { System.out.println("Refering to gui name, " + bcon.getComponent() + ", that doesnt exist. Unable to create monitor."); return; } } else { System.out.println("Refering to task name, " + bcon.getTask() + ", that doesnt exist. Unable to create monitor."); return; } } } } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setComponentAt(i, new MonitorContainerPanel(container, this)); break; } } System.out.println("Connecting to server(s)."); Enumeration e = servers.keys(); List<JmxWorker> list = new ArrayList<JmxWorker>(); while (e.hasMoreElements()) { JmxWorker worker = servers.get(e.nextElement()).getWorker(); worker.setRunning(true); worker.start(); list.add(worker); } MonitorServer.add(tabName, list); Config.addUrl(url); }
Code Sample 2:
public void run() throws Exception { logger.debug("#run enter"); PreparedStatement ps = null; try { connection.setAutoCommit(false); ps = connection.prepareStatement(SQL_UPDATE_ITEM_MIN_QTTY); ps.setInt(1, deliveryId); ps.setInt(2, deliveryId); ps.executeUpdate(); ps.close(); logger.debug("#run update STORE.ITEM ok"); ps = connection.prepareStatement(SQL_DELETE_DELIVERY_LINE); ps.setInt(1, deliveryId); ps.executeUpdate(); ps.close(); logger.debug("#run delete STORE.DELIVERY_LINE ok"); ps = connection.prepareStatement(SQL_DELETE_DELIVERY); ps.setInt(1, deliveryId); ps.executeUpdate(); ps.close(); logger.debug("#run delete STORE.DELIVERY ok"); connection.commit(); } catch (Exception ex) { logger.error("#run Transaction roll back ", ex); connection.rollback(); throw new Exception("#run Не удалось загрузить в БД информацию об обновлении склада. Ошибка : " + ex.getMessage()); } finally { connection.setAutoCommit(true); } logger.debug("#run exit"); }
|
11
|
Code Sample 1:
public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("GET REQUEST OR RESPONSE - Send content: " + file.getAbsolutePath()); FileInputStream in = null; try { in = new FileInputStream(file); int bytes = IOUtils.copy(in, out); LOGGER.debug("wrote bytes: " + bytes); out.flush(); } finally { IOUtils.closeQuietly(in); } }
Code Sample 2:
public static void rewrite(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new FileInputStream(args[0])); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); CodeAttribute attribute = method.getCodeAttribute(); int origStack = attribute.getMaxStack(); System.out.print(method.getName()); attribute.codeCheck(); System.out.println(" " + origStack + " " + attribute.getMaxStack()); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); }
|
11
|
Code Sample 1:
public static void _save(PortletRequest req, PortletResponse res, PortletConfig config, ActionForm form) throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(UserManagerPropertiesFactory.class, "Property File save Failed " + e, e); } SessionMessages.add(req, "message", "message.usermanager.display.save"); }
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:
private void fillTemplate(String resource, OutputStream outputStream, Map<String, String> replacements) throws IOException { URL url = Tools.getResource(resource); if (url == null) { throw new IOException("could not find resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8"))); String line = null; do { line = reader.readLine(); if (line != null) { for (String key : replacements.keySet()) { String value = replacements.get(key); if (key != null) { line = line.replace(key, value); } } writer.write(line); writer.newLine(); } } while (line != null); reader.close(); writer.close(); }
Code Sample 2:
public String get(String url) { String buf = null; StringBuilder resultBuffer = new StringBuilder(512); if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(url)>> " + url); try { URL theURL = new URL(url); URLConnection urlConn = theURL.openConnection(); urlConn.setDoOutput(true); urlConn.setReadTimeout(timeOut); BufferedReader urlReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); do { buf = urlReader.readLine(); if (buf != null) { resultBuffer.append(buf); resultBuffer.append("\n"); } } while (buf != null); urlReader.close(); if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(output)>> " + resultBuffer.toString()); int xmlNdx = resultBuffer.lastIndexOf("?>"); if (xmlNdx == -1) result = resultBuffer.toString(); else result = resultBuffer.substring(xmlNdx + 2); } catch (Exception e) { result = debug.logger("gov.llnl.tox.util.href", "error: get >> ", e); } return (result); }
|
00
|
Code Sample 1:
private static String GetSHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return LoginHttpPostProcessor.ConvertToHex(sha1hash); }
Code Sample 2:
public void checkFilesAndCopyValid(String filename) { downloadResults(); loadResults(); File tmpFolderF = new File(tmpFolder); deleteFileFromTMPFolder(tmpFolderF); ZipReader zr = new ZipReader(); zr.UnzipFile(filename); try { LogManager.getInstance().log("Ov��uji odevzdan� soubory a kop�ruji validovan�:"); LogManager.getInstance().log(""); JAXBElement<?> element = ElementJAXB.getJAXBElement(); Ppa1VysledkyCviceniType pvct = (Ppa1VysledkyCviceniType) element.getValue(); File zipFolder = new File(tmpFolder).listFiles()[0].listFiles()[0].listFiles()[0]; File[] zipFolderList = zipFolder.listFiles(); for (File studentDirectory : zipFolderList) { if (studentDirectory.isDirectory()) { String osobniCisloZeSlozky = studentDirectory.getName().split("-")[0]; LogManager.getInstance().changeLog("Prov��ov�n� soubor� studenta s ��slem: " + osobniCisloZeSlozky); List<StudentType> students = (List<StudentType>) pvct.getStudent(); for (StudentType student : students) { if (student.getOsobniCislo().equals(osobniCisloZeSlozky)) { int pzp = student.getDomaciUlohy().getPosledniZpracovanyPokus().getCislo().intValue(); DomaciUlohyType dut = student.getDomaciUlohy(); ChybneOdevzdaneType chot = dut.getChybneOdevzdane(); ObjectFactory of = new ObjectFactory(); File[] pokusyDirectories = studentDirectory.listFiles(); NodeList souboryNL = result.getElementsByTagName("soubor"); int start = souboryNL.getLength() - 1; boolean samostatnaPrace = false; for (int i = (pokusyDirectories.length - 1); i >= 0; i--) { if ((pokusyDirectories[i].isDirectory()) && (pzp < Integer.parseInt(pokusyDirectories[i].getName().split("_")[1].trim()))) { File testedFile = pokusyDirectories[i].listFiles()[0]; if ((testedFile.exists()) && (testedFile.isFile())) { String[] partsOfFilename = testedFile.getName().split("_"); String osobniCisloZeSouboru = "", priponaSouboru = ""; String[] posledniCastSouboru = null; if (partsOfFilename.length == 4) { posledniCastSouboru = partsOfFilename[3].split("[.]"); osobniCisloZeSouboru = posledniCastSouboru[0]; if (posledniCastSouboru.length <= 1) priponaSouboru = ""; else priponaSouboru = posledniCastSouboru[1]; } String samostatnaPraceNazev = Konfigurace.getInstance().getSamostatnaPraceNazev(); List<SouborType> lst = chot.getSoubor(); if (testedFile.getName().startsWith(samostatnaPraceNazev)) { samostatnaPrace = true; } else { samostatnaPrace = false; if (partsOfFilename.length != 4) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� struktura jm�na souboru."); lst.add(st); continue; } else if (!testedFile.getName().startsWith("Ppa1_cv")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� za��tek jm�na souboru."); lst.add(st); continue; } else if (!priponaSouboru.equals("java")) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("�patn� p��pona souboru."); lst.add(st); continue; } else if (!osobniCisloZeSouboru.equals(osobniCisloZeSlozky)) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Nesouhlas� osobn� ��sla."); lst.add(st); continue; } else if (partsOfFilename[3].split("[.]").length > 2) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("V�ce p��pon souboru."); lst.add(st); continue; } else { long cisloCviceni, cisloUlohy; try { if (partsOfFilename[1].length() == 4) { String cisloS = partsOfFilename[1].substring(2); long cisloL = Long.parseLong(cisloS); cisloCviceni = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo cvi�en�"); lst.add(st); continue; } try { if (partsOfFilename[2].length() > 0) { String cisloS = partsOfFilename[2]; long cisloL = Long.parseLong(cisloS); cisloUlohy = cisloL; } else { throw new NumberFormatException(); } } catch (NumberFormatException e) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Chyb� (nebo je chybn�) ��slo �lohy"); lst.add(st); continue; } CislaUloh ci = new CislaUloh(); List<long[]> cviceni = ci.getSeznamCviceni(); boolean nalezenoCv = false, nalezenaUl = false; for (long[] c : cviceni) { if (c[0] == cisloCviceni) { for (int j = 1; j < c.length; j++) { if (c[j] == cisloUlohy) { nalezenaUl = true; break; } } nalezenoCv = true; break; } } if (!nalezenoCv) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo cvi�en�"); lst.add(st); continue; } if (!nalezenaUl) { SouborType st = new SouborType(); st.setJmeno(testedFile.getName()); st.setDuvod("Neplatn� ��slo �lohy"); lst.add(st); continue; } } } } Calendar dateFromZipFile = null; File zipFile = new File(filename); if (zipFile.exists()) { String[] s = zipFile.getName().split("_"); if (s.length >= 3) { String[] date = s[1].split("-"), time = s[2].split("-"); dateFromZipFile = new GregorianCalendar(); dateFromZipFile.set(Integer.parseInt(date[0]), Integer.parseInt(date[1]) - 1, Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), 0); } } boolean shodaJmenaSouboru = false; String vysledekValidaceSouboru = ""; for (int j = start; j >= 0; j--) { NodeList vlastnostiSouboruNL = souboryNL.item(j).getChildNodes(); for (int k = 0; k < vlastnostiSouboruNL.getLength(); k++) { if (vlastnostiSouboruNL.item(k).getNodeName().equals("cas")) { String[] obsahElementuCas = vlastnostiSouboruNL.item(k).getTextContent().split(" "); String[] datumZElementu = obsahElementuCas[0].split("-"), casZElementu = obsahElementuCas[1].split("-"); Calendar datumACasZElementu = new GregorianCalendar(); datumACasZElementu.set(Integer.parseInt(datumZElementu[0]), Integer.parseInt(datumZElementu[1]) - 1, Integer.parseInt(datumZElementu[2]), Integer.parseInt(casZElementu[0]), Integer.parseInt(casZElementu[1]), Integer.parseInt(casZElementu[2])); if ((dateFromZipFile != null) && (datumACasZElementu.compareTo(dateFromZipFile) > 0)) { shodaJmenaSouboru = false; break; } } if (vlastnostiSouboruNL.item(k).getNodeName().equals("nazev")) { shodaJmenaSouboru = vlastnostiSouboruNL.item(k).getTextContent().equals(testedFile.getName()); } if (vlastnostiSouboruNL.item(k).getNodeName().equals("vysledek")) { vysledekValidaceSouboru = vlastnostiSouboruNL.item(k).getTextContent(); } } if (shodaJmenaSouboru) { start = --j; break; } } if (shodaJmenaSouboru && !samostatnaPrace) { boolean odevzdanoVcas = false; String cisloCviceniS = testedFile.getName().split("_")[1].substring(2); int cisloCviceniI = Integer.parseInt(cisloCviceniS); String cisloUlohyS = testedFile.getName().split("_")[2]; int cisloUlohyI = Integer.parseInt(cisloUlohyS); List<CviceniType> lct = student.getDomaciUlohy().getCviceni(); for (CviceniType ct : lct) { if (ct.getCislo().intValue() == cisloCviceniI) { MezniTerminOdevzdaniVcasType mtovt = ct.getMezniTerminOdevzdaniVcas(); Calendar mtovGC = new GregorianCalendar(); mtovGC.set(mtovt.getDatum().getYear(), mtovt.getDatum().getMonth() - 1, mtovt.getDatum().getDay(), 23, 59, 59); Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); if (fileTimeStamp.compareTo(mtovGC) <= 0) odevzdanoVcas = true; else odevzdanoVcas = false; List<UlohaType> lut = ct.getUloha(); for (UlohaType ut : lut) { if (ut.getCislo().intValue() == cisloUlohyI) { List<OdevzdanoType> lot = ut.getOdevzdano(); OdevzdanoType ot = of.createOdevzdanoType(); ot.setDatum(xmlGCDate); ot.setCas(xmlGCTime); OdevzdanoVcasType ovt = of.createOdevzdanoVcasType(); ovt.setVysledek(odevzdanoVcas); ValidatorType vt = of.createValidatorType(); vt.setVysledek(vysledekValidaceSouboru.equals("true")); ot.setOdevzdanoVcas(ovt); ot.setValidator(vt); lot.add(ot); if (vt.isVysledek()) { String test = String.format("%s%s%02d", validovane, File.separator, ct.getCislo().intValue()); if (!(new File(test).exists())) { LogManager.getInstance().log("Nebyla provedena p��prava soubor�. Chyb� slo�ka " + test.substring(Ppa1Cviceni.USER_DIR.length()) + "."); return; } else { copyValidFile(testedFile, ct.getCislo().intValue()); } } break; } } break; } } } else if (shodaJmenaSouboru && samostatnaPrace) { String[] partsOfFilename = testedFile.getName().split("_"); String[] partsOfLastPartOfFilename = partsOfFilename[partsOfFilename.length - 1].split("[.]"); String osobniCisloZeSouboru = partsOfLastPartOfFilename[0]; String priponaZeSouboru = partsOfLastPartOfFilename[partsOfLastPartOfFilename.length - 1]; if ((partsOfLastPartOfFilename.length == 2) && (priponaZeSouboru.equals("java"))) { if (student.getOsobniCislo().equals(osobniCisloZeSouboru)) { Calendar fileTimeStamp = new GregorianCalendar(); fileTimeStamp.setTimeInMillis(testedFile.lastModified()); String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-"); String[] casSouboru = String.format("%tT", fileTimeStamp).split(":"); XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED); List<UlozenoType> lut = student.getSamostatnaPrace().getUlozeno(); if (lut.isEmpty()) { File samostatnaPraceNewFile = new File(sp + File.separator + testedFile.getName()); if (samostatnaPraceNewFile.exists()) { samostatnaPraceNewFile.delete(); samostatnaPraceNewFile.createNewFile(); } String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(testedFile); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(samostatnaPraceNewFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); samostatnaPraceNewFile.setLastModified(testedFile.lastModified()); } UlozenoType ut = of.createUlozenoType(); ut.setDatum(xmlGCDate); ut.setCas(xmlGCTime); lut.add(0, ut); } } } } } PosledniZpracovanyPokusType pzpt = new PosledniZpracovanyPokusType(); String[] slozkaPoslednihoPokusu = pokusyDirectories[pokusyDirectories.length - 1].getName().split("_"); int cisloPokusu = Integer.parseInt(slozkaPoslednihoPokusu[slozkaPoslednihoPokusu.length - 1].trim()); pzpt.setCislo(new BigInteger(String.valueOf(cisloPokusu))); student.getDomaciUlohy().setPosledniZpracovanyPokus(pzpt); break; } } } } ElementJAXB.setJAXBElement(element); LogManager.getInstance().log("Ov��ov�n� a kop�rov�n� odevzdan�ch soubor� dokon�eno."); } catch (FileNotFoundException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (DatatypeConfigurationException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } catch (IOException e) { e.printStackTrace(); LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�."); } LogManager.getInstance().log("Maz�n� rozbalen�ch soubor� ..."); deleteFileFromTMPFolder(tmpFolderF); LogManager.getInstance().changeLog("Maz�n� rozbalen�ch soubor� ... OK"); }
|
00
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
public static void bubbleSort(int[] a) { for (int i = a.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (a[j] > a[j + 1]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } }
|
00
|
Code Sample 1:
private void doDecrypt(boolean createOutput) throws IOException { FileInputStream input = null; FileOutputStream output = null; File tempOutput = null; try { input = new FileInputStream(infile); String cipherBaseFilename = basename(infile); byte[] magic = new byte[MAGIC.length]; input.read(magic); for (int i = 0; i < MAGIC.length; i++) { if (MAGIC[i] != magic[i]) throw new IOException("Not a BORK file (bad magic number)"); } short version = readShort(input); if (version / 1000 > VERSION / 1000) throw new IOException("File created by an incompatible future version: " + version + " > " + VERSION); String cipherName = readString(input); Cipher cipher = createCipher(cipherName, createSessionKey(password, cipherBaseFilename)); CipherInputStream decryptedInput = new CipherInputStream(input, cipher); long headerCrc = Unsigned.promote(readInt(decryptedInput)); decryptedInput.resetCRC(); outfile = new File(outputDir, readString(decryptedInput)); if (!createOutput || outfile.exists()) { skipped = true; return; } tempOutput = File.createTempFile("bork", null, outputDir); tempOutput.deleteOnExit(); byte[] buffer = new byte[BUFFER_SIZE]; output = new FileOutputStream(tempOutput); int bytesRead; while ((bytesRead = decryptedInput.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); output = null; if (headerCrc != decryptedInput.getCRC()) { outfile = null; throw new IOException("CRC mismatch: password is probably incorrect"); } if (!tempOutput.renameTo(outfile)) throw new IOException("Failed to rename temp output file " + tempOutput + " to " + outfile); outfile.setLastModified(infile.lastModified()); } finally { close(input); close(output); if (tempOutput != null) tempOutput.delete(); } }
Code Sample 2:
public void modifyDecisionInstruction(int id, int condition, String frameSlot, String linkName, int objectId, String attribute, int positive, int negative) throws FidoDatabaseException, ObjectNotFoundException, InstructionNotFoundException { try { Connection conn = null; Statement stmt = null; try { if ((condition == ConditionalOperatorTable.CONTAINS_LINK) || (condition == ConditionalOperatorTable.NOT_CONTAINS_LINK)) { ObjectTable ot = new ObjectTable(); if (ot.contains(objectId) == false) throw new ObjectNotFoundException(objectId); } conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, positive) == false) throw new InstructionNotFoundException(positive); if (contains(stmt, negative) == false) throw new InstructionNotFoundException(negative); String sql = "update Instructions set Operator = " + condition + ", " + " FrameSlot = '" + frameSlot + "', " + " LinkName = '" + linkName + "', " + " ObjectId = " + objectId + ", " + " AttributeName = '" + attribute + "' " + "where InstructionId = " + id; stmt.executeUpdate(sql); InstructionGroupTable groupTable = new InstructionGroupTable(); groupTable.deleteInstruction(stmt, id); if (positive != -1) groupTable.addInstructionAt(stmt, id, 1, positive); if (negative != -1) groupTable.addInstructionAt(stmt, id, 2, negative); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
|
00
|
Code Sample 1:
private static String getRegistrationClasses() { CentralRegistrationClass c = new CentralRegistrationClass(); String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class"); try { Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); String file = url.getFile(); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest mf = jarConnection.getManifest(); Attributes attrs = (Attributes) mf.getAttributes(name); if (attrs != null) { String classes = attrs.getValue("RegistrationClasses"); return classes; } } } catch (IOException ex) { ex.printStackTrace(); } return ""; }
Code Sample 2:
int doOne(int bid, int tid, int aid, int delta) { int aBalance = 0; if (Conn == null) { incrementFailedTransactionCount(); return 0; } try { if (prepared_stmt) { pstmt1.setInt(1, delta); pstmt1.setInt(2, aid); pstmt1.executeUpdate(); pstmt1.clearWarnings(); pstmt2.setInt(1, aid); ResultSet RS = pstmt2.executeQuery(); pstmt2.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } pstmt3.setInt(1, delta); pstmt3.setInt(2, tid); pstmt3.executeUpdate(); pstmt3.clearWarnings(); pstmt4.setInt(1, delta); pstmt4.setInt(2, bid); pstmt4.executeUpdate(); pstmt4.clearWarnings(); pstmt5.setInt(1, tid); pstmt5.setInt(2, bid); pstmt5.setInt(3, aid); pstmt5.setInt(4, delta); pstmt5.executeUpdate(); pstmt5.clearWarnings(); } else { Statement Stmt = Conn.createStatement(); String Query = "UPDATE accounts "; Query += "SET Abalance = Abalance + " + delta + " "; Query += "WHERE Aid = " + aid; int res = Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "SELECT Abalance "; Query += "FROM accounts "; Query += "WHERE Aid = " + aid; ResultSet RS = Stmt.executeQuery(Query); Stmt.clearWarnings(); while (RS.next()) { aBalance = RS.getInt(1); } Query = "UPDATE tellers "; Query += "SET Tbalance = Tbalance + " + delta + " "; Query += "WHERE Tid = " + tid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "UPDATE branches "; Query += "SET Bbalance = Bbalance + " + delta + " "; Query += "WHERE Bid = " + bid; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Query = "INSERT INTO history(Tid, Bid, Aid, delta) "; Query += "VALUES ("; Query += tid + ","; Query += bid + ","; Query += aid + ","; Query += delta + ")"; Stmt.executeUpdate(Query); Stmt.clearWarnings(); Stmt.close(); } if (transactions) { Conn.commit(); } return aBalance; } catch (Exception E) { if (verbose) { System.out.println("Transaction failed: " + E.getMessage()); E.printStackTrace(); } incrementFailedTransactionCount(); if (transactions) { try { Conn.rollback(); } catch (SQLException E1) { } } } return 0; }
|
11
|
Code Sample 1:
public void run() { if (saveAsDialog == null) { saveAsDialog = new FileDialog(window.getShell(), SWT.SAVE); saveAsDialog.setFilterExtensions(saveAsTypes); } String outputFile = saveAsDialog.open(); if (outputFile != null) { Object inputFile = DataSourceSingleton.getInstance().getContainer().getWrapped(); InputStream in; try { if (inputFile instanceof URL) in = ((URL) inputFile).openStream(); else in = new FileInputStream((File) inputFile); OutputStream out = new FileOutputStream(outputFile); if (outputFile.endsWith("xml")) { int c; while ((c = in.read()) != -1) out.write(c); } else { PrintWriter pw = new PrintWriter(out); Element data = DataSourceSingleton.getInstance().getRawData(); writeTextFile(data, pw, -1); pw.close(); } in.close(); out.close(); } catch (MalformedURLException e1) { } catch (IOException e) { } } }
Code Sample 2:
public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
|
00
|
Code Sample 1:
@Override public void send() { BufferedReader in = null; StringBuffer result = new StringBuffer(); try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { result.append(str); } } catch (ConnectException ce) { logger.error("MockupExecutableCommand excute fail: " + ce.getMessage()); } catch (Exception e) { logger.error("MockupExecutableCommand excute fail: " + e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } }
Code Sample 2:
private String readWebpage() { BufferedReader in = null; StringBuffer sb = new StringBuffer(); try { URI uri = new URI("file:///www.vogella.de"); IProxyService proxyService = getProxyService(); IProxyData[] proxyDataForHost = proxyService.select(uri); for (IProxyData data : proxyDataForHost) { if (data.getHost() != null) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", data.getHost()); } if (data.getHost() != null) { System.setProperty("http.proxyPort", String.valueOf(data.getPort())); } } proxyService = null; URL url; url = uri.toURL(); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine + "\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); }
|
00
|
Code Sample 1:
public static String md5(String text) { String hashed = ""; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes(), 0, text.length()); hashed = new BigInteger(1, digest.digest()).toString(16); } catch (Exception e) { Log.e(ctGlobal.tag, "ctCommon.md5: " + e.toString()); } return hashed; }
Code Sample 2:
private static void testTidy() { try { String url = "http://groups.google.com/group/dengues/files"; java.io.InputStream is = new java.net.URL(url).openStream(); org.w3c.dom.Document doc = dengues.system.HTMLWebHelper.parseDOM(is); org.w3c.dom.NodeList list = doc.getElementsByTagName("td"); org.w3c.dom.Element stockTypeElement = null; for (int i = 0; i < list.getLength(); i++) { org.w3c.dom.Node item = list.item(i); String content = dengues.system.HTMLWebHelper.getContent(item); String convert = dengues.system.HTMLWebHelper.convert(content); if (convert.equals("zDevil")) { stockTypeElement = (org.w3c.dom.Element) item.getParentNode().getParentNode(); break; } } if (stockTypeElement != null) { org.w3c.dom.NodeList trList = stockTypeElement.getElementsByTagName("tr"); for (int i = 0; i < trList.getLength(); i++) { org.w3c.dom.NodeList trListChildren = trList.item(i).getChildNodes(); if (trListChildren.getLength() > 2) { org.w3c.dom.Node node_0 = trListChildren.item(0); org.w3c.dom.Node node_1 = trListChildren.item(1); String content = dengues.system.HTMLWebHelper.getContent(node_0); String convert_0 = dengues.system.HTMLWebHelper.convert(content); content = dengues.system.HTMLWebHelper.getContent(node_1); String convert_1 = dengues.system.HTMLWebHelper.convert(content); if (!"".equals(convert_0)) { System.out.println(convert_0 + " => " + convert_1); } } } } is.close(); } catch (java.net.MalformedURLException ex) { ex.printStackTrace(); } catch (java.io.IOException ex) { ex.printStackTrace(); } }
|
11
|
Code Sample 1:
public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
Code Sample 2:
public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, e); } }
|
00
|
Code Sample 1:
public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new MyException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
private static Long getNextPkValueForEntityIncreaseBy(String ename, int count, int increaseBy) { if (increaseBy < 1) increaseBy = 1; String where = "where eoentity_name = '" + ename + "'"; ERXJDBCConnectionBroker broker = ERXJDBCConnectionBroker.connectionBrokerForEntityNamed(ename); Connection con = broker.getConnection(); try { try { con.setAutoCommit(false); con.setReadOnly(false); } catch (SQLException e) { log.error(e, e); } for (int tries = 0; tries < count; tries++) { try { ResultSet resultSet = con.createStatement().executeQuery("select pk_value from pk_table " + where); con.commit(); boolean hasNext = resultSet.next(); long pk = 1; if (hasNext) { pk = resultSet.getLong("pk_value"); con.createStatement().executeUpdate("update pk_table set pk_value = " + (pk + increaseBy) + " " + where); } else { pk = maxIdFromTable(ename); con.createStatement().executeUpdate("insert into pk_table (eoentity_name, pk_value) values ('" + ename + "', " + (pk + increaseBy) + ")"); } con.commit(); return new Long(pk); } catch (SQLException ex) { String s = ex.getMessage().toLowerCase(); boolean creationError = (s.indexOf("error code 116") != -1); creationError |= (s.indexOf("pk_table") != -1 && s.indexOf("does not exist") != -1); creationError |= s.indexOf("ora-00942") != -1; if (creationError) { try { con.rollback(); log.info("creating pk table"); con.createStatement().executeUpdate("create table pk_table (eoentity_name varchar(100) not null, pk_value integer)"); con.createStatement().executeUpdate("alter table pk_table add primary key (eoentity_name)"); con.commit(); } catch (SQLException ee) { throw new NSForwardException(ee, "could not create pk table"); } } else { throw new NSForwardException(ex, "Error fetching PK"); } } } } finally { broker.freeConnection(con); } throw new IllegalStateException("Couldn't get PK"); }
|
00
|
Code Sample 1:
public static InputStream getInputStream(String fileName) throws IOException { InputStream input; if (fileName.startsWith("http:")) { URL url = new URL(fileName); URLConnection connection = url.openConnection(); input = connection.getInputStream(); } else { input = new FileInputStream(fileName); } return input; }
Code Sample 2:
public JythonWrapperAction(AActionBO.ActionDTO dto, URL url) throws IOException { super(dto); InputStream in = url.openStream(); InputStreamReader rin = new InputStreamReader(in); BufferedReader reader = new BufferedReader(rin); StringBuffer s = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { s.append(str); s.append("\n"); } in.close(); script = s.toString(); }
|
00
|
Code Sample 1:
public Psrxml getPsrxmlForCandidateList(CandidateList clist) throws BookKeeprCommunicationException { try { synchronized (httpClient) { long psrxmlid = clist.getPsrxmlId(); HttpGet req = new HttpGet(remoteHost.getUrl() + "/id/" + StringConvertable.ID.toString(psrxmlid)); HttpResponse resp = httpClient.execute(req); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { InputStream in = resp.getEntity().getContent(); XMLAble xmlable = XMLReader.read(in); in.close(); if (xmlable instanceof Psrxml) { Psrxml psrxml = (Psrxml) xmlable; return psrxml; } else { throw new BookKeeprCommunicationException("BookKeepr returned the wrong thing for psrxml id " + psrxmlid); } } catch (SAXException ex) { Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, "Got a malformed message from the bookkeepr", ex); throw new BookKeeprCommunicationException(ex); } } else { resp.getEntity().consumeContent(); throw new BookKeeprCommunicationException("Got a " + resp.getStatusLine().getStatusCode() + " from the BookKeepr (" + remoteHost.getUrl() + "/id/" + StringConvertable.ID + ")"); } } } catch (HttpException ex) { throw new BookKeeprCommunicationException(ex); } catch (IOException ex) { throw new BookKeeprCommunicationException(ex); } catch (URISyntaxException ex) { throw new BookKeeprCommunicationException(ex); } }
Code Sample 2:
@SuppressWarnings("unchecked") protected void handleRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost) throws ServletException, IOException { HttpClient httpclient = WebReader.getHttpClient(); try { StringBuffer sb = new StringBuffer(); sb.append(targetServer); sb.append(req.getRequestURI()); if (req.getQueryString() != null) { sb.append("?" + req.getQueryString()); } HttpRequestBase targetRequest = null; if (isPost) { HttpPost post = new HttpPost(sb.toString()); Enumeration<String> paramNames = req.getParameterNames(); String paramName = null; List<NameValuePair> params = new ArrayList<NameValuePair>(); while (paramNames.hasMoreElements()) { paramName = paramNames.nextElement(); params.add(new BasicNameValuePair(paramName, req.getParameterValues(paramName)[0])); } post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); targetRequest = post; } else { System.out.println("GET"); HttpGet get = new HttpGet(sb.toString()); targetRequest = get; } HttpResponse targetResponse = httpclient.execute(targetRequest); HttpEntity entity = targetResponse.getEntity(); InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output)); String line = reader.readLine(); while (line != null) { writer.write(line + "\n"); line = reader.readLine(); } reader.close(); writer.close(); } finally { WebReader.returnHttpClient(httpclient); } }
|
00
|
Code Sample 1:
public static byte[] decrypt(byte[] ciphertext, byte[] key) throws IOException { CryptInputStream in = new CryptInputStream(new ByteArrayInputStream(ciphertext), new SerpentEngine(), key); ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); return bout.toByteArray(); }
Code Sample 2:
private static long writeVMDKFile(String absoluteFile, String urlString) throws Exception { URL urlCon = new URL(urlString); HttpsURLConnection conn = (HttpsURLConnection) urlCon.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); List cookies = (List) headers.get("Set-cookie"); cookieValue = (String) cookies.get(0); StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";"); cookieValue = tokenizer.nextToken(); String path = "$" + tokenizer.nextToken(); String cookie = "$Version=\"1\"; " + cookieValue + "; " + path; Map map = new HashMap(); map.put("Cookie", Collections.singletonList(cookie)); ((BindingProvider) vimPort).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, map); conn.setRequestProperty("Cookie", cookie); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestProperty("Expect", "100-continue"); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Length", "1024"); InputStream in = conn.getInputStream(); String localpath = localPath + "/" + absoluteFile; OutputStream out = new FileOutputStream(new File(localpath)); byte[] buf = new byte[102400]; int len = 0; long written = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); written = written + len; } System.out.println(" Exported File " + absoluteFile + " : " + written); in.close(); out.close(); return written; }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Throwable { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("cas", "cas file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("o", "output directory").longName("outputDir").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("tempDir", "temp directory").build()); options.addOption(new CommandLineOptionBuilder("prefix", "file prefix for all generated files ( default " + DEFAULT_PREFIX + " )").build()); options.addOption(new CommandLineOptionBuilder("trim", "trim file in sfffile's tab delimmed trim format").build()); options.addOption(new CommandLineOptionBuilder("trimMap", "trim map file containing tab delimited trimmed fastX file to untrimmed counterpart").build()); options.addOption(new CommandLineOptionBuilder("chromat_dir", "directory of chromatograms to be converted into phd " + "(it is assumed the read data for these chromatograms are in a fasta file which the .cas file knows about").build()); options.addOption(new CommandLineOptionBuilder("s", "cache size ( default " + DEFAULT_CACHE_SIZE + " )").longName("cache_size").build()); options.addOption(new CommandLineOptionBuilder("useIllumina", "any FASTQ files in this assembly are encoded in Illumina 1.3+ format (default is Sanger)").isFlag(true).build()); options.addOption(new CommandLineOptionBuilder("useClosureTrimming", "apply additional contig trimming based on JCVI Closure rules").isFlag(true).build()); CommandLine commandLine; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int cacheSize = commandLine.hasOption("s") ? Integer.parseInt(commandLine.getOptionValue("s")) : DEFAULT_CACHE_SIZE; File casFile = new File(commandLine.getOptionValue("cas")); File casWorkingDirectory = casFile.getParentFile(); ReadWriteDirectoryFileServer outputDir = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; TrimDataStore trimDatastore; if (commandLine.hasOption("trim")) { List<TrimDataStore> dataStores = new ArrayList<TrimDataStore>(); final String trimFiles = commandLine.getOptionValue("trim"); for (String trimFile : trimFiles.split(",")) { System.out.println("adding trim file " + trimFile); dataStores.add(new DefaultTrimFileDataStore(new File(trimFile))); } trimDatastore = MultipleDataStoreWrapper.createMultipleDataStoreWrapper(TrimDataStore.class, dataStores); } else { trimDatastore = TrimDataStoreUtil.EMPTY_DATASTORE; } CasTrimMap trimToUntrimmedMap; if (commandLine.hasOption("trimMap")) { trimToUntrimmedMap = new DefaultTrimFileCasTrimMap(new File(commandLine.getOptionValue("trimMap"))); } else { trimToUntrimmedMap = new UnTrimmedExtensionTrimMap(); } boolean useClosureTrimming = commandLine.hasOption("useClosureTrimming"); TraceDataStore<FileSangerTrace> sangerTraceDataStore = null; Map<String, File> sangerFileMap = null; ReadOnlyDirectoryFileServer sourceChromatogramFileServer = null; if (commandLine.hasOption("chromat_dir")) { sourceChromatogramFileServer = DirectoryFileServer.createReadOnlyDirectoryFileServer(new File(commandLine.getOptionValue("chromat_dir"))); sangerTraceDataStore = new SingleSangerTraceDirectoryFileDataStore(sourceChromatogramFileServer, ".scf"); sangerFileMap = new HashMap<String, File>(); Iterator<String> iter = sangerTraceDataStore.getIds(); while (iter.hasNext()) { String id = iter.next(); sangerFileMap.put(id, sangerTraceDataStore.get(id).getFile()); } } PrintWriter logOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".log")), true); PrintWriter consensusOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".consensus.fasta")), true); PrintWriter traceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".traceFiles.txt")), true); PrintWriter referenceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".referenceFiles.txt")), true); long startTime = System.currentTimeMillis(); logOut.println(System.getProperty("user.dir")); final ReadWriteDirectoryFileServer tempDir; if (!commandLine.hasOption("tempDir")) { tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(DEFAULT_TEMP_DIR); } else { File t = new File(commandLine.getOptionValue("tempDir")); IOUtil.mkdirs(t); tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(t); } try { if (!outputDir.contains("chromat_dir")) { outputDir.createNewDir("chromat_dir"); } if (sourceChromatogramFileServer != null) { for (File f : sourceChromatogramFileServer) { String name = f.getName(); OutputStream out = new FileOutputStream(outputDir.createNewFile("chromat_dir/" + name)); final FileInputStream fileInputStream = new FileInputStream(f); try { IOUtils.copy(fileInputStream, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(fileInputStream); } } } FastQQualityCodec qualityCodec = commandLine.hasOption("useIllumina") ? FastQQualityCodec.ILLUMINA : FastQQualityCodec.SANGER; CasDataStoreFactory casDataStoreFactory = new MultiCasDataStoreFactory(new H2SffCasDataStoreFactory(casWorkingDirectory, tempDir, EmptyDataStoreFilter.INSTANCE), new H2FastQCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, qualityCodec, tempDir.getRootDir()), new FastaCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, cacheSize)); final SliceMapFactory sliceMapFactory = new LargeNoQualitySliceMapFactory(); CasAssembly casAssembly = new DefaultCasAssembly.Builder(casFile, casDataStoreFactory, trimDatastore, trimToUntrimmedMap, casWorkingDirectory).build(); System.out.println("finished making casAssemblies"); for (File traceFile : casAssembly.getNuceotideFiles()) { traceFilesOut.println(traceFile.getAbsolutePath()); final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!outputDir.contains("solexa_dir")) { outputDir.createNewDir("solexa_dir"); } if (outputDir.contains("solexa_dir/" + name)) { IOUtil.delete(outputDir.getFile("solexa_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!outputDir.contains("sff_dir")) { outputDir.createNewDir("sff_dir"); } if (outputDir.contains("sff_dir/" + name)) { IOUtil.delete(outputDir.getFile("sff_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } for (File traceFile : casAssembly.getReferenceFiles()) { referenceFilesOut.println(traceFile.getAbsolutePath()); } DataStore<CasContig> contigDatastore = casAssembly.getContigDataStore(); Map<String, AceContig> aceContigs = new HashMap<String, AceContig>(); CasIdLookup readIdLookup = sangerFileMap == null ? casAssembly.getReadIdLookup() : new DifferentFileCasIdLookupAdapter(casAssembly.getReadIdLookup(), sangerFileMap); Date phdDate = new Date(startTime); NextGenClosureAceContigTrimmer closureContigTrimmer = null; if (useClosureTrimming) { closureContigTrimmer = new NextGenClosureAceContigTrimmer(2, 5, 10); } for (CasContig casContig : contigDatastore) { final AceContigAdapter adpatedCasContig = new AceContigAdapter(casContig, phdDate, readIdLookup); CoverageMap<CoverageRegion<AcePlacedRead>> coverageMap = DefaultCoverageMap.buildCoverageMap(adpatedCasContig); for (AceContig aceContig : ConsedUtil.split0xContig(adpatedCasContig, coverageMap)) { if (useClosureTrimming) { AceContig trimmedAceContig = closureContigTrimmer.trimContig(aceContig); if (trimmedAceContig == null) { System.out.printf("%s was completely trimmed... skipping%n", aceContig.getId()); continue; } aceContig = trimmedAceContig; } aceContigs.put(aceContig.getId(), aceContig); consensusOut.print(new DefaultNucleotideEncodedSequenceFastaRecord(aceContig.getId(), NucleotideGlyph.convertToString(NucleotideGlyph.convertToUngapped(aceContig.getConsensus().decode())))); } } System.out.printf("finished adapting %d casAssemblies into %d ace contigs%n", contigDatastore.size(), aceContigs.size()); QualityDataStore qualityDataStore = sangerTraceDataStore == null ? casAssembly.getQualityDataStore() : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(QualityDataStore.class, TraceQualityDataStoreAdapter.adapt(sangerTraceDataStore), casAssembly.getQualityDataStore()); final DateTime phdDateTime = new DateTime(phdDate); final PhdDataStore casPhdDataStore = CachedDataStore.createCachedDataStore(PhdDataStore.class, new ArtificalPhdDataStore(casAssembly.getNucleotideDataStore(), qualityDataStore, phdDateTime), cacheSize); final PhdDataStore phdDataStore = sangerTraceDataStore == null ? casPhdDataStore : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(PhdDataStore.class, new PhdSangerTraceDataStoreAdapter<FileSangerTrace>(sangerTraceDataStore, phdDateTime), casPhdDataStore); WholeAssemblyAceTag pathToPhd = new DefaultWholeAssemblyAceTag("phdball", "cas2consed", new Date(DateTimeUtils.currentTimeMillis()), "../phd_dir/" + prefix + ".phd.ball"); AceAssembly aceAssembly = new DefaultAceAssembly<AceContig>(new SimpleDataStore<AceContig>(aceContigs), phdDataStore, Collections.<File>emptyList(), new DefaultAceTagMap(Collections.<ConsensusAceTag>emptyList(), Collections.<ReadAceTag>emptyList(), Arrays.asList(pathToPhd))); System.out.println("writing consed package..."); ConsedWriter.writeConsedPackage(aceAssembly, sliceMapFactory, outputDir.getRootDir(), prefix, false); } catch (Throwable t) { t.printStackTrace(logOut); throw t; } finally { long endTime = System.currentTimeMillis(); logOut.printf("took %s%n", new Period(endTime - startTime)); logOut.flush(); logOut.close(); outputDir.close(); consensusOut.close(); traceFilesOut.close(); referenceFilesOut.close(); trimDatastore.close(); } } catch (ParseException e) { printHelp(options); System.exit(1); } }
Code Sample 2:
public void run() { Pair p = null; try { while ((p = queue.pop()) != null) { GetMethod get = new GetMethod(p.getRemoteUri()); try { get.setFollowRedirects(true); get.setRequestHeader("Mariner-Application", "prerenderer"); get.setRequestHeader("Mariner-DeviceName", deviceName); int iGetResultCode = httpClient.executeMethod(get); if (iGetResultCode != 200) { throw new IOException("Got response code " + iGetResultCode + " for a request for " + p.getRemoteUri()); } InputStream is = get.getResponseBodyAsStream(); File localFile = new File(deviceFile, p.getLocalUri()); localFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(localFile); IOUtils.copy(is, os); os.close(); } finally { get.releaseConnection(); } } } catch (Exception ex) { result = ex; } }
|
11
|
Code Sample 1:
private String createDefaultRepoConf() throws IOException { InputStream confIn = getClass().getResourceAsStream(REPO_CONF_PATH); File tempConfFile = File.createTempFile("repository", "xml"); tempConfFile.deleteOnExit(); IOUtils.copy(confIn, new FileOutputStream(tempConfFile)); return tempConfFile.getAbsolutePath(); }
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:
void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } }
Code Sample 2:
public static void createBackup() { String workspacePath = Workspace.INSTANCE.getWorkspace(); if (workspacePath.length() == 0) return; workspacePath += "/"; String backupPath = workspacePath + "Backup"; File directory = new File(backupPath); if (!directory.exists()) directory.mkdirs(); String dateString = DataUtils.DateAndTimeOfNowAsLocalString(); dateString = dateString.replace(" ", "_"); dateString = dateString.replace(":", ""); backupPath += "/Backup_" + dateString + ".zip"; ArrayList<String> backupedFiles = new ArrayList<String>(); backupedFiles.add("Database/Database.properties"); backupedFiles.add("Database/Database.script"); FileInputStream in; byte[] data = new byte[1024]; int read = 0; try { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath)); zip.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < backupedFiles.size(); i++) { String backupedFile = backupedFiles.get(i); try { File inFile = new File(workspacePath + backupedFile); if (inFile.exists()) { in = new FileInputStream(workspacePath + backupedFile); if (in != null) { ZipEntry entry = new ZipEntry(backupedFile); zip.putNextEntry(entry); while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read); zip.closeEntry(); in.close(); } } } catch (Exception e) { Logger.logError(e, "Error during file backup:" + backupedFile); } } zip.close(); } catch (IOException ex) { Logger.logError(ex, "Error during backup"); } }
|
00
|
Code Sample 1:
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 (Exception e) { log.error(e, e); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
private static void initialize() throws IOException { System.out.println("Getting startup cookies from localhostr.com"); HttpGet httpget = new HttpGet("http://localhostr.com/"); if (login) { httpget.setHeader("Cookie", sessioncookie); } HttpResponse myresponse = httpclient.execute(httpget); HttpEntity myresEntity = myresponse.getEntity(); localhostrurl = EntityUtils.toString(myresEntity); localhostrurl = parseResponse(localhostrurl, "url : '", "'"); System.out.println("Localhost url : " + localhostrurl); InputStream is = myresponse.getEntity().getContent(); is.close(); }
|
11
|
Code Sample 1:
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public void visit(BosMember member) throws BosException { String relative = AddressingUtil.getRelativePath(member.getDataSourceUri(), baseUri); URL resultUrl; try { resultUrl = new URL(outputUrl, relative); File resultFile = new File(resultUrl.toURI()); resultFile.getParentFile().mkdirs(); log.info("Creating result file \"" + resultFile.getAbsolutePath() + "\"..."); IOUtils.copy(member.getInputStream(), new FileOutputStream(resultFile)); } catch (Exception e) { throw new BosException(e); } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dest) throws IOException { if (!src.exists()) throw new IOException("File not found '" + src.getAbsolutePath() + "'"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { String pathInfo = httpServletRequest.getPathInfo(); log.info("PathInfo: " + pathInfo); if (pathInfo == null || pathInfo.equals("") || pathInfo.equals("/")) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String fileName = pathInfo.charAt(0) == '/' ? pathInfo.substring(1) : pathInfo; log.info("FileName: " + fileName); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = getDataSource().getConnection(); ps = con.prepareStatement("select file, size from files where name=?"); ps.setString(1, fileName); rs = ps.executeQuery(); if (rs.next()) { httpServletResponse.setContentType(getServletContext().getMimeType(fileName)); httpServletResponse.setContentLength(rs.getInt("size")); OutputStream os = httpServletResponse.getOutputStream(); org.apache.commons.io.IOUtils.copy(rs.getBinaryStream("file"), os); os.flush(); } else { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } catch (SQLException e) { throw new ServletException(e); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { } if (ps != null) try { ps.close(); } catch (SQLException e) { } if (con != null) try { con.close(); } catch (SQLException e) { } } }
|
11
|
Code Sample 1:
private void copyFile(String fileName, String messageID, boolean isError) { try { File inputFile = new File(fileName); File outputFile = null; if (isError) { outputFile = new File(provider.getErrorDataLocation(folderName) + messageID + ".xml"); } else { outputFile = new File(provider.getDataProcessedLocation(folderName) + messageID + ".xml"); } FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); try { boolean isMultipart = FileUpload.isMultipartContent(request); Store storeInstance = getStoreInstance(request); if (isMultipart) { Map fields = new HashMap(); Vector files = new Vector(); List items = diskFileUpload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fields.put(item.getFieldName(), item.getString()); } else { if (!StringUtils.isBlank(item.getName())) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); IOUtils.copy(item.getInputStream(), baos); MailPartObj part = new MailPartObj(); part.setAttachent(baos.toByteArray()); part.setContentType(item.getContentType()); part.setName(item.getName()); part.setSize(item.getSize()); files.addElement(part); } catch (Exception ex) { } finally { IOUtils.closeQuietly(baos); } } } } if (files.size() > 0) { storeInstance.send(files, 0, Charset.defaultCharset().displayName()); } } else { errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null")); request.setAttribute("exception", "The form is null"); request.setAttribute("newLocation", null); doTrace(request, DLog.ERROR, getClass(), "The form is null"); } } catch (Exception ex) { String errorMessage = ExceptionUtilities.parseMessage(ex); if (errorMessage == null) { errorMessage = "NullPointerException"; } errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage)); request.setAttribute("exception", errorMessage); doTrace(request, DLog.ERROR, getClass(), errorMessage); } finally { } if (errors.isEmpty()) { doTrace(request, DLog.INFO, getClass(), "OK"); return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD); } else { saveErrors(request, errors); return mapping.findForward(Constants.ACTION_FAIL_FORWARD); } }
|
11
|
Code Sample 1:
public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); }
Code Sample 2:
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); try { boolean isMultipart = FileUpload.isMultipartContent(request); Store storeInstance = getStoreInstance(request); if (isMultipart) { Map fields = new HashMap(); Vector files = new Vector(); List items = diskFileUpload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fields.put(item.getFieldName(), item.getString()); } else { if (!StringUtils.isBlank(item.getName())) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); IOUtils.copy(item.getInputStream(), baos); MailPartObj part = new MailPartObj(); part.setAttachent(baos.toByteArray()); part.setContentType(item.getContentType()); part.setName(item.getName()); part.setSize(item.getSize()); files.addElement(part); } catch (Exception ex) { } finally { IOUtils.closeQuietly(baos); } } } } if (files.size() > 0) { storeInstance.send(files, 0, Charset.defaultCharset().displayName()); } } else { errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null")); request.setAttribute("exception", "The form is null"); request.setAttribute("newLocation", null); doTrace(request, DLog.ERROR, getClass(), "The form is null"); } } catch (Exception ex) { String errorMessage = ExceptionUtilities.parseMessage(ex); if (errorMessage == null) { errorMessage = "NullPointerException"; } errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage)); request.setAttribute("exception", errorMessage); doTrace(request, DLog.ERROR, getClass(), errorMessage); } finally { } if (errors.isEmpty()) { doTrace(request, DLog.INFO, getClass(), "OK"); return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD); } else { saveErrors(request, errors); return mapping.findForward(Constants.ACTION_FAIL_FORWARD); } }
|
00
|
Code Sample 1:
protected String getCache() throws IOException { if (cache == null) { URL url = ((URI) hasContent()).toURL(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) ; in.close(); cache = inputLine; } return cache; }
Code Sample 2:
@Test public void testWrite() { System.out.println("write"); final File[] files = { new File(sharePath) }; System.out.println("Creating hash..."); String initHash = MD5File.MD5Directory(files[0]); System.out.println("Hash: " + initHash); Share readShare = ShareUtility.createShare(files, "TestShare"); System.out.println("Creating shares..."); final ShareFolder[] readers = ShareUtility.cropShareToParts(readShare, PARTS); System.out.println("Reading and writing shares..."); done = 0; for (int i = 0; i < PARTS; i++) { final int j = i; new Thread() { public void run() { ShareFolder part = (ShareFolder) ObjectClone.clone(readers[j]); ShareFileReader reader = new ShareFileReader(readers[j], files[0]); ShareFileWriter writer = new ShareFileWriter(part, new File("Downloads/" + readers[j].getName())); long tot = 0; byte[] b = new byte[(int) (Math.random() * 10000)]; while (tot < readers[j].getSize()) { reader.read(b); byte[] bwrite = new byte[(int) (Math.random() * 10000) + b.length]; System.arraycopy(b, 0, bwrite, 0, b.length); writer.write(bwrite, b.length); tot += b.length; } done++; System.out.println((int) (done * 100.0 / PARTS) + "% Complete"); } }.start(); } while (done < PARTS) { Thread.yield(); } File resultFile = new File("Downloads/" + readShare.getName()); System.out.println("Creating hash of written share..."); String resultHash = MD5File.MD5Directory(resultFile); System.out.println("Init hash: " + initHash); System.out.println("Result hash: " + resultHash); assertEquals(initHash, resultHash); }
|
00
|
Code Sample 1:
private Reader getReader(String uri, Query query) throws SourceException { if (OntoramaConfig.DEBUG) { System.out.println("uri = " + uri); } InputStreamReader reader = null; try { System.out.println("class UrlSource, uri = " + uri); URL url = new URL(uri); URLConnection connection = url.openConnection(); reader = new InputStreamReader(connection.getInputStream()); } catch (MalformedURLException urlExc) { throw new SourceException("Url " + uri + " specified for this ontology source is not well formed, error: " + urlExc.getMessage()); } catch (IOException ioExc) { throw new SourceException("Couldn't read input data source for " + uri + ", error: " + ioExc.getMessage()); } return reader; }
Code Sample 2:
public void deleteSynchrnServerFile(SynchrnServerVO synchrnServerVO) throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("euc-kr"); if (!EgovWebUtil.isIPAddress(synchrnServerVO.getServerIp())) { throw new RuntimeException("IP is needed. (" + synchrnServerVO.getServerIp() + ")"); } InetAddress host = InetAddress.getByName(synchrnServerVO.getServerIp()); ftpClient.connect(host, Integer.parseInt(synchrnServerVO.getServerPort())); ftpClient.login(synchrnServerVO.getFtpId(), synchrnServerVO.getFtpPassword()); FTPFile[] fTPFile = null; try { ftpClient.changeWorkingDirectory(synchrnServerVO.getSynchrnLc()); fTPFile = ftpClient.listFiles(synchrnServerVO.getSynchrnLc()); for (int i = 0; i < fTPFile.length; i++) { if (synchrnServerVO.getDeleteFileNm().equals(fTPFile[i].getName())) ftpClient.deleteFile(fTPFile[i].getName()); } SynchrnServer synchrnServer = new SynchrnServer(); synchrnServer.setServerId(synchrnServerVO.getServerId()); synchrnServer.setReflctAt("N"); synchrnServerDAO.processSynchrn(synchrnServer); } catch (Exception e) { System.out.println(e); } finally { ftpClient.logout(); } }
|
00
|
Code Sample 1:
public String getMd5CodeOf16(String str) { StringBuffer buf = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte b[] = md.digest(); int i; buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { return buf.toString().substring(8, 24); } }
Code Sample 2:
public void check() { statusBar.setStatusText(Labels.getLabel("state.retrievingVersion")); Runnable checkVersionCode = new Runnable() { public void run() { BufferedReader reader = null; String message = null; int messageStyle = SWT.ICON_WARNING; try { URL url = new URL(Version.LATEST_VERSION_URL); URLConnection conn = url.openConnection(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String latestVersion = reader.readLine(); latestVersion = latestVersion.substring(latestVersion.indexOf(' ') + 1); if (!Version.getVersion().equals(latestVersion)) { message = Labels.getLabel("text.version.old"); message = message.replaceFirst("%LATEST", latestVersion); message = message.replaceFirst("%VERSION", Version.getVersion()); messageStyle = SWT.ICON_QUESTION | SWT.YES | SWT.NO; } else { message = Labels.getLabel("text.version.latest"); messageStyle = SWT.ICON_INFORMATION; } } catch (Exception e) { message = Labels.getLabel("exception.UserErrorException.version.latestFailed"); Logger.getLogger(getClass().getName()).log(Level.WARNING, message, e); } finally { try { if (reader != null) reader.close(); } catch (IOException e) { } final String messageToShow = message; final int messageStyleToShow = messageStyle; Display.getDefault().asyncExec(new Runnable() { public void run() { statusBar.setStatusText(null); MessageBox messageBox = new MessageBox(statusBar.getShell(), messageStyleToShow); messageBox.setText(Version.getFullName()); messageBox.setMessage(messageToShow); if (messageBox.open() == SWT.YES) { BrowserLauncher.openURL(Version.DOWNLOAD_URL); } } }); } } }; new Thread(checkVersionCode).start(); }
|
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 FileChannel getFileChannel(Object o) throws IOException { Class c = o.getClass(); try { Method m = c.getMethod("getChannel", null); return (FileChannel) m.invoke(o, null); } catch (IllegalAccessException x) { } catch (NoSuchMethodException x) { } catch (InvocationTargetException x) { if (x.getTargetException() instanceof IOException) throw (IOException) x.getTargetException(); } if (o instanceof FileInputStream) return new MyFileChannelImpl((FileInputStream) o); if (o instanceof FileOutputStream) return new MyFileChannelImpl((FileOutputStream) o); if (o instanceof RandomAccessFile) return new MyFileChannelImpl((RandomAccessFile) o); Assert.UNREACHABLE(o.getClass().toString()); return null; }
|
00
|
Code Sample 1:
public static boolean copyFile(File src, File dest) throws IOException { if (src == null) { throw new IllegalArgumentException("src == null"); } if (dest == null) { throw new IllegalArgumentException("dest == null"); } if (!src.isFile()) { return false; } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); return true; } catch (IOException e) { throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
Code Sample 2:
private static boolean initLOG4JProperties(String homeDir) { String Log4jURL = homeDir + LOG4J_URL; try { URL log4jurl = getURL(Log4jURL); InputStream inStreamLog4j = log4jurl.openStream(); Properties propertiesLog4j = new Properties(); try { propertiesLog4j.load(inStreamLog4j); PropertyConfigurator.configure(propertiesLog4j); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { logger.info("Failed to initialize LOG4J with properties file."); return false; } return true; }
|
00
|
Code Sample 1:
public static Collection<SearchKeyResult> searchKey(String iText, String iKeyServer) throws Exception { Vector<SearchKeyResult> outVec = new Vector<SearchKeyResult>(); String uri = iKeyServer + "/pks/lookup?search=" + URLEncoder.encode(iText, "UTF-8"); URL url = new URL(uri); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); Pattern regex = Pattern.compile("pub.*?<a\\s+href\\s*=\"(.*?)\".*?>\\s*(\\w+)\\s*</a>.*?(\\d+-\\d+-\\d+).*?<a\\s+href\\s*=\".*?\".*?>\\s*(.+?)\\s*</a>", Pattern.CANON_EQ); String line; while ((line = input.readLine()) != null) { Matcher regexMatcher = regex.matcher(line); while (regexMatcher.find()) { String id = regexMatcher.group(2); String downUrl = iKeyServer + regexMatcher.group(1); String downDate = regexMatcher.group(3); String name = HTMLDecoder.decodeHTML(regexMatcher.group(4)); outVec.add(new SearchKeyResult(id, name, downDate, downUrl)); } } input.close(); return outVec; }
Code Sample 2:
private static void convertToOnline(final String filePath, final DocuBean docuBean) throws Exception { File source = new File(filePath + File.separator + docuBean.getFileName()); File dir = new File(filePath + File.separator + docuBean.getId()); if (!dir.exists()) { dir.mkdir(); } File in = source; boolean isSpace = false; if (source.getName().indexOf(" ") != -1) { in = new File(StringUtils.replace(source.getName(), " ", "")); try { IOUtils.copyFile(source, in); } catch (IOException e) { e.printStackTrace(); } isSpace = true; } File finalPdf = null; try { String outPath = dir.getAbsolutePath(); final File pdf = DocViewerConverter.toPDF(in, outPath); convertToSwf(pdf, outPath, docuBean); finalPdf = new File(outPath + File.separator + FileUtils.getFilePrefix(StringUtils.replace(source.getName(), " ", "")) + "_decrypted.pdf"); if (!finalPdf.exists()) { finalPdf = pdf; } pdfByFirstPageToJpeg(finalPdf, outPath, docuBean); if (docuBean.getSuccess() == 2 && dir.listFiles().length < 2) { docuBean.setSuccess(3); } } catch (Exception e) { throw e; } finally { if (isSpace) { IOUtils.delete(in); } } }
|
00
|
Code Sample 1:
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
Code Sample 2:
public static String postServiceContent(String serviceURL, String text) throws IOException { URL url = new URL(serviceURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.connect(); int code = connection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); byte[] buffer = null; String stringBuffer = ""; buffer = new byte[4096]; int totBytes, bytes, sumBytes = 0; totBytes = connection.getContentLength(); while (true) { bytes = is.read(buffer); if (bytes <= 0) break; stringBuffer = stringBuffer + new String(buffer); } return stringBuffer; } return null; }
|
00
|
Code Sample 1:
public static boolean download(String url, File file) { HttpURLConnection conn = null; BufferedInputStream in = null; BufferedOutputStream out = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.connect(); if (conn.getResponseCode() == 200) { System.out.println("length:" + conn.getContentLength()); in = new BufferedInputStream(conn.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(file)); byte[] b = new byte[1024 << 10]; int i = 0; while ((i = in.read(b)) > -1) { if (i > 0) out.write(b, 0, i); } return true; } else { System.out.println(conn.getResponseCode() + ":" + url); } } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } if (conn != null) conn.disconnect(); } return false; }
Code Sample 2:
public static User authenticate(final String username, final String password) throws LoginException { Object result = doPriviledgedAction(new PrivilegedAction() { public Object run() { List correctUsers = (List) JsonPath.query("select * from ? where name=?", usersTable(), username); if (correctUsers.size() == 0) { return new LoginException("user " + username + " not found"); } Persistable userObject = (Persistable) correctUsers.get(0); boolean alreadyHashed = false; boolean passwordMatch = password.equals(userObject.get(PASSWORD_FIELD)); if (!passwordMatch) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(((String) userObject.get(PASSWORD_FIELD)).getBytes()); passwordMatch = password.equals(new String(new Base64().encode(md.digest()))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } alreadyHashed = true; } if (passwordMatch) { Logger.getLogger(User.class.toString()).info("User " + username + " has been authenticated"); User user = (User) userObject; try { if (alreadyHashed) user.currentTicket = password; else { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); user.currentTicket = new String(new Base64().encode(md.digest())); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return user; } else { Logger.getLogger(User.class.toString()).info("The password was incorrect for " + username); return new LoginException("The password was incorrect for user " + username + ". "); } } }); if (result instanceof LoginException) throw (LoginException) result; return (User) result; }
|
00
|
Code Sample 1:
private void copyXsl(File aTargetLogDir) { Trace.println(Trace.LEVEL.UTIL, "copyXsl( " + aTargetLogDir.getName() + " )", true); if (myXslSourceDir == null) { return; } File[] files = myXslSourceDir.listFiles(); for (int i = 0; i < files.length; i++) { File srcFile = files[i]; if (!srcFile.isDirectory()) { File tgtFile = new File(aTargetLogDir + File.separator + srcFile.getName()); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(srcFile).getChannel(); outChannel = new FileOutputStream(tgtFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new IOError(e); } finally { if (inChannel != null) try { inChannel.close(); } catch (IOException exc) { throw new IOError(exc); } if (outChannel != null) try { outChannel.close(); } catch (IOException exc) { throw new IOError(exc); } } } } }
Code Sample 2:
public boolean connect(String host, String userName, String password) throws IOException, UnknownHostException { try { if (ftpClient != null) { if (ftpClient.isConnected()) { ftpClient.disconnect(); } } ftpClient = new FTPClient(); boolean success = false; ftpClient.connect(host); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { success = ftpClient.login(userName, password); } if (!success) { ftpClient.disconnect(); } return success; } catch (Exception ex) { throw new IOException(ex.getMessage()); } }
|
11
|
Code Sample 1:
private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
Code Sample 2:
private void initializeTree() { InputStreamReader reader = null; BufferedReader buffReader = null; try { for (int i = 0; i < ORDER.length; i++) { int index = ORDER[i]; String indexName = index < 10 ? "0" + index : (index > 20 ? "big" : "" + index); URL url = EmptyClass.class.getResource("engchar" + indexName + ".dic"); logger.info("... Loading: " + "engchar" + indexName + ".dic = {" + url + "}"); reader = new InputStreamReader(url.openStream()); buffReader = new BufferedReader(reader); String line = null; String word = null; do { line = buffReader.readLine(); if (line != null) { boolean plural = line.endsWith("/S"); boolean forbidden = line.endsWith("/X"); if (plural) { int stringIndex = line.indexOf("/S"); word = new String(line.substring(0, stringIndex)); } else if (forbidden) { int stringIndex = line.indexOf("/X"); word = new String(line.substring(0, stringIndex)); } else { word = line.toString(); } if (tree == null) { tree = new BKTree(); } tree.insertDictionaryWord(word, plural, forbidden); } } while (line != null); } logger.debug("Loading supplemental dictionary..."); List<String> listOfWords = KSupplementalDictionaryUtil.getWords(); for (String word : listOfWords) { tree.insertDictionaryWord(word, false, false); } initialized = true; } catch (Exception exception) { logger.error("Error", exception); } finally { if (reader != null) { try { reader.close(); } catch (Exception ex) { } } if (buffReader != null) { try { buffReader.close(); } catch (Exception ex) { } } } }
|
11
|
Code Sample 1:
public void copyFile(File sourceFile, File destFile) throws IOException { Log.level3("Copying " + sourceFile.getPath() + " to " + destFile.getPath()); 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:
public void processAction(ActionMapping mapping, ActionForm form, PortletConfig config, ActionRequest req, ActionResponse res) throws Exception { boolean editor = false; req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, false); User user = _getUser(req); List<Role> roles = RoleFactory.getAllRolesForUser(user.getUserId()); for (Role role : roles) { if (role.getName().equals("Report Administrator") || role.getName().equals("Report Editor") || role.getName().equals("CMS Administrator")) { req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, true); editor = true; break; } } requiresInput = false; badParameters = false; newReport = false; ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); String cmd = req.getParameter(Constants.CMD); Logger.debug(this, "Inside EditReportAction cmd=" + cmd); ReportForm rfm = (ReportForm) form; ArrayList<String> ds = (DbConnectionFactory.getAllDataSources()); ArrayList<DataSource> dsResults = new ArrayList<DataSource>(); for (String dataSource : ds) { DataSource d = rfm.getNewDataSource(); if (dataSource.equals(com.dotmarketing.util.Constants.DATABASE_DEFAULT_DATASOURCE)) { d.setDsName("DotCMS Datasource"); } else { d.setDsName(dataSource); } dsResults.add(d); } rfm.setDataSources(dsResults); httpReq.setAttribute("dataSources", rfm.getDataSources()); Long reportId = UtilMethods.parseLong(req.getParameter("reportId"), 0); String referrer = req.getParameter("referrer"); if (reportId > 0) { report = ReportFactory.getReport(reportId); ArrayList<String> adminRoles = new ArrayList<String>(); adminRoles.add(com.dotmarketing.util.Constants.ROLE_REPORT_ADMINISTRATOR); if (user.getUserId().equals(report.getOwner())) { _checkWritePermissions(report, user, httpReq, adminRoles); } if (cmd == null || !cmd.equals(Constants.EDIT)) { rfm.setSelectedDataSource(report.getDs()); rfm.setReportName(report.getReportName()); rfm.setReportDescription(report.getReportDescription()); rfm.setReportId(report.getInode()); rfm.setWebFormReport(report.isWebFormReport()); httpReq.setAttribute("selectedDS", report.getDs()); } } else { if (!editor) { throw new DotRuntimeException("user not allowed to create a new report"); } report = new Report(); report.setOwner(_getUser(req).getUserId()); newReport = true; } req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, report); if ((cmd != null) && cmd.equals(Constants.EDIT)) { if (Validator.validate(req, form, mapping)) { report.setReportName(rfm.getReportName()); report.setReportDescription(rfm.getReportDescription()); report.setWebFormReport(rfm.isWebFormReport()); if (rfm.isWebFormReport()) report.setDs("None"); else report.setDs(rfm.getSelectedDataSource()); String jrxmlPath = ""; String jasperPath = ""; try { HibernateUtil.startTransaction(); ReportFactory.saveReport(report); _applyPermissions(req, report); if (!rfm.isWebFormReport()) { if (UtilMethods.isSet(Config.getStringProperty("ASSET_REAL_PATH"))) { jrxmlPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"; jasperPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"; } else { jrxmlPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"); jasperPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"); } UploadPortletRequest upr = PortalUtil.getUploadPortletRequest(req); File importFile = upr.getFile("jrxmlFile"); if (importFile.exists()) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(importFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); File f = new File(jrxmlPath); FileChannel channelTo = new FileOutputStream(f).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); try { JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath); } catch (Exception e) { Logger.error(this, "Unable to compile or save jrxml: " + e.toString()); try { f = new File(jrxmlPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jrxml. This is usually a permissions problem."); } try { f = new File(jasperPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jasper. This is usually a permissions problem."); } HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", UtilMethods.htmlLineBreak(e.getMessage())); setForward(req, "portlet.ext.report.edit_report"); return; } JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperPath); ReportParameterFactory.deleteReportsParameters(report); _loadReportParameters(jasperReport.getParameters()); report.setRequiresInput(requiresInput); HibernateUtil.save(report); } else if (newReport) { HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", "message.report.compile.error"); setForward(req, "portlet.ext.report.edit_report"); return; } } HibernateUtil.commitTransaction(); HashMap params = new HashMap(); SessionMessages.add(req, "message", "message.report.upload.success"); params.put("struts_action", new String[] { "/ext/report/view_reports" }); referrer = com.dotmarketing.util.PortletURLUtil.getRenderURL(((ActionRequestImpl) req).getHttpServletRequest(), javax.portlet.WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, referrer); return; } catch (Exception ex) { HibernateUtil.rollbackTransaction(); Logger.error(this, "Unable to save Report: " + ex.toString()); File f; Logger.info(this, "Trying to delete jrxml"); try { f = new File(jrxmlPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jrxml. This is usually because the file doesn't exist."); } try { f = new File(jasperPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jasper. This is usually because the file doesn't exist."); } if (badParameters) { SessionMessages.add(req, "error", ex.getMessage()); } else { SessionMessages.add(req, "error", "message.report.compile.error"); } setForward(req, "portlet.ext.report.edit_report"); return; } } else { setForward(req, "portlet.ext.report.edit_report"); } } if ((cmd != null) && cmd.equals("downloadReportSource")) { ActionResponseImpl resImpl = (ActionResponseImpl) res; HttpServletResponse response = resImpl.getHttpServletResponse(); if (!downloadSourceReport(reportId, httpReq, response)) { SessionMessages.add(req, "error", "message.report.source.file.not.found"); } } setForward(req, "portlet.ext.report.edit_report"); }
|
00
|
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 long getLastModification() { try { if (connection == null) connection = url.openConnection(); return connection.getLastModified(); } catch (IOException e) { LOG.warn("URL could not be opened: " + e.getMessage(), e); return 0; } }
|
00
|
Code Sample 1:
public InputStream getConfResourceAsInputStream(String name) { try { URL url = getResource(name); if (url == null) { LOG.info(name + " not found"); return null; } else { LOG.info("found resource " + name + " at " + url); } return url.openStream(); } catch (Exception e) { return null; } }
Code Sample 2:
public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(inputLocation); outputStream = new FileOutputStream(outputLocation); byte buffer[] = new byte[1024]; while (inputStream.available() > 0) { int read = inputStream.read(buffer); outputStream.write(buffer, 0, read); } inputLocation.delete(); } finally { IOUtil.closeAndIgnoreErrors(inputStream); IOUtil.closeAndIgnoreErrors(outputStream); } }
|
00
|
Code Sample 1:
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, NULL_OUTPUT_STREAM); } finally { IOUtils.close(in); } return checksum; }
Code Sample 2:
public void load(URL urlin) throws IOException { index = hs.getDoIndex(); loaded = false; url = urlin; int c, i; htmlDocLength = 0; HtmlReader in = new HtmlReader(new InputStreamReader(url.openStream(), charset)); try { if (debug >= 2) System.out.print("Loading " + urlin.toString() + " ... "); while ((c = in.read()) >= 0) { htmlDoc[htmlDocLength++] = (char) (c); if (htmlDocLength == htmlDocMaxLength) { char[] newHtmlDoc = new char[2 * htmlDocMaxLength]; System.arraycopy(htmlDoc, 0, newHtmlDoc, 0, htmlDocMaxLength); htmlDocMaxLength = 2 * htmlDocMaxLength; htmlDoc = newHtmlDoc; } } if (debug >= 2) System.out.println("done."); } catch (ArrayIndexOutOfBoundsException aioobe) { if (debug >= 1) System.out.println("Error, reading file into memory (too big) - skipping " + urlin.toString()); loaded = false; return; } in.close(); fetchURLpos = 0; dumpPos = 0; dumpLastChar = SPACE; loaded = true; frameset = false; titledone = false; headdone = false; checkhead = false; checkbody = false; }
|
11
|
Code Sample 1:
public void copyFile() throws Exception { SmbFile file = new SmbFile("smb://elsa:elsa@elsa/Elsa/Desktop/Ficheiros2/04-04-2066/How To Make a Flash Preloader.doc"); println("length: " + file.length()); SmbFileInputStream in = new SmbFileInputStream(file); println("available: " + in.available()); File dest = new File("C:\\Documents and Settings\\Carlos\\Desktop\\Flash Preloader.doc"); FileOutputStream out = new FileOutputStream(dest); int buffer_length = 1024; byte[] buffer = new byte[buffer_length]; while (true) { int bytes_read = in.read(buffer, 0, buffer_length); if (bytes_read <= 0) { break; } out.write(buffer, 0, bytes_read); } in.close(); out.close(); println("done."); }
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(); } }
|
11
|
Code Sample 1:
public void excluirTopico(Integer idDisciplina) throws Exception { String sql = "DELETE from topico WHERE id_disciplina = ?"; PreparedStatement stmt = null; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, idDisciplina); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } }
Code Sample 2:
private void salvarArtista(Artista artista) throws Exception { System.out.println("GerenteMySQL.salvarArtista()" + artista.toString2()); Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "insert into artista VALUES (?,?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, artista.getNumeroInscricao()); ps.setString(2, artista.getNome()); ps.setBoolean(3, artista.isSexo()); ps.setString(4, artista.getEmail()); ps.setString(5, artista.getObs()); ps.setString(6, artista.getTelefone()); ps.setNull(7, Types.INTEGER); ps.executeUpdate(); salvarEndereco(conn, ps, artista); sql = "insert into obra VALUES (?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); for (Obra obra : artista.getListaObras()) { salvarObra(conn, ps, obra, artista.getNumeroInscricao()); } conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } }
|
00
|
Code Sample 1:
public LOCKSSDaemonStatusTableTO getDataFromDaemonStatusTableByHttps() throws HttpResponseException { LOCKSSDaemonStatusTableXmlStreamParser ldstxp = null; LOCKSSDaemonStatusTableTO ldstTO = null; HttpEntity entity = null; HttpGet httpget = null; xstream.setMode(XStream.NO_REFERENCES); xstream.alias("HttpClientDAO", HttpClientDAO.class); try { httpget = new HttpGet(dataUrl); logger.log(Level.INFO, "executing request {0}", httpget.getURI()); HttpResponse resp = httpClient.execute(httpget); int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.log(Level.WARNING, "response to the request is not OK: skip this IP: status code={0}", statusCode); httpget.abort(); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); return ldstTO; } entity = resp.getEntity(); InputStream is = entity.getContent(); ldstxp = new LOCKSSDaemonStatusTableXmlStreamParser(); ldstxp.read(new BufferedInputStream(is)); ldstTO = ldstxp.getLOCKSSDaemonStatusTableTO(); ldstTO.setIpAddress(this.ip); logger.log(Level.INFO, "After parsing [{0}] table", this.tableId); logger.log(Level.FINEST, "After parsing {0}: contents of ldstTO:\n{1}", new Object[] { this.tableId, ldstTO }); if (ldstTO.hasIncompleteRows) { logger.log(Level.WARNING, "!!!!!!!!! incomplete rows are found for {0}", tableId); if (ldstTO.getTableData() != null && ldstTO.getTableData().size() > 0) { logger.log(Level.FINE, "incomplete rows: table(map) data dump =[\n{0}\n]", xstream.toXML(ldstTO.getTableData())); } } else { logger.log(Level.INFO, "All rows are complete for {0}", tableId); } } catch (ConnectTimeoutException ce) { logger.log(Level.WARNING, "ConnectTimeoutException occurred", ce); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (SocketTimeoutException se) { logger.log(Level.WARNING, "SocketTimeoutException occurred", se); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (ClientProtocolException pe) { logger.log(Level.SEVERE, "The protocol was not http; https is suspected", pe); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); ldstTO.setHttpProtocol(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (IOException ex) { logger.log(Level.SEVERE, "IO exception occurs", ex); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } finally { if (entity != null) { try { EntityUtils.consume(entity); } catch (IOException ex) { logger.log(Level.SEVERE, "io exception when entity was to be" + "consumed", ex); } } } return ldstTO; }
Code Sample 2:
public void testBlobB() { ResultSet rs; byte[] ba; byte[] baR1 = new byte[] { (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB }; byte[] baR2 = new byte[] { (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB }; try { connection.setAutoCommit(false); Statement st = connection.createStatement(); st.executeUpdate("DROP TABLE blo IF EXISTS"); st.executeUpdate("CREATE TABLE blo (id INTEGER, b blob( 100))"); PreparedStatement ps = connection.prepareStatement("INSERT INTO blo(id, b) values(2, ?)"); ps.setBlob(1, new SerialBlob(baR1)); ps.executeUpdate(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } java.sql.Blob blob1 = rs.getBlob("b"); System.out.println("Size of retrieved blob: " + blob1.length()); byte[] baOut = blob1.getBytes(1, (int) blob1.length()); if (baOut.length != baR1.length) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } for (int i = 0; i < baOut.length; i++) { if (baOut[i] != baR1[i]) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } } rs.close(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } blob1 = rs.getBlob("b"); ba = blob1.getBytes(1, baR2.length); if (ba.length != baR2.length) { assertTrue("row2 byte length differs", false); } for (int i = 0; i < ba.length; i++) { if (ba[i] != baR1[i]) { assertTrue("row2 byte " + i + " differs", false); } } rs.close(); connection.rollback(); ps.setBinaryStream(1, new HsqlByteArrayInputStream(baR1), baR1.length); ps.executeUpdate(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } blob1 = rs.getBlob("b"); System.out.println("Size of retrieved blob: " + blob1.length()); baOut = blob1.getBytes(1, (int) blob1.length()); if (baOut.length != baR1.length) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } for (int i = 0; i < baOut.length; i++) { if (baOut[i] != baR1[i]) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } } rs.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); fail("test failure"); } }
|
11
|
Code Sample 1:
public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public CmsSetupTestResult execute(CmsSetupBean setupBean) { CmsSetupTestResult testResult = new CmsSetupTestResult(this); String basePath = setupBean.getWebAppRfsPath(); if (!basePath.endsWith(File.separator)) { basePath += File.separator; } File file1; Random rnd = new Random(); do { file1 = new File(basePath + "test" + rnd.nextInt(1000)); } while (file1.exists()); boolean success = false; try { file1.createNewFile(); FileWriter fw = new FileWriter(file1); fw.write("aA1"); fw.close(); success = true; FileReader fr = new FileReader(file1); success = success && (fr.read() == 'a'); success = success && (fr.read() == 'A'); success = success && (fr.read() == '1'); success = success && (fr.read() == -1); fr.close(); success = file1.delete(); success = !file1.exists(); } catch (Exception e) { success = false; } if (!success) { testResult.setRed(); testResult.setInfo("OpenCms cannot be installed without read and write privileges for path " + basePath + "! Please check you are running your servlet container with the right user and privileges."); testResult.setHelp("Not enough permissions to create/read/write a file"); testResult.setResult(RESULT_FAILED); } else { testResult.setGreen(); testResult.setResult(RESULT_PASSED); } return testResult; }
|
11
|
Code Sample 1:
private static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("�������� ���� �� ���������" + from_file); if (!from_file.isFile()) abort("���������� ����������� ��������" + from_file); if (!from_file.canRead()) abort("�������� ���� ���������� ��� ������" + from_file); if (from_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("�������� ���� ���������� ��� ������" + to_file); System.out.println("������������ ������� ����?" + to_file.getName() + "?(Y/N):"); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("������������ ���� �� ��� �����������"); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("������� ���������� �� ���������" + parent); if (!dir.isFile()) abort("�� �������� ���������" + parent); if (!dir.canWrite()) abort("������ �� ������" + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public static void streamCopyFile(File srcFile, File destFile) { try { FileInputStream fi = new FileInputStream(srcFile); FileOutputStream fo = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int readLength = 0; while (readLength != -1) { readLength = fi.read(buf); if (readLength != -1) { fo.write(buf, 0, readLength); } } fo.close(); fi.close(); } catch (Exception e) { } }
|
11
|
Code Sample 1:
public void onCreate() { window = ((Window) getFellow("win")); userName = ((Textbox) getFellow("user")); password = ((Textbox) getFellow("password")); session = window.getDesktop().getSession(); if (Executions.getCurrent().getParameter("login") != null) { login = Executions.getCurrent().getParameter("login"); session.setAttribute("login", login); } if (Executions.getCurrent().getParameter("password") != null) { passwordu = Executions.getCurrent().getParameter("password"); } if (Executions.getCurrent().getParameter("option") != null) { option = Executions.getCurrent().getParameter("option"); session.setAttribute("option", option); } if (Executions.getCurrent().getParameter("organization") != null) { organization = Executions.getCurrent().getParameter("organization"); session.setAttribute("organization", organization); } if (Executions.getCurrent().getParameter("project") != null) { project = Executions.getCurrent().getParameter("project"); session.setAttribute("project", project); } if (login != null) { User user = UserDAO.getUserByUserName(login); if (user != null) { String encodedPassword = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(user.getPassword().getBytes()); BASE64Encoder encoder = new BASE64Encoder(); encodedPassword = encoder.encode(digest.digest()); } catch (Exception e) { } if (passwordu.compareTo(encodedPassword) == 0) { session.setAttribute("user", user); session.setAttribute("numero", 5); session.setAttribute("option", option); session.setAttribute("organization", organization); session.setAttribute("project", project); Executions.sendRedirect("menu.zul"); } } } }
Code Sample 2:
public static String cryptografar(String senha) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(senha.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); senha = hash.toString(16); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); } return senha; }
|
00
|
Code Sample 1:
public boolean loadFile(String inpfile) { if (osmlContainer == null) return false; hApdx.clear(); try { BufferedReader in = null; if (inpfile.indexOf("http://") >= 0) { URL url = null; url = new URL(inpfile); URLConnection conn = url.openConnection(); conn.setUseCaches(false); InputStreamReader is = new InputStreamReader(conn.getInputStream()); in = new BufferedReader(is); } else { in = new BufferedReader(new FileReader(inpfile)); } String pline = null; while ((pline = in.readLine()) != null) { StringTokenizer tok = new StringTokenizer(pline, "\t\n\r"); if (tok.countTokens() < 2) continue; String name = tok.nextToken(); String apdx = tok.nextToken(); String note = ""; if (tok.countTokens() > 0) note = tok.nextToken(); if (name.length() == 0 || apdx.length() == 0) continue; OmicElementContainer element = (OmicElementContainer) OmicElementContainer.createContainer(); element.setName(name); element.setNote(note); element.addAppendix(apdx); String keys[] = commaPattern.split(apdx); for (int j = 0; j < keys.length; j++) { ArrayList v = (ArrayList) hApdx.get(keys[j]); if (v == null) v = new ArrayList(); v.add(element); hApdx.put(keys[j], v); } } in.close(); } catch (MalformedURLException mfe) { System.out.println("MalformedURLException"); return false; } catch (IOException ioe) { System.out.println("IOException"); return false; } System.out.println("appendix name list size " + hApdx.size()); if (bElementDirected) { int nCount = 0; ArrayList<OmicElementContainer> omicElementList = osmlContainer.getAllOmicElementContainers(); for (OmicElementContainer element : omicElementList) { String name = element.getName(); String apdx = element.getAppendix(); if (name.length() == 0) continue; String names[] = commaPattern.split(name); String apdxs[] = commaPattern.split(apdx); String list[] = new String[names.length + apdxs.length]; for (int j = 0; j < names.length; j++) list[j] = names[j]; for (int j = 0; j < apdxs.length; j++) list[j + names.length] = apdxs[j]; for (int j = 0; j < list.length; j++) { ArrayList v = (ArrayList) hApdx.get(list[j]); if (v == null) continue; for (int k = 0; k < v.size(); k++) { OmicElementContainer appendix = (OmicElementContainer) v.get(k); element.addAppendix(appendix.getName()); nCount++; } } } System.out.println("match appendix element " + nCount + " items"); } if (bFunctionDirected) { int nCount = 0; FunctionalClassContainer functions[] = osmlContainer.getFunctionalClassContainer("[@container=all]"); ArrayList vFunction = new ArrayList(); for (int i = 0; i < functions.length; i++) { if (!vFunction.contains(functions[i])) vFunction.add(functions[i]); } for (int i = 0; i < vFunction.size(); i++) { FunctionalClassContainer function = (FunctionalClassContainer) vFunction.get(i); String name = function.getName(); if (name.length() == 0) continue; String names[] = name.split(","); for (int j = 0; j < names.length; j++) { ArrayList v = (ArrayList) hApdx.get(names[j]); if (v == null) continue; for (int k = 0; k < v.size(); k++) { OmicElementContainer appendix = (OmicElementContainer) v.get(k); functions[i].addOmicElementContainer(appendix); nCount++; } } } System.out.println("match appendix function " + nCount + " items"); } return true; }
Code Sample 2:
private boolean serverOK(String serverAddress, String serverPort) { boolean status = false; String serverString = serverAddress + ":" + serverPort + MolConvertInNodeModel.SERVER_WSDL_PATH; System.out.println("connecting to " + serverString + "..."); try { java.net.URL url = new java.net.URL(serverString); try { java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); status = readContents(connection); if (status) { JOptionPane.showMessageDialog(this.getPanel(), "Connection to Server is OK"); } } catch (Exception connEx) { JOptionPane.showMessageDialog(this.getPanel(), connEx.getMessage()); logger.error(connEx.getMessage()); } } catch (java.net.MalformedURLException urlEx) { JOptionPane.showMessageDialog(this.getPanel(), urlEx.getMessage()); logger.error(urlEx.getMessage()); } return status; }
|
00
|
Code Sample 1:
public static Map<VariableLengthInteger, ElementDescriptor> readDescriptors(URL url) throws IOException, XMLStreamException { if (url == null) { throw new IllegalArgumentException("url is null"); } InputStream stream = new BufferedInputStream(url.openStream()); try { return readDescriptors(stream); } finally { try { stream.close(); } catch (IOException ignored) { } } }
Code Sample 2:
public static int convertImage(InputStream is, OutputStream os, String command) throws IOException, InterruptedException { if (logger.isInfoEnabled()) { logger.info(command); } Process p = Runtime.getRuntime().exec(command); ByteArrayOutputStream errOut = new ByteArrayOutputStream(); StreamGobbler errGobbler = new StreamGobbler(p.getErrorStream(), errOut, "Convert Thread (err gobbler): " + command); errGobbler.start(); StreamGobbler outGobbler = new StreamGobbler(new BufferedInputStream(is), p.getOutputStream(), "Convert Thread (out gobbler): " + command); outGobbler.start(); try { IOUtils.copy(p.getInputStream(), os); os.flush(); if (p.waitFor() != 0) { logger.error("Unable to convert, stderr: " + new String(errOut.toByteArray(), "UTF-8")); } return p.exitValue(); } finally { IOUtils.closeQuietly(os); } }
|
11
|
Code Sample 1:
protected void download(URL url, File destination, long beginRange, long endRange, long totalFileSize, boolean appendToFile) throws DownloadException { System.out.println(" DOWNLOAD REQUEST RECEIVED " + url.toString() + " \n\tbeginRange : " + beginRange + " - EndRange " + endRange + " \n\t to -> " + destination.getAbsolutePath()); try { if (destination.exists() && !appendToFile) { destination.delete(); } if (!destination.exists()) destination.createNewFile(); GetMethod get = new GetMethod(url.toString()); HttpClient httpClient = new HttpClient(); Header rangeHeader = new Header(); rangeHeader.setName("Range"); rangeHeader.setValue("bytes=" + beginRange + "-" + endRange); get.setRequestHeader(rangeHeader); httpClient.executeMethod(get); int statusCode = get.getStatusCode(); if (statusCode >= 400 && statusCode < 500) throw new DownloadException("The file does not exist in this location : message from server -> " + statusCode + " " + get.getStatusText()); InputStream input = get.getResponseBodyAsStream(); OutputStream output = new FileOutputStream(destination, appendToFile); try { int length = IOUtils.copy(input, output); System.out.println(" Length : " + length); } finally { input.close(); output.flush(); output.close(); } } catch (Exception e) { e.printStackTrace(); logger.error("Unable to figure out the length of the file from the URL : " + e.getMessage()); throw new DownloadException("Unable to figure out the length of the file from the URL : " + e.getMessage()); } }
Code Sample 2:
private void loadMascotLibrary() { if (isMascotLibraryLoaded) return; try { boolean isLinux = false; boolean isAMD64 = false; String mascotLibraryFile; if (Configurator.getOSName().toLowerCase().contains("linux")) { isLinux = true; } if (Configurator.getOSArch().toLowerCase().contains("amd64")) { isAMD64 = true; } if (isLinux) { if (isAMD64) { mascotLibraryFile = "libmsparserj-64.so"; } else { mascotLibraryFile = "libmsparserj-32.so"; } } else { if (isAMD64) { mascotLibraryFile = "msparserj-64.dll"; } else { mascotLibraryFile = "msparserj-32.dll"; } } logger.warn("Using: " + mascotLibraryFile); URL mascot_lib = MascotDAO.class.getClassLoader().getResource(mascotLibraryFile); if (mascot_lib != null) { logger.debug("Mascot library URL: " + mascot_lib); tmpMascotLibraryFile = File.createTempFile("libmascot.so.", ".tmp", new File(System.getProperty("java.io.tmpdir"))); InputStream in = mascot_lib.openStream(); OutputStream out = new FileOutputStream(tmpMascotLibraryFile); IOUtils.copy(in, out); in.close(); out.close(); System.load(tmpMascotLibraryFile.getAbsolutePath()); isMascotLibraryLoaded = true; } else { throw new ConverterException("Could not load Mascot Library for system: " + Configurator.getOSName() + Configurator.getOSArch()); } } catch (IOException e) { throw new ConverterException("Error loading Mascot library: " + e.getMessage(), e); } }
|
11
|
Code Sample 1:
public void testAddingEntries() throws Exception { DiskCache c = new DiskCache(); { c.setRoot(rootFolder.getAbsolutePath()); c.setHtmlExtension("htm"); c.setPropertiesExtension("txt"); assertEquals("htm", c.getHtmlExtension()); assertEquals("txt", c.getPropertiesExtension()); assertEquals(rootFolder.getAbsolutePath(), c.getRoot()); } String key1 = "cat1/key1"; String key2 = "cat1/key2"; try { try { { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(300005L); i.setTranslationCount(10); i.setEncoding("ISO-8859-7"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = new ByteArrayInputStream(greekTextBytes); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } c.storeInCache(key1, i); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key2, null); CacheItem i = c.getOrCreateCacheEntry(key2); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(350000L); i.setTranslationCount(11); i.setEncoding("ISO-8859-1"); i.setHeader(new ResponseHeaderImpl("Test3", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test4", new String[] { "Value1" })); String englishText = "Hello this is another example"; { InputStream input = new ByteArrayInputStream(englishText.getBytes("ISO-8859-1")); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[29]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test3", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test4", h.getName()); assertEquals("[Value1]", Arrays.toString(h.getValues())); } } } c.storeInCache(key2, i); assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-1"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(englishText, w.toString()); } } { CacheItem i = c.getOrCreateCacheEntry(key1); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); } } finally { c.removeCacheEntry(key1, null); } } finally { c.removeCacheEntry(key2, null); } }
Code Sample 2:
private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
00
|
Code Sample 1:
public static Bitmap loadPhotoBitmap(final String imageUrl, final String type) { InputStream imageStream = null; try { HttpGet httpRequest = new HttpGet(new URL(imageUrl).toURI()); HttpResponse response = (HttpResponse) new DefaultHttpClient().execute(httpRequest); httpRequest = null; BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity()); response = null; imageStream = bufHttpEntity.getContent(); bufHttpEntity = null; if (imageStream != null) { final BitmapFactory.Options options = new BitmapFactory.Options(); if (type.equals("image")) { options.inSampleSize = 2; } return BitmapFactory.decodeStream(imageStream, null, options); } else { } } catch (IOException e) { } catch (URISyntaxException e) { } finally { if (imageStream != null) closeStream(imageStream); } return null; }
Code Sample 2:
public String getValidationKey(String transactionId, double transactionAmount) { try { java.security.MessageDigest d = java.security.MessageDigest.getInstance("MD5"); d.reset(); String value = this.getPostingKey() + transactionId + transactionAmount; d.update(value.getBytes()); byte[] buf = d.digest(); return Base64.encodeBytes(buf); } catch (java.security.NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
|
11
|
Code Sample 1:
public static void copyFile1(File srcFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); FileChannel source = fis.getChannel(); FileChannel destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); fis.close(); fos.close(); }
Code Sample 2:
public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); }
|
00
|
Code Sample 1:
private void checkUrl(URL url) throws IOException { File urlFile = new File(url.getFile()); assertEquals(file.getCanonicalPath(), urlFile.getCanonicalPath()); System.out.println("Using url " + url); InputStream openStream = url.openStream(); assertNotNull(openStream); }
Code Sample 2:
public String md5sum(String toCompute) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toCompute.getBytes()); java.math.BigInteger hash = new java.math.BigInteger(1, md.digest()); return hash.toString(16); }
|
11
|
Code Sample 1:
public static void copyFile(String source, String destination, TimeSlotTracker timeSlotTracker) { LOG.info("copying [" + source + "] to [" + destination + "]"); BufferedInputStream sourceStream = null; BufferedOutputStream destStream = null; try { File destinationFile = new File(destination); if (destinationFile.exists()) { destinationFile.delete(); } sourceStream = new BufferedInputStream(new FileInputStream(source)); destStream = new BufferedOutputStream(new FileOutputStream(destinationFile)); int readByte; while ((readByte = sourceStream.read()) > 0) { destStream.write(readByte); } Object[] arg = { destinationFile.getName() }; String msg = timeSlotTracker.getString("datasource.xml.copyFile.copied", arg); LOG.fine(msg); } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } finally { try { if (destStream != null) { destStream.close(); } if (sourceStream != null) { sourceStream.close(); } } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } } }
Code Sample 2:
@RequestMapping(value = "/image/{fileName}", method = RequestMethod.GET) public void getImage(@PathVariable String fileName, HttpServletRequest req, HttpServletResponse res) throws Exception { File file = new File(STORAGE_PATH + fileName + ".jpg"); res.setHeader("Cache-Control", "no-store"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); res.setContentType("image/jpg"); ServletOutputStream ostream = res.getOutputStream(); IOUtils.copy(new FileInputStream(file), ostream); ostream.flush(); ostream.close(); }
|
00
|
Code Sample 1:
private static synchronized void find(String name) throws SAXException, IOException { if (c_cache.containsKey(name)) return; CustomHandler handler = null; URL url = null; String validatorFiles = (String) Config.getProperty(Config.PROP_RULES_ENGINE_VALIDATORS_URL_LIST, XML_FILE); for (StringTokenizer strtknzr = new StringTokenizer(validatorFiles, ","); strtknzr.hasMoreTokens(); ) { String validatorFile = strtknzr.nextToken(); try { url = URLHelper.newExtendedURL(validatorFile); } catch (MalformedURLException e) { url = null; } if (url == null) throw new FileNotFoundException("File not found - " + validatorFile); try { handler = new CustomHandler(name); XMLReader reader = XMLReaderFactory.createXMLReader(PARSER_NAME); reader.setContentHandler(handler); reader.setEntityResolver(new DefaultEntityResolver()); reader.setErrorHandler(new DefaultErrorHandler()); reader.parse(new InputSource(url.openStream())); } catch (SAXException e) { if (SUCCESS_MESSAGE.equals(e.getMessage()) && handler != null) break; else throw e; } catch (IOException e) { throw e; } if (handler.getFieldValidatorMetaData() != null) break; } c_cache.put(name, handler != null ? handler.getFieldValidatorMetaData() : null); }
Code Sample 2:
public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.