/*
   * (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;
  }
Example #2
0
  /**
   * 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);
    }
  }
Example #3
0
  /*
   * 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;
  }
  /*
   * (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);
    }
  }
Example #5
0
  /**
   * 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());
        }
      }
    }
  }
Example #6
0
 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;
  }
Example #8
0
  /**
   * 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);
        }
      }
    }
  }
Example #9
0
  /**
   * 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;
   }
 }