@Override public long getSpace(String path, SpaceType type) throws IOException { File file = new File(path); switch (type) { case SPACE_TOTAL: return file.getTotalSpace(); case SPACE_FREE: return file.getFreeSpace(); case SPACE_USED: return file.getTotalSpace() - file.getFreeSpace(); default: throw new IOException("Unknown getSpace parameter: " + type); } }
public static Result upload() { try { Http.MultipartFormData body = request().body().asMultipartFormData(); Http.MultipartFormData.FilePart picture = body.getFile("picture"); if (picture != null) { String fileName = picture.getFilename(); logger.info("Uploading file name: {}", fileName); File pictureFile = picture.getFile(); pictureFile.getTotalSpace(); logger.info("Total space: {}", pictureFile); File folder = pictureFile.getParentFile(); File renamedFile = new File(folder, fileName); File result = ExifImageUtils.rotateFromOrientationData(pictureFile, renamedFile); // final String absolutePath = pictureFile.getAbsolutePath(); // final String escapedPath = UrlEscapers.urlPathSegmentEscaper().escape(absolutePath); // return ok(views.html.main.render(escapedPath)); return ok(views.html.main.render(result.getAbsolutePath())); } return ok("asdf"); } catch (Exception e) { logger.error("Error uploading", e); return internalServerError(e.getMessage()); } }
public static void main(String[] args) { // We create an instance of a File to represent a partition // of our file system. For instance here we used a drive D: // as in Windows operating system. File file = new File("/home/local/ZOHOCORP/venkat-0773/webnms/5.2_astro/state/traps"); File file2 = new File("/home/local/ZOHOCORP/venkat-0773/webnms/5.2_astro/state/"); File file3 = new File("/home/local/ZOHOCORP/venkat-0773/webnms/5.2_astro"); // Using the getTotalSpace() we can get an information of // the actual size of the partition, and we convert it to // mega bytes. long totalSpace = file.getTotalSpace() / (1024 * 1024); /*System.err.println("file.length :: "+getFolderSize(file)); System.err.println("file2.length :: "+getFolderSize(file2)); System.err.println("file3.length :: "+getFolderSize(file3));*/ System.err.println( "file.sizeOfDirectory :: " + org.apache.commons.io.FileUtils.sizeOfDirectory(file3)); // Next we get the free disk space as the name of the // method shown us, and also get the size in mega bytes. long freeSpace = file.getFreeSpace() / (1024 * 1024); // Just print out the values. System.out.println("Total Space1 = " + totalSpace + " Mega Bytes"); System.out.println("Free Space1 = " + freeSpace + " Mega Bytes"); System.out.println("Free Space3 = " + Runtime.getRuntime().totalMemory() + " Mega Bytes"); System.out.println("Free Space4 = " + Runtime.getRuntime().freeMemory() + " Mega Bytes"); System.out.println("Free Space5 = " + Runtime.getRuntime().maxMemory() + "Bytes"); System.out.println( "Free Space6 = " + ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage() + "Bytes"); System.out.println( "Free Space7 = " + ManagementFactory.getMemoryMXBean().getHeapMemoryUsage() + "Bytes"); System.out.println("Free Space8 = " + file.getUsableSpace() / 1024 / 1024 + " Mega Bytes"); }
@Ignore @Test public void crash() throws Exception { // Reproduces SIGBUS crash. Requires writing direct buffers // to a mapped file when there is not enough space left. To avoid having // to fill up a primary device use a small ramdisk, or loop device. E.g. // $ dd if=/dev/zero of=file.img bs=1M count=100 // $ losetup /dev/loop0 file.img // $ mkfs.ext4 /dev/loop0 // $ mkdir -p root // $ mount -t ext4 /dev/loop0 root assumeTrue(Platform.isLinux()); File f = new File("root/test.file"); if (f.exists()) f.delete(); FileIO fio = FileIO.open(f, EnumSet.of(OpenOption.CREATE, OpenOption.PREALLOCATE)); final long len = f.getTotalSpace() * 5L; fio.setLength(len); fio.map(); ByteBuffer bb = ByteBuffer.allocateDirect(4097); for (long pos = 0; pos < len - bb.remaining(); pos += 512) { fio.write(pos, bb); bb.flip(); } fio.close(); }
public static String getStat() { StringBuilder stat = new StringBuilder(); stat.append("Available processors (cores): ") .append(Runtime.getRuntime().availableProcessors()); /* Total amount of free memory available to the JVM */ stat.append("\nFree memory (bytes): ").append(Runtime.getRuntime().freeMemory()); /* This will return Long.MAX_VALUE if there is no preset limit */ long maxMemory = Runtime.getRuntime().maxMemory(); /* Maximum amount of memory the JVM will attempt to use */ stat.append("\nMaximum memory (bytes): ") .append(maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory); /* Total memory currently in use by the JVM */ stat.append("\nTotal memory (bytes): ").append(Runtime.getRuntime().totalMemory()); /* Get a list of all filesystem roots on this system */ File[] roots = File.listRoots(); /* For each filesystem root, print some info */ for (File root : roots) { stat.append("\nFile system root: ").append(root.getAbsolutePath()); stat.append("\nTotal space (bytes): ").append(root.getTotalSpace()); stat.append("\nFree space (bytes): ").append(root.getFreeSpace()); stat.append("\nUsable space (bytes): ").append(root.getUsableSpace()); } return stat.toString(); }
public FileStoreStorageSummary( @Nullable File binariesFolder, BinaryProviderType binariesStorageType) { this.binariesFolder = binariesFolder; this.binariesStorageType = binariesStorageType; freeSpace = binariesFolder != null ? binariesFolder.getFreeSpace() : 0; totalSpace = binariesFolder != null ? binariesFolder.getTotalSpace() : 0; usedSpace = totalSpace - freeSpace; }
public static String construct(String uid, String key) throws JSONException, SigarException { JSONObject construct = new JSONObject(); construct.put("uid", uid); construct.put("key", key); construct.put("hostname", sigar.getNetInfo().getHostName()); JSONObject obj = new JSONObject(); obj.put("uptime", formatUptime(sigar.getUptime().getUptime())); obj.put("load1", ((int) (sigar.getCpuPerc().getCombined() * 100))); obj.put("load5", 0); obj.put("load15", 0); construct.put("uplo", obj); Mem mem = sigar.getMem(); JSONObject memory = new JSONObject(); memory.put("total", byteToMByte(mem.getTotal())); memory.put("used", byteToMByte(mem.getUsed())); memory.put("free", byteToMByte(mem.getFree())); memory.put("bufcac", 0); construct.put("ram", memory); LinkedList<HashMap<String, Object>> fsystems = new LinkedList<HashMap<String, Object>>(); long total = 0; long used = 0; long free = 0; for (File file : File.listRoots()) { long ftotal = file.getTotalSpace(); long ffree = file.getFreeSpace(); long fused = ftotal - ffree; HashMap<String, Object> system = new HashMap<String, Object>(); system.put("mount", file.getPath()); system.put("total", byteToKByte(ftotal)); system.put("used", byteToKByte(fused)); system.put("avail", byteToKByte(ffree)); fsystems.add(system); total += ftotal; free += ffree; used += fused; } HashMap<String, Object> bla = new HashMap<String, Object>(); bla.put("single", fsystems); HashMap<String, Object> tot = new HashMap<String, Object>(); tot.put("total", byteToKByte(total)); tot.put("free", byteToKByte(free)); tot.put("used", byteToKByte(used)); bla.put("total", tot); construct.put("disk", bla); return construct.toString(); }
@Override public FsStatus getStatus(Path p) throws IOException { File partition = pathToFile(p == null ? new Path("/") : p); // File provides getUsableSpace() and getFreeSpace() // File provides no API to obtain used space, assume used = total - free return new FsStatus( partition.getTotalSpace(), partition.getTotalSpace() - partition.getFreeSpace(), partition.getFreeSpace()); }
/** * 获取当前系统的磁盘占用率 * * @return */ public double getDiskState() { File[] roots = File.listRoots(); // 获取磁盘分区列表 double totalDisk = 0, freeDisk = 0, diskPercentage; for (File file : roots) { totalDisk += file.getTotalSpace() / 1024 / 1024 / 1024; freeDisk += file.getFreeSpace() / 1024 / 1024 / 1024; } diskPercentage = 100 * (totalDisk - freeDisk) / totalDisk; return diskPercentage; }
/** * 上传文件 * * @param file * @param url * @return */ public static void upLoadFile( String TaskTag, OnDataReturnListener dataReturnListener, File file, String url, String Type, String params) { paramType = Type; param = params; targetURL = Constants.HOST + url; targetFile = file; if (0 != file.getTotalSpace()) { UpFileToService upFile = new UpFileToService(TaskTag, dataReturnListener); Log.v("fileSize", file.getTotalSpace() + "::::"); Log.v("Path", file.getPath()); upFile.execute(targetFile); } else { return; } }
/** * Method called when Select File method is pressed * * @param evt */ private void jButton2ActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton2ActionPerformed final JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(this); // Where frame is the parent component if (returnVal == JFileChooser.APPROVE_OPTION) { File file = null; file = fc.getSelectedFile(); gui.performSendProposal(file.getAbsolutePath(), file.getTotalSpace()); } else { // User did not choose a valid file } } // GEN-LAST:event_jButton2ActionPerformed
/** * 获取存储设备的总容量 * * @param uriStr * @return */ public static Long getTotalSpace(String uriStr) { URI uri = checkURI(uriStr); StorageDevice.DeviceType schema = StorageDevice.DeviceType.of(uri.getScheme()); if (schema == null) { return Long.valueOf(0); } switch (schema) { case FILE: File path = new File(uri.getPath()); forceMkdir(path); return path.getTotalSpace(); default: return Long.valueOf(0); } }
// 获取文件系统使用率 public static List<String> getDisk() { // 操作系统 List<String> list = new ArrayList<String>(); for (char c = 'A'; c <= 'Z'; c++) { String dirName = c + ":/"; File win = new File(dirName); if (win.exists()) { long total = (long) win.getTotalSpace(); long free = (long) win.getFreeSpace(); Double compare = (Double) (1 - free * 1.0 / total) * 100; String str = c + ":盘 已使用 " + compare.intValue() + "%"; list.add(str); } } return list; }
/** * @param path * @return -1 means path is null, 0 means path is not exist. */ @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.GINGERBREAD) public static long getTotalSpace(File path) { if (path == null) { return -1; } if (Version.hasGingerbread()) { return path.getTotalSpace(); } else { if (!path.exists()) { return 0; } else { final StatFs stats = new StatFs(path.getPath()); return (long) stats.getBlockSize() * (long) stats.getBlockCount(); } } }
@Test public void preallocateTooLarge() throws Exception { assumeTrue(Platform.isLinux()); FileIO fio = FileIO.open(file, EnumSet.of(OpenOption.CREATE, OpenOption.MAPPED, OpenOption.PREALLOCATE)); FileStore fs = Files.getFileStore(file.toPath()); assumeTrue("ext4".equals(fs.type()) && !fs.name().contains("docker")); long len = file.getTotalSpace() * 100L; // setLength traps the IOException and prevents resizing / remapping. Not remapping avoids // the SIGBUS issue. fio.setLength(len); assertEquals(0, fio.length()); fio.close(); }
/** * Initialize this index from the given file. * * @param indexFile the file from which this index is to be initialized * @return <code>true</code> if the index was correctly initialized */ private boolean initializeIndexFrom(File indexFile) { if (indexFile == null) { if (DartCoreDebug.TRACE_INDEX_STATISTICS) { DartCore.logInformation("Index file was null"); } return false; } else if (!indexFile.exists()) { if (DartCoreDebug.TRACE_INDEX_STATISTICS) { DartCore.logInformation("Index file " + indexFile.getAbsolutePath() + " does not exist"); } return false; } if (DartCoreDebug.TRACE_INDEX_STATISTICS) { DartCore.logInformation( "About to initialize the index from file " + indexFile.getAbsolutePath() + " (size = " + indexFile.getTotalSpace() + " bytes)"); } try { boolean wasRead = readIndexFrom(indexFile); if (DartCoreDebug.TRACE_INDEX_STATISTICS) { logIndexStats("After initializing the index from file " + indexFile.getAbsolutePath()); } synchronized (indexStore) { return wasRead && indexStore.getResourceCount() > 0; } } catch (Exception exception) { DartCore.logError("Could not read index file " + indexFile.getAbsolutePath(), exception); } if (DartCoreDebug.TRACE_INDEX_STATISTICS) { logIndexStats("Deleting corrupted index file " + indexFile.getAbsolutePath()); } try { indexFile.delete(); } catch (Exception exception) { DartCore.logError( "Could not delete corrupt index file " + indexFile.getAbsolutePath(), exception); } return false; }
@Override public FsStats fsStats() { final Map<String, FsStats.Filesystem> filesystems = new HashMap<>(locations.size()); for (File location : locations) { final String path = location.getAbsolutePath(); final long total = location.getTotalSpace(); final long free = location.getFreeSpace(); final long available = location.getUsableSpace(); final long used = total - free; final short usedPercent = (short) ((double) used / total * 100); final FsStats.Filesystem filesystem = FsStats.Filesystem.create(path, total, free, available, used, usedPercent); filesystems.put(path, filesystem); } return FsStats.create(filesystems); }
/* * TODO: Finish method. */ public static String readBytesFromFile(File filename) throws IOException, OverlappingFileLockException { if (!filename.exists()) { return null; } try { ByteBuffer buffer = ByteBuffer.allocate(((int) filename.getTotalSpace() * 4)); fileReader = new FileInputStream(filename).getChannel(); FileLock lock = fileReader.tryLock(); if (lock != null) { fileReader.read(buffer); } else { throw new OverlappingFileLockException(); } } finally { fileWriter.close(); } return ""; }
private void initUpload(final PictureFile pictureFile, File localFile, String remoteName) { String absoluteLocalPath = localFile.getAbsolutePath(); final long size = localFile.getTotalSpace(); awsUploadHelper.upload( localFile, remoteName, new UploadStateListener(absoluteLocalPath) { @Override public void onCompleted(long countBytesTransfered) { onUploadCompleted(pictureFile); OnUploadStateChanged( pictureFile, ServiceInnerUploadState.COMPLETED, countBytesTransfered, size); } @Override public void onInit(long countBytesTransfered) { onUploadInit(pictureFile); OnUploadStateChanged( pictureFile, ServiceInnerUploadState.INIT, countBytesTransfered, size); } @Override public void onProgress(long countBytesTransfered) { onUploadInProgress(pictureFile); OnUploadStateChanged( pictureFile, ServiceInnerUploadState.IN_PROGRESS, countBytesTransfered, size); } @Override public void onFail(long countBytesTransfered) { onUploadFailed(pictureFile); OnUploadStateChanged( pictureFile, ServiceInnerUploadState.FAILED, countBytesTransfered, size); } }); }
/** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { System.out.println(" MANILYZER TESTING"); FeatureExtraction F1 = new FeatureExtraction(); System.out.println( "GENERATE FEATURE VECTOR FILE (CSV) CONTAINING " + F1.getFeature_count("C://Manilyzer//Feature_List.txt") + " FEATURES"); System.out.println(""); PrintStream console = System.err; File error = new File("err.txt"); FileOutputStream fos = new FileOutputStream(error); PrintStream ps = new PrintStream(fos); System.setErr(ps); /* Malware Human Readable XML files */ File malware_folder = new File("C://Manilyzer//data//malware"); File[] list_of_files_malware = malware_folder.listFiles(); /* Benign Human Readable XML file */ File benign_folder = new File("C://Manilyzer//data//benign"); File[] list_of_files_benign = benign_folder.listFiles(); int file_exists = F1.CreateFeatureCSV("C://Manilyzer", "C://Manilyzer//Feature_List.txt"); System.out.println(""); if (file_exists == 1) { System.out.println("GENERATE FEATURE VECTOR FOR MALWARE SAMPLES "); for (File file : list_of_files_malware) { if (file.getTotalSpace() > 0) F1.generateFeatureVector(file.getPath(), true, file.getName()); } System.out.println("GENERATE FEATURE VECTOR FOR BENIGN SAMPLES "); for (File file : list_of_files_benign) { if (file.getTotalSpace() > 0) F1.generateFeatureVector(file.getPath(), false, file.getName()); } } else { System.out.println("FEATURE VECTOR FILE ALREADY EXISTS "); } System.out.println(); System.out.println("SMS MALWARES CONTAINED IN THE MALWARE DUMP "); SMSMalwareDetection sms = new SMSMalwareDetection(); for (File file : list_of_files_malware) { if (file.getTotalSpace() > 0) sms.DetermineSMSMalware(file.getPath(), true, file.getName()); } FeatureClassification classify = new FeatureClassification(); System.out.println(""); System.out.println("FEATURE CLASSIFICATION"); System.out.println(); System.out.println("NAIVE BAYES FEATURE CLASSIFICATION"); classify.classifyNaiveBayes("C://Manilyzer"); System.out.println("J48 FEATURE CLASSIFICATION"); classify.classifyJ48Trees("C://Manilyzer"); }
/** * Gets File System Information. * * @return An array of {@link OSFileStore} objects representing mounted volumes. May return * disconnected volumes with {@link OSFileStore#getTotalSpace()} = 0. */ @Override public OSFileStore[] getFileStores() { // Open a DiskArbitration session to get VolumeName of file systems with // bsd names DASessionRef session = DiskArbitration.INSTANCE.DASessionCreate(CfUtil.ALLOCATOR); if (session == null) { LOG.error("Unable to open session to DiskArbitration framework."); } // List of file systems List<OSFileStore> fsList = new ArrayList<>(); // Use getfsstat to find fileSystems // Query with null to get total # required int numfs = SystemB.INSTANCE.getfsstat64(null, 0, 0); if (numfs > 0) { // Create array to hold results Statfs[] fs = new Statfs[numfs]; // Fill array with results numfs = SystemB.INSTANCE.getfsstat64(fs, numfs * new Statfs().size(), SystemB.MNT_NOWAIT); for (int f = 0; f < numfs; f++) { // Mount on name will match mounted path, e.g. /Volumes/foo // Mount to name will match canonical path., e.g., /dev/disk0s2 // Byte arrays are null-terminated strings // Get volume name String volume = new String(fs[f].f_mntfromname).trim(); // Skip system types if (volume.equals("devfs") || volume.startsWith("map ")) { continue; } // Set description String description = "Volume"; if (LOCAL_DISK.matcher(volume).matches()) { description = "Local Disk"; } if (volume.startsWith("localhost:") || volume.startsWith("//")) { description = "Network Drive"; } // Set type and path String type = new String(fs[f].f_fstypename).trim(); String path = new String(fs[f].f_mntonname).trim(); // Set name and uuid String name = ""; String uuid = ""; // Use volume to find DiskArbitration volume name and search for // the registry entry for UUID String bsdName = volume.replace("/dev/disk", "disk"); if (bsdName.startsWith("disk")) { // Get the DiskArbitration dictionary for this disk, // which has volumename DADiskRef disk = DiskArbitration.INSTANCE.DADiskCreateFromBSDName(CfUtil.ALLOCATOR, session, volume); if (disk != null) { CFDictionaryRef diskInfo = DiskArbitration.INSTANCE.DADiskCopyDescription(disk); if (diskInfo != null) { // get volume name from its key Pointer volumePtr = CoreFoundation.INSTANCE.CFDictionaryGetValue( diskInfo, CfUtil.getCFString("DAVolumeName")); name = CfUtil.cfPointerToString(volumePtr); CfUtil.release(diskInfo); } CfUtil.release(disk); } // Search for bsd name in IOKit registry for UUID CFMutableDictionaryRef matchingDict = IOKitUtil.getBSDNameMatchingDict(bsdName); if (matchingDict != null) { // search for all IOservices that match the bsd name IntByReference fsIter = new IntByReference(); IOKitUtil.getMatchingServices(matchingDict, fsIter); // getMatchingServices releases matchingDict // Should only match one logical drive int fsEntry = IOKit.INSTANCE.IOIteratorNext(fsIter.getValue()); if (fsEntry != 0 && IOKit.INSTANCE.IOObjectConformsTo(fsEntry, "IOMedia")) { // Now get the UUID uuid = IOKitUtil.getIORegistryStringProperty(fsEntry, "UUID"); if (uuid == null) { uuid = ""; } else { uuid = uuid.toLowerCase(); } IOKit.INSTANCE.IOObjectRelease(fsEntry); } IOKit.INSTANCE.IOObjectRelease(fsIter.getValue()); } } File file = new File(path); if (name.isEmpty()) { name = file.getName(); // getName() for / is still blank, so: if (name.isEmpty()) { name = file.getPath(); } } // Add to the list fsList.add( new OSFileStore( name, volume, path, description, type, uuid, file.getUsableSpace(), file.getTotalSpace())); } } // Close DA session CfUtil.release(session); return fsList.toArray(new OSFileStore[fsList.size()]); }
@SuppressWarnings("unchecked") public String execute() { String sawsdlExt = ".sawsdl"; String wsdlExt = ".wsdl"; String sawadlExt = ".sawadl"; String wadlExt = ".wadl"; StringBuffer buf = new StringBuffer(); SAXBuilder sbuilder = new SAXBuilder(); Document doc = null; @SuppressWarnings("rawtypes") Map session = ActionContext.getContext().getSession(); String importURL = ""; errormsg = ""; String filename = ""; System.out.println("wsloc = " + wsloc); if (WSFile != null) System.out.println("OWLFile size = " + WSFile.getTotalSpace()); try { XMLParser wsParser = null; session.remove("wsname"); session.remove("wsdlparser"); session.remove("wadlparser"); if (wsloc.indexOf("http:") != -1) { importURL = wsloc; if (wsloc.equalsIgnoreCase(wsdlExt) || wsloc.equalsIgnoreCase(sawsdlExt)) { doc = sbuilder.build(importURL); wsParser = new SAWSDLParser(doc); session.put("wsdlparser", wsParser); session.remove("wadlparser"); int start = importURL.lastIndexOf("/"); filename = importURL.substring(start, importURL.length()); session.put("wsname", filename); } else if (wsloc.equalsIgnoreCase(wadlExt) || wsloc.equalsIgnoreCase(sawadlExt)) { doc = sbuilder.build(importURL); wsParser = new WADLParser(doc); session.put("wadlparser", wsParser); session.remove("wsdlparser"); int start = importURL.lastIndexOf("/"); filename = importURL.substring(start, importURL.length()); session.put("wsname", filename); } } else { if (WSFile != null) { if (wsloc.endsWith(wsdlExt) || wsloc.endsWith(sawsdlExt)) { doc = sbuilder.build(WSFile); wsParser = new SAWSDLParser(doc); session.put("wsdlparser", wsParser); filename = wsloc; session.put("wsname", filename); } else if (wsloc.endsWith(wadlExt) || wsloc.endsWith(sawadlExt)) { doc = sbuilder.build(WSFile); wsParser = new WADLParser(doc); session.put("wadlparser", wsParser); filename = wsloc; session.put("wsname", filename); } else { errormsg = "File is not wsdl or wadl file."; } } else { errormsg = "WSDL file lost."; } } if (wsParser == null) { errormsg = "WSDL is invalidate"; return ERROR; } if (isWSDL(doc)) { boolean hasSAWSDLNS = false; @SuppressWarnings("rawtypes") List nameSpaces = doc.getRootElement().getAdditionalNamespaces(); for (int i = 0; i < nameSpaces.size(); i++) { Namespace ns = (Namespace) nameSpaces.get(i); if (ns.getURI().equalsIgnoreCase(SAWSDLParser.sawsdlNS.getURI())) { hasSAWSDLNS = true; break; } } if (!hasSAWSDLNS) { doc.getRootElement().addNamespaceDeclaration(SAWSDLParser.sawsdlNS); } boolean wsdlV1 = ((SAWSDLParser) wsParser).isWsdlV1(); if (wsdlV1 == true) { LoadWSDLTree.loadWSDL((SAWSDLParser) wsParser, buf, filename); } else { // not implement yet } innerTreeHtml = buf.toString(); type = "wsdl"; } else if (isWADL(doc)) { // not implement yet LoadWADLTree.loadWADL((WADLParser) wsParser, buf, wsloc); innerTreeHtml = buf.toString(); type = "wadl"; } } catch (IOException e) { e.printStackTrace(); errormsg = e.toString(); } catch (URISyntaxException e) { e.printStackTrace(); errormsg = e.toString(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); errormsg = e.toString(); } catch (JDOMException e) { e.printStackTrace(); errormsg = e.toString(); } catch (Exception e) { e.printStackTrace(); errormsg = e.toString(); } System.out.println("errormsg = " + errormsg); System.out.println("draw finish"); return SUCCESS; }
/** 使用andbase框架 聊天图片上传的方法 @2015-11-16 */ public static void UpLoadImage_Chat( final Context context, Uri uri, String QuestionId, String userId, String toUserId, String petId, final Trancaction trancaction) { AbHttpUtil mAbHttpUtil = AbHttpUtil.getInstance(context); String url = DataInit.httpHead + "chatLogImgSave" + ".action"; AbRequestParams params = new AbRequestParams(); File file1 = null; try { // 多文件上传添加多个即可 file1 = new File(ImageTool.getPath(context, uri)); if (!file1.exists()) { throw new Exception("图片路径错误"); } if (file1.getTotalSpace() > 4 * 1024 * 1024) { Point point = ImageTool.getScreenSize(context); Bitmap bitmap = ImageTool.readUri(uri, context, point.y, point.y, true); String ImagesDir = BaseDataManager.getMyBaseDataManager(context).getDataInit().getSD_Directory(); Log.i("正常", "图片过大,转换中的路径ImagesDir=" + ImagesDir); String fileName = file1.getName(); ImageTool.saveFile(bitmap, fileName, ImagesDir); file1 = new File(ImagesDir, fileName); } params.put("fileName", file1.getName()); params.put("file", file1); params.put("id", QuestionId); params.put("userId", userId); params.put("toUserId", toUserId); params.put("petId", petId); } catch (Exception e) { Log.e("异常201511161459", e.toString()); return; } mAbHttpUtil.post( url, params, new AbStringHttpResponseListener() { @Override public void onSuccess(int statusCode, String content) { Log.i("正常", "onSuccess=" + statusCode); try { if (statusCode == 200) { trancaction.onResponse(new JSONObject(content)); } else { trancaction.onErrorResponse(new VolleyError()); } } catch (Exception e) { Log.e("异常201512021617", e.toString()); } } // 开始执行前 @Override public void onStart() { Log.i("正常", "onStart"); } @Override public void onFailure(int statusCode, String content, Throwable error) { Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show(); } // 进度 @Override public void onProgress(int bytesWritten, int totalSize) {} // 完成后调用,失败,成功,都要调用 public void onFinish() { Log.i("正常", "结束"); } }); }
@Test public void testPersist() throws Exception { fileStorageMedia.persist(new ArrayList<>()); assertTrue(randomTmpFile.getTotalSpace() > 0L); }
/** * 使用andbase框架 头像上传的方法 @2015-11-20 * 上传用户头像图片uploadUserImg // @param id 用户id // @param file 文件 * // @param fileName 文件名字 */ public static void UpLoad_Portrait(final Context context, Uri uri) { AbHttpUtil mAbHttpUtil = AbHttpUtil.getInstance(context); String url = DataInit.httpHead + "uploadUserImg" + ".action"; AbRequestParams params = new AbRequestParams(); File file1 = null; try { // 多文件上传添加多个即可 file1 = new File(ImageTool.getPath(context, uri)); if (!file1.exists()) { throw new Exception("图片路径错误"); } if (file1.getTotalSpace() > 4 * 1024 * 1024) { Point point = ImageTool.getScreenSize(context); Bitmap bitmap = ImageTool.readUri(uri, context, point.y, point.y, true); String ImagesDir = BaseDataManager.getMyBaseDataManager(context).getDataInit().getSD_Directory(); Log.i("正常", "图片过大,转换中的路径ImagesDir=" + ImagesDir); String fileName = file1.getName(); ImageTool.saveFile(bitmap, fileName, ImagesDir); file1 = new File(ImagesDir, fileName); } params.put("fileName", file1.getName()); params.put("file", file1); params.put("id", BaseDataManager.getMyBOSSInfo(context).getId()); } catch (Exception e) { Log.e("异常201511201059", e.toString()); return; } mAbHttpUtil.post( url, params, new AbStringHttpResponseListener() { @Override public void onSuccess(int statusCode, String content) { try { JSONObject jsonObject = new JSONObject(content); Toast.makeText(context, Reader.analysis("message", jsonObject), Toast.LENGTH_SHORT) .show(); } catch (Exception e) { Log.e("异常201511201311", e.toString()); } } // 开始执行前 @Override public void onStart() { Log.i("正常", "onStart"); } @Override public void onFailure(int statusCode, String content, Throwable error) { Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show(); } // 进度 @Override public void onProgress(int bytesWritten, int totalSize) {} // 完成后调用,失败,成功,都要调用 public void onFinish() { Log.i("正常", "结束"); } }); }