/** * Execute the zipalign for a certain apk * * @param apk */ public static void zipAlign(File apk) { // String zipAlign = SdkUtils.getSdkToolsPath(); String zipAlign = AndroidUtils.getSDKPathByPreference() + IPath.SEPARATOR + IAndroidConstants.FD_TOOLS; try { File tempFile = File.createTempFile("_tozipalign", ".apk"); FileUtil.copyFile(apk, tempFile); if (!zipAlign.endsWith(File.separator)) { zipAlign += File.separator; } zipAlign += Platform.getOS().equals(Platform.OS_WIN32) ? "zipalign.exe" : "zipalign"; String[] command = new String[] { zipAlign, "-f", "-v", "4", tempFile.getAbsolutePath(), apk.getAbsolutePath() }; StringBuilder commandLine = new StringBuilder(); for (String commandPart : command) { commandLine.append(commandPart); commandLine.append(" "); } AndmoreLogger.info(PackageFile.class, "Zipaligning package: " + commandLine.toString()); Runtime.getRuntime().exec(command); } catch (IOException e) { AndmoreLogger.error(PackageFile.class, "Error while zipaligning package", e); } catch (Exception e) { AndmoreLogger.error( PackageFile.class, "Zipalign application cannot be executed - insuficient permissions", e); } }
/* * (non-Javadoc) * * @see org.eclipse.andmore.android.model.java.JavaClass#addComments() */ @Override protected void addComments() throws AndroidException { ASTNode todoComment; ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(document.get().toCharArray()); compUnit = (CompilationUnit) parser.createAST(null); ast = compUnit.getAST(); rewrite = ASTRewrite.create(ast); todoComment = rewrite.createStringPlaceholder( CodeUtilsNLS.MODEL_Common_ToDoPutYourCodeHere, ASTNode.EMPTY_STATEMENT); TypeDeclaration receiverClass = (TypeDeclaration) compUnit.types().get(0); MethodDeclaration method; Block block; // Adds the Override annotation and ToDo comment to all overridden // methods for (int i = 0; i < receiverClass.bodyDeclarations().size(); i++) { method = (MethodDeclaration) receiverClass.bodyDeclarations().get(i); // Adds the Override annotation rewrite .getListRewrite(method, method.getModifiersProperty()) .insertFirst(OVERRIDE_ANNOTATION, null); // Adds the ToDo comment block = method.getBody(); rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertFirst(todoComment, null); } try { // Writes the modifications TextEdit modifications = rewrite.rewriteAST(document, null); modifications.apply(document); } catch (IllegalArgumentException e) { String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className); AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e); throw new AndroidException(errMsg); } catch (MalformedTreeException e) { String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className); AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e); throw new AndroidException(errMsg); } catch (BadLocationException e) { String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className); AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e); throw new AndroidException(errMsg); } }
/* * (non-Javadoc) * * @see org.eclipse.jface.wizard.Wizard#performFinish() */ @Override public boolean performFinish() { boolean saved = false; try { DoSave doSave = new DoSave(); getContainer().run(false, false, doSave); if (doSave.exception != null) { throw doSave.exception; } else { saved = doSave.saved; } } catch (Exception e) { IStatus status = new Status(IStatus.ERROR, CodeUtilsActivator.PLUGIN_ID, e.getLocalizedMessage()); EclipseUtils.showErrorDialog( CodeUtilsNLS.UI_GenericErrorDialogTitle, CodeUtilsNLS.ERR_BuildingBlockCreation_ErrorMessage, status); } if (saved) { ICompilationUnit javaFile = getBuildingBlock() .getPackageFragment() .getCompilationUnit(getBuildingBlock().getName() + ".java"); // $NON-NLS-1$ if ((javaFile != null) && javaFile.exists()) { try { JavaUI.openInEditor(javaFile); } catch (Exception e) { // Do nothing AndmoreLogger.error( NewActivityBasedOnTemplateWizard.class, "Could not open the activity " //$NON-NLS-1$ + getBuildingBlock().getName() + " on an editor.", e); //$NON-NLS-1$ } } } if (saved) { // Collecting usage data for statistical purposes try { AndmoreLogger.collectUsageData( UsageDataConstants.WHAT_BUILDINGBLOCK_ACTIVITY, UsageDataConstants.KIND_BUILDINGBLOCK, UsageDataConstants.DESCRIPTION_DEFAULT, CodeUtilsActivator.PLUGIN_ID, CodeUtilsActivator.getDefault().getBundle().getVersion().toString()); } catch (Throwable e) { // Do nothing, but error on the log should never prevent app // from working } } return saved; }
/* * Wait until the device status becomes online * * @param serialNumber device serial number * * @param instance TmL instance, if it exists * * @return true if the device became online, false otherwise */ private static boolean waitForDeviceToBeOnline(String serialNumber, ISerialNumbered instance) { AndmoreLogger.debug("Wait device to be online: " + serialNumber); boolean instanceOnline = false; long timeoutLimit = 0; if (instance != null) { Properties prop = ((IInstance) instance).getProperties(); String timeout = prop.getProperty(RemoteDeviceInstance.PROPERTY_TIMEOUT); timeoutLimit = System.currentTimeMillis() + (Integer.parseInt(timeout) * 1000); } else { timeoutLimit = System.currentTimeMillis() + (RemoteDeviceConstants.DEFAULT_TIMEOUT * 1000); } while ((instanceOnline = DDMSFacade.isDeviceOnline(serialNumber)) == false) { try { Thread.sleep(1000); } catch (InterruptedException e) { AndmoreLogger.error("Wait for device to be online: thread has been interrupted"); } try { testTimeout(timeoutLimit); } catch (TimeoutException e) { AndmoreLogger.warn("Timeout reached wile wating device to be online: " + serialNumber); break; } } return instanceOnline; }
/** * Writes this package file to an output stream * * @param outputStream the stream to write the package to * @throws IOException if an I/O error occurs when writing the package contents to the output * stream */ public void write(OutputStream outputStream) throws IOException { // create a jar output stream JarOutputStream jarOut = null; try { jarOut = new JarOutputStream(outputStream, manifest); // for each entry in the package file for (String jarEntryName : entryMap.keySet()) { if (jarEntryName.contains("raw/") || rawFiles.contains(jarEntryName)) { writeRaw(jarOut, jarEntryName); } else { writeCompressed(jarOut, jarEntryName); } } } finally { if (jarOut != null) { try { jarOut.finish(); jarOut.close(); } catch (IOException e) { AndmoreLogger.error("Could not close stream while writing jar file. " + e.getMessage()); } } } }
private void writeCompressed(JarOutputStream jarOut, String entryName) throws IOException { File file = entryMap.get(entryName); if ((file.exists()) && (file.isFile())) { JarEntry entry = new JarEntry(entryName); jarOut.putNextEntry(entry); WritableByteChannel outputChannel = null; FileChannel readFromFileChannel = null; FileInputStream inputStream = null; try { outputChannel = Channels.newChannel(jarOut); inputStream = new FileInputStream(file); readFromFileChannel = inputStream.getChannel(); readFromFileChannel.transferTo(0, file.length(), outputChannel); } finally { try { if (jarOut != null) { jarOut.closeEntry(); } if (readFromFileChannel != null) { readFromFileChannel.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException e) { AndmoreLogger.error("Could not close stream: ", e.getMessage()); // $NON-NLS-1$ } } } }
/* * (non-Javadoc) * * @see org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator# * isSelectedValid(java.lang.Object) */ @Override public boolean isSelectedValid(Object element) { boolean isValid = false; try { if (element instanceof IJavaProject) { IJavaProject jproject = (IJavaProject) element; IPath path = jproject.getProject().getFullPath(); isValid = (jproject.findPackageFragmentRoot(path) != null); } else if (element instanceof IPackageFragmentRoot) { IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) element; boolean isSrc = (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE); boolean isGen = packageFragmentRoot.getElementName().equals(IAndroidConstants.GEN_SRC_FOLDER) && (packageFragmentRoot.getParent() instanceof IJavaProject); isValid = isSrc && !isGen; } else { isValid = true; } } catch (JavaModelException e) { AndmoreLogger.error(ElementTreeValidator.class, e.getLocalizedMessage(), e); } return isValid; }
/** * Retrieves an image data. If it has never been used at the current session, loads it from skin. * Released image is retrieved if both parameters are false. * * @param isPressed true if the image to be retrieved is the pressed image * @param isEnter true if the image to be retrieved is the enter image. It only has effect if * isPressed == false * @return An image data containing the desired image pixels */ private ImageData getImageData(boolean isPressed, boolean isEnter) { ImageData imageData = null; IAndroidEmulatorInstance instance = UIHelper.getInstanceAssociatedToControl(this); try { if (isPressed) { imageData = skin.getPressedImageData(instance.getCurrentLayout()); } else { if (isEnter) { imageData = skin.getEnterImageData(instance.getCurrentLayout()); } else { imageData = skin.getReleasedImageData(instance.getCurrentLayout()); } } } catch (SkinException e) { error( "The image requested from skin could not be retrieved. isPressed=" + isPressed + "; message=" + e.getMessage()); EclipseUtils.showErrorDialog(e); error("The skin could not provide an important resource. Stopping the instance"); try { instance.stop(true); } catch (InstanceStopException e1) { error("Error while running service for stopping virtual machine"); EclipseUtils.showErrorDialog( EmulatorNLS.GEN_Error, EmulatorNLS.EXC_General_CannotRunStopService); } } return imageData; }
/** * Execute a command. * * @param cmd Array of strings holding the command to be executed. * @return The {@link IStatus} of the command execution. * @throws IOException Exception thrown in case there are problems executing the command. */ public static IStatus executeCommand(String[] cmd) throws IOException { IStatus status = Status.OK_STATUS; Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(cmd); try { // wait for the command to finish its execution process.waitFor(); } catch (InterruptedException e) { AndmoreLogger.error(RemoteDeviceUtils.class, "Problems executing the command"); status = new Status( IStatus.ERROR, RemoteDevicePlugin.PLUGIN_ID, "Problems executing the command", e); } // in case the is a problem with the command execution, create an error // status if (process.exitValue() != 0) { AndmoreLogger.error(RemoteDeviceUtils.class, "The IP was not found"); status = new Status(IStatus.ERROR, RemoteDevicePlugin.PLUGIN_ID, "The IP was not found"); } return status; }
@Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { saved = getBuildingBlock().save(getContainer(), monitor); getBuildingBlock().getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor); getBuildingBlock().getProject().build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor); } catch (CoreException ce) { // build failed - show a warning message AndmoreLogger.error(this.getClass(), ce.getMessage(), ce); EclipseUtils.showWarningDialog( CodeUtilsNLS.UI_NewActivityWizard_TitleNewActivityWizard, CodeUtilsNLS.NewActivityWizard_MessageSomeProblemsOccurredWhileBuildingProject); } catch (AndroidException e) { exception = e; } }
@Override public void applyLayout(String layoutName) { // Populate the attributes with information from skin AndroidSkinBean skinBean = null; try { skinBean = skin.getSkinBean(layoutName); } catch (SkinException e) { error("The skin data could not be retrieved from skin files. Cause: " + e.getMessage()); EclipseUtils.showErrorDialog(e); } // Create layout and set it to composite if (skinBean != null) { // When changing to a new layout, the key may move to another // position // It does not make sense to keep the old key object currentKey = null; // Change the background color to the one that applies to the layout // being set RGB color = skin.getBackgroundColor(layoutName); setBackground(new Color(PlatformUI.getWorkbench().getDisplay(), color)); Layout prevLayout = getLayout(); if (prevLayout instanceof AndroidSkinLayout) { ((AndroidSkinLayout) prevLayout).dispose(); } AndroidSkinLayout androidLayout = new AndroidSkinLayout(skinBean, skin.isFlipSupported()); setLayout(androidLayout); embeddedViewScale = skinBean.getEmbeddedViewScale(); layout(); redraw(); } }
/** * Handle Remote Device disconnection * * @param serialNumber the serial number of the disconnected device */ public static void disconnectDevice(String serialNumber) { if (DDMSFacade.isRemote(serialNumber)) { ISerialNumbered instance = DevicesManager.getInstance().getDeviceBySerialNumber(serialNumber); AndmoreLogger.debug( "Handle remote device disconnected event. Serial Number: " + serialNumber + " Instance: " + instance); if (instance != null) { Object volatileProperty = ((RemoteDeviceInstance) instance) .getProperties() .get(RemoteDeviceInstance.PROPERTY_VOLATILE); boolean isVolatile = ((volatileProperty != null) ? ((Boolean) volatileProperty).booleanValue() : false); if (!isVolatile) { try { AndmoreLogger.debug( "Disconnecting Remote Device: the device is NOT volatile, the TmL service will be called"); Map<Object, Object> arguments = new HashMap<Object, Object>(); arguments.put(RemoteDeviceConstants.DUMMY_TRANSITION, true); RemoteDevicePlugin.getDisconnectServiceHandler().run((IInstance) instance, arguments); } catch (Exception e) { AndmoreLogger.error("Error when running TmL disconnect service: " + e.getMessage()); } } else { AndmoreLogger.debug( "Disconnecting Remote Device: the device is volatile, it will be deleted"); DevicesManager.getInstance().deleteInstanceOfDevice(serialNumber); } } } }