Java Code Examples for java.io.IOException#printStackTrace()

The following examples show how to use java.io.IOException#printStackTrace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RedisExample.java    From java-platform with Apache License 2.0 6 votes vote down vote up
public void testPipelined() {// 0.076秒
	Jedis jedis = new Jedis("120.25.241.144", 6379);
	jedis.auth("b840fc02d52404542994");

	long start = System.currentTimeMillis();
	Pipeline pipeline = jedis.pipelined();
	for (int i = 0; i < 1000; i++) {
		pipeline.set("n" + i, "n" + i);
		System.out.println(i);
	}
	pipeline.syncAndReturnAll();
	long end = System.currentTimeMillis();
	System.out.println("共花费:" + (end - start) / 1000.0 + "秒");

	jedis.disconnect();
	try {
		Closeables.close(jedis, true);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 2
Source File: Archive.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void run() {
  final BufferedReader br = new BufferedReader(new InputStreamReader(in));
  try {
    String line = br.readLine();
    while (null != line) {
      if (null != cmd) {
        final StringBuffer sb = new StringBuffer();
        for (final String element : cmd) {
          if (sb.length() > 0)
            sb.append(" ");
          sb.append(element);
        }
        // NYI! Log error
        System.err.println("Failed to execute: '" + sb.toString() + "':");
        cmd = null;
      }
      if (copyToStdout)
        System.out.println(line);
      line = br.readLine();
    }
  } catch (final IOException _ioe) {
    _ioe.printStackTrace();
  }
}
 
Example 3
Source File: AudioPlayer.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
public void loadSoundEffects() {
	soundEffects = new ArrayList<>();
	soundEffects.add(SoundConstants.SND_EQUIPMENT);
	soundEffects.add(SoundConstants.SND_PERSON_DEAD);
	soundEffects.add(SoundConstants.SND_PERSON_FEMALE1);
	soundEffects.add(SoundConstants.SND_PERSON_FEMALE2);
	soundEffects.add(SoundConstants.SND_PERSON_MALE1);
	soundEffects.add(SoundConstants.SND_PERSON_MALE2);

	soundEffects.add(SoundConstants.SND_ROVER_MAINTENANCE);
	soundEffects.add(SoundConstants.SND_ROVER_MALFUNCTION);
	soundEffects.add(SoundConstants.SND_ROVER_MOVING);
	soundEffects.add(SoundConstants.SND_ROVER_PARKED);
	soundEffects.add(SoundConstants.SND_SETTLEMENT);

	for (String s : soundEffects) {
		try {
			allSoundClips.put(s, new OGGSoundClip(s, false));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	currentSoundClip = allSoundClips.get(SoundConstants.SND_PERSON_FEMALE1);
}
 
Example 4
Source File: NopolMojo.java    From repairnator with MIT License 6 votes vote down vote up
private String loadZ3AndGivePath() {
    boolean isMac = System.getProperty("os.name").toLowerCase().contains("mac");

    String resourcePath = (isMac)? "z3/z3_for_mac" : "z3/z3_for_linux";
    InputStream in = this.getClass().getClassLoader().getResourceAsStream(resourcePath);

    try {
        Path tempFilePath = Files.createTempFile("nopol", "z3");
        byte[] content = ByteStreams.toByteArray(in);
        Files.write(tempFilePath, content);

        tempFilePath.toFile().setExecutable(true);
        return tempFilePath.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 5
Source File: NugetProcessCompiler.java    From setupmaker with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        try
        {
            //ProcessBuilder ps = new ProcessBuilder("where", "chocolatey");
            //ProcessBuilder ps = new ProcessBuilder("chocolatey.bat", "pack");
            Process process = Runtime.getRuntime().exec("nuget pack oracle/oracle.nuspec -NoPackageAnalysis", null, new File("target/nuget"));
            //Process process = ps.start();
            
            Scanner in = new Scanner(process.getInputStream());
            
            while(in.hasNextLine()) {
                System.out.println(in.nextLine());
            }
            process.destroy();
            System.out.println(process.exitValue());
            
            in.close();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
 
Example 6
Source File: EntityCorefReferenceBaseline.java    From EventCoreference with Apache License 2.0 5 votes vote down vote up
static public void main (String [] args) {
      if (args.length==0) {
          processNafStream(System.in);
      }
      else {
          String pathToNafFile = "";
          String extension = "";
          for (int i = 0; i < args.length; i++) {
              String arg = args[i];
              if (arg.equals("--naf-file") && args.length>(i+1)) {
                  pathToNafFile = args[i+1];
              }
              else if (arg.equals("--extension") && args.length>(i+1)) {
                  extension = args[i+1];
              }
          }
          //File inpFile = new File("/Users/kyoto/Desktop/NWR-DATA/50_docs_test");
          File inpFile = new File(pathToNafFile);
          if (inpFile.isDirectory()) {
              ArrayList<File> files = Util.makeRecursiveFileList(inpFile, extension);
              for (int i = 0; i < files.size(); i++) {
                  File file = files.get(i);
                 // System.out.println("file.getAbsolutePath() = " + file.getAbsolutePath());
                  try {
                      FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()+".coref");
                      processNafFile(fos, file.getAbsolutePath());
                      fos.close();
                  } catch (IOException e) {
                      e.printStackTrace();  //To change body of catch statement ßuse File | Settings | File Templates.
                  }
              }
          }
          else {
              processNafFile(pathToNafFile);
          }
      }
}
 
Example 7
Source File: SystemUtils.java    From mobile-manager-tool with MIT License 5 votes vote down vote up
private String[] getTotalMemory() {

        String[] result = {"",""};  //1-total 2-avail
        final ActivityManager activityManager = (ActivityManager) AppMain.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(mi);

        long mTotalMem = 0;
        long mAvailMem = mi.availMem;
        String str1 = "/proc/meminfo";
        String str2;
        String[] arrayOfString;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            mTotalMem = Integer.valueOf(arrayOfString[1]).intValue() * 1024;
            localBufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        result[0] = Formatter.formatFileSize(AppMain.getInstance(), mTotalMem);
        result[1] = Formatter.formatFileSize(AppMain.getInstance(), mAvailMem);
        Log.i(">>>SystemUtils", "meminfo total:" + result[0] + " used:" + result[1]);
        return result;
    }
 
Example 8
Source File: EffectData.java    From GlobalWarming with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String getContents() {
    createIfNotExists();

    try {
        return new String(Files.readAllBytes(getPath()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
}
 
Example 9
Source File: RestVolleyImageCache.java    From RestVolley with Apache License 2.0 5 votes vote down vote up
public DiskLruCache getDiskCache() {
    if (mDiskCache == null) {
        //create disk cache
        try {
            mDiskCache = DiskLruCache.open(mCacheDir, 1, 1, DISK_CACHE_SIZE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return mDiskCache;
}
 
Example 10
Source File: FormBuilderController.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private void rewriteFileAndLoadCurrentTab() {
    JSONArray rootArray = Utilities.formsRootFromSectionsMap(selectedSectionsMap);
    String rootString = rootArray.toString(2);
    try {
        FileUtilities.writeFile(rootString, selectedFile);
        reloadFormTab(currentSelectedFormName);
        refreshFormWidgetsCombo();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}
 
Example 11
Source File: DaoBeanUpdateOKImpl.java    From kripton with Apache License 2.0 5 votes vote down vote up
public static void clearCompiledStatements() {
  try {
    if (updateDistancePreparedStatement0!=null) {
      updateDistancePreparedStatement0.close();
      updateDistancePreparedStatement0=null;
    }
  } catch(IOException e) {
    e.printStackTrace();
  }
}
 
Example 12
Source File: JsonUtils.java    From actor4j-core with Apache License 2.0 5 votes vote down vote up
public static <T> T readValue(String content, Class<T> valueType) {
	T result = null;
	
	try {
		result = new ObjectMapper().readValue(content, valueType);
	} catch (IOException e) {
		e.printStackTrace();
	}			

	return result;
}
 
Example 13
Source File: GameClient.java    From JavaGame with GNU Affero General Public License v3.0 5 votes vote down vote up
public void sendData(byte[] data) {
	DatagramPacket packet = new DatagramPacket(data, data.length,
			ipAddress, 1331);
	try {
		socket.send(packet);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 14
Source File: ReverseOperators.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
@operator (
		value = "save_agent")
@doc (
		value = "")
public static int saveAgent(final IScope scope, final IAgent agent, final String pathname) {
	final String path = FileUtils.constructAbsoluteFilePath(scope, pathname, false);

	final String serializedAgent = serializeAgent(scope, agent);

	final ExperimentAgent expAgt = (ExperimentAgent) scope.getExperiment();
	final SimulationAgent simAgt = expAgt.getSimulation();
	final int savedCycle = simAgt.getClock().getCycle();
	final String savedModel = expAgt.getModel().getFilePath();
	final String savedExperiment = (String) expAgt.getSpecies().getFacet(IKeyword.NAME).value(scope);

	FileWriter fw = null;
	try {
		if (path.equals("")) { return -1; }
		
		final File f = new File(path);
		
		final File parent = f.getParentFile();
		if (!parent.exists()) {
			parent.mkdirs();
		}
								
		if (!f.exists()) {
			f.createNewFile();
		}
		fw = new FileWriter(f);

		// Write the Metadata
		fw.write(savedModel + System.lineSeparator());
		fw.write(savedExperiment + System.lineSeparator());
		fw.write(savedCycle + System.lineSeparator());

		// Write the serializedAgent
		fw.write(serializedAgent);
		fw.close();
	} catch (final IOException e) {
		e.printStackTrace();
	}

	return 0;
}
 
Example 15
Source File: TextureRegisterEvent.java    From Moo-Fluids with GNU General Public License v3.0 4 votes vote down vote up
public static void modifyTexture(final Color colourOverlay, final String fluidName) {
  try {

    final BufferedImage
        image =
        ImageIO.read(Minecraft.getMinecraft().getResourceManager()
                         .getResource(new ResourceLocation(BASE_TEXTURE))
                         .getInputStream());

    final File outputPath = new File(Minecraft.getMinecraft().mcDataDir + SEPARATOR +
                                     "assets" + SEPARATOR,
                                     ModInformation.MOD_ID + SEPARATOR +
                                     TEXTURE_LOCATION + SEPARATOR +
                                     fluidName + ".png");

    if (!outputPath.exists()) {
      int width = image.getWidth();
      int height = image.getHeight();

      Graphics g = image.getGraphics();
      g.setColor(colourOverlay);

      for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
          final int pixel = image.getRGB(x, y);
          if (!(pixel >> 24 == 0)) {
            g.fillRect(x, y, 1, 1);
          }
        }
      }

      if (!outputPath.getParentFile().exists() && !outputPath.getParentFile().mkdirs()) {
        return;
      }

      ImageIO.write(image, "png", outputPath);
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 16
Source File: CreateDatabaseAction.java    From ezScrum with GNU General Public License v2.0 4 votes vote down vote up
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String result = "{\"success\":true}";
		// user session
		IUserSession userSession = (IUserSession) request.getSession().getAttribute("UserSession");

		// 取得所有 ITS 參數資料
		String serverURL = request.getParameter("ServerUrl");
		String serverPath = request.getParameter("ServicePath");
		String serverAcc = request.getParameter("DBAccount");
		String serverPwd = request.getParameter("DBPassword");
		String projectName = request.getParameter("Name");
		String dbName = request.getParameter("DBName");

		// 取得空的專案資訊
//		IProject projectTemp = ResourceFacade.getWorkspace().getRoot().getProject(projectName);
		IProject projectTemp = (new ProjectMapper()).getProjectByID(projectName);

		// 設定ITS資訊
//		ITSPrefsStorage tmpPrefs = new ITSPrefsStorage(projectTemp, null);
//		tmpPrefs.setServerUrl(serverURL);
//		tmpPrefs.setServicePath(serverPath);
//		tmpPrefs.setDBAccount(serverAcc);
//		tmpPrefs.setDBPassword(serverPwd);
//		tmpPrefs.setDBName(dbName);
		
		// 設定 ITS資訊
		Configuration tmpConfig = new Configuration(null);
		tmpConfig.setServerUrl(serverURL);
		tmpConfig.setWebServicePath(serverPath);
		tmpConfig.setDBAccount(serverAcc);
		tmpConfig.setDBPassword(serverPwd);
		tmpConfig.setDBName(dbName);

		MantisService service = new MantisService(tmpConfig);
		service.createDB();
		service.initiateDB();

		try {
			response.setContentType("text/html; charset=utf-8");
			response.getWriter().write(result);
			response.getWriter().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
 
Example 17
Source File: DailyRollFileWriter.java    From nesty with Apache License 2.0 4 votes vote down vote up
/**
 * rotate and split in synchronize
 */
protected synchronized void checkRotate(Time current) {

    try {
        if (lastest != null) {

            // check if daytime changed
            if (current.diffDay(lastest)) {

                // start rotate file

                /**
                 * 1. first of all, rename the file to "file.yyyyy-mm-dd"
                 *     parallel write will be lead to this file, so the previos
                 *     file pointer is still valid
                 */
                archive(lastest);

                /**
                 * 2. snapshot the current file output stream, we close it
                 *     after we open new output stream
                 *
                 */
                FileOutputStream close = super.out;

                /**
                 * 3. open new stream ! all operations will effect the new
                 *     output stream, and we can close the previos *snapshot*
                 *     safe
                 */
                open(getFileName(), getFileWriteMode());

                /**
                 * 4. safe close
                 */
                if (close != null) {
                    close.flush();
                    close.close();
                }
            }
        }

        lastest = current;

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 18
Source File: UnicodeNormalizerConformanceTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Test the conformance of NewNormalizer to
 * http://www.unicode.org/unicode/reports/tr15/conformance/Draft-TestSuite.txt.
 * This file must be located at the path specified as TEST_SUITE_FILE.
 */
@Test
public void TestConformance() throws Exception{
    String line = null;
    String[] fields = new String[5];
    StringBuffer buf = new StringBuffer();
    int passCount = 0;
    int failCount = 0;
    UnicodeSet other = new UnicodeSet(0, 0x10ffff);
    int c=0;
    BufferedReader input = null;
    try {
        input = TestUtil.getDataReader("unicode/NormalizationTest.txt");
        for (int count = 0;;++count) {
            line = input.readLine();
            if (line == null) {
                //read the extra test cases
                if(count > moreCases.length) {
                    count = 0;
                } else if(count == moreCases.length) {
                    // all done
                    break;
                }
                line = moreCases[count++];
            }
            if (line.length() == 0) continue;

            // Expect 5 columns of this format:
            // 1E0C;1E0C;0044 0323;1E0C;0044 0323; # <comments>

            // Skip comments
            if (line.charAt(0) == '#'  || line.charAt(0)=='@') continue;

            // Parse out the fields
            hexsplit(line, ';', fields, buf);
            
            // Remove a single code point from the "other" UnicodeSet
            if(fields[0].length()==UTF16.moveCodePointOffset(fields[0],0, 1)) {
                c=UTF16.charAt(fields[0],0); 
                if(0xac20<=c && c<=0xd73f) {
                    // not an exhaustive test run: skip most Hangul syllables
                    if(c==0xac20) {
                        other.remove(0xac20, 0xd73f);
                    }
                    continue;
                }
                other.remove(c);
            }
            if (checkConformance(fields, line)) {
                ++passCount;
            } else {
                ++failCount;
            }
            if ((count % 1000) == 999) {
                logln("Line " + (count+1));
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new IllegalArgumentException("Couldn't read file "
          + ex.getClass().getName() + " " + ex.getMessage()
          + " line = " + line
          );
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (Exception ignored) {
            }
        }
    }

    if (failCount != 0) {
        errln("Total: " + failCount + " lines failed, " +
              passCount + " lines passed");
    } else {
        logln("Total: " + passCount + " lines passed");
    }
}
 
Example 19
Source File: AipOcr.java    From java-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * 通用文字识别接口
 * 用户向服务请求识别某张图中的所有文字
 *
 * @param image - 本地图片路径
 * @param options - 可选参数对象,key: value都为string类型
 * options - options列表:
 *   language_type 识别语言类型,默认为CHN_ENG。可选值包括:<br>- CHN_ENG:中英文混合;<br>- ENG:英文;<br>- POR:葡萄牙语;<br>- FRE:法语;<br>- GER:德语;<br>- ITA:意大利语;<br>- SPA:西班牙语;<br>- RUS:俄语;<br>- JAP:日语;<br>- KOR:韩语;
 *   detect_direction 是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括:<br>- true:检测朝向;<br>- false:不检测朝向。
 *   detect_language 是否检测语言,默认不检测。当前支持(中文、英语、日语、韩语)
 *   probability 是否返回识别结果中每一行的置信度
 * @return JSONObject
 */
public JSONObject basicGeneral(String image, HashMap<String, String> options) {
    try {
        byte[] data = Util.readFileByBytes(image);
        return basicGeneral(data, options);
    } catch (IOException e) {
        e.printStackTrace();
        return AipError.IMAGE_READ_ERROR.toJsonResult();
    }
}
 
Example 20
Source File: AipOcr.java    From java-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * 手写文字识别接口
 * 【此接口需要您在[页面](http://ai.baidu.com/tech/ocr)中提交合作咨询开通权限】提供对各类名片的结构化识别功能,提取姓名、邮编、邮箱、电话、网址、地址、手机号字段
 *
 * @param image - 本地图片路径
 * @param options - 可选参数对象,key: value都为string类型
 * options - options列表:
 *   recognize_granularity 是否定位单字符位置,big:不定位单字符位置,默认值;small:定位单字符位置
 * @return JSONObject
 */
public JSONObject handwriting(String image, HashMap<String, String> options) {
    try {
        byte[] data = Util.readFileByBytes(image);
        return handwriting(data, options);
    } catch (IOException e) {
        e.printStackTrace();
        return AipError.IMAGE_READ_ERROR.toJsonResult();
    }
}