PListAccessor { public String getStringValue(String key) throws IOException { if (!plist.exists()) { throw new FileNotFoundException("The Plist " + plist.getAbsolutePath() + " does not exist."); } try { String command = "/usr/libexec/PlistBuddy -c \"Print :" + key + "\" \"" + plist.getAbsolutePath() + "\""; System.out.println("[INFO] PlistBuddy Print command is: '" + command + "'."); String[] args = new String[] { "bash", "-c", command }; Process p = Runtime.getRuntime().exec(args); p.waitFor(); int exitValue = p.exitValue(); if (exitValue == 0) { InputStream is = p.getInputStream(); try { return new Scanner(is, Charset.defaultCharset().name()).useDelimiter("\\Z").next(); } finally { closeQuietly(is); } } String errorMessage = "<n/a>"; try { errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name()).useDelimiter("\\Z").next(); } catch (Exception ex) { System.out.println("[ERROR] Exception caught during retrieving error message of command '" + command + "': " + ex); } if (errorMessage.contains(":" + key + "\", Does Not Exist")) { return null; } throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ") + "\" command failed. Error message is: " + errorMessage + ". Return code was: '" + exitValue + "'."); } catch (InterruptedException e) { throw new RuntimeException(e); } } PListAccessor(File file); File getPlistFile(); String getStringValue(String key); void updateStringValue(String key, String value); void addStringValue(String key, String value); void addStringValueToDict(String key, String value, String dictKey); void addElement(String key, String type); void addDictToArray(String dict, String array); void createPlist(); String printValue(String key); static final String KEY_BUNDLE_IDENTIFIER; static final String KEY_BUNDLE_VERSION; static final String KEY_BUNDLE_SHORT_VERSION_STRING; static final String KEY_WK_COMPANION_APP_BUNDLE_IDENTIFIER; static final String KEY_WK_APP_BUNDLE_IDENTIFIER; }
@Test public void readString() throws IOException { String appId = plist.getStringValue(PListAccessor.KEY_BUNDLE_IDENTIFIER); assertEquals("com.sap.myapp", appId); }
@Test(expected = FileNotFoundException.class) public void readStringFromNonExistingPList() throws IOException { PListAccessor plist = new PListAccessor(new File("/foo")); plist.getStringValue(PListAccessor.KEY_BUNDLE_IDENTIFIER); }
@Test public void readStringFromNonExistingKey() throws IOException { assertNull(plist.getStringValue("foo")); }