/**
  * Determines if file is jsp fragment or not (does a deep, indepth check, looking into contents of
  * file)
  *
  * @param file assumes file is not null and exists
  * @return true if file is jsp fragment, false otherwise
  */
 private boolean isFragment(IFile file) {
   // copied from JSPValidator
   boolean isFragment = false;
   InputStream is = null;
   try {
     IContentDescription contentDescription = file.getContentDescription();
     // it can be null
     if (contentDescription == null) {
       is = file.getContents();
       contentDescription =
           Platform.getContentTypeManager()
               .getDescriptionFor(
                   is, file.getName(), new QualifiedName[] {IContentDescription.CHARSET});
     }
     if (contentDescription != null) {
       String fileCtId = contentDescription.getContentType().getId();
       isFragment =
           (fileCtId != null && ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT.equals(fileCtId));
     }
   } catch (IOException e) {
     // ignore, assume it's invalid JSP
   } catch (CoreException e) {
     // ignore, assume it's invalid JSP
   } finally {
     // must close input stream in case others need it
     if (is != null)
       try {
         is.close();
       } catch (Exception e) {
         // not sure how to recover at this point
       }
   }
   return isFragment;
 }
 private void assertXMLFilesMatch(String label, IFile testFile, String expectedFileLocation)
     throws Exception {
   Reader testReader = null;
   Reader expectedReader = null;
   try {
     testReader = new InputStreamReader(testFile.getContents());
     expectedReader =
         new InputStreamReader(
             CreateSwitchYardProjectTest.class
                 .getClassLoader()
                 .getResourceAsStream(expectedFileLocation));
     Diff diff = XMLUnit.compareXML(testReader, expectedReader);
     assertTrue(label + ": " + diff.toString(), diff.identical());
   } finally {
     if (testReader != null) {
       try {
         testReader.close();
       } catch (Exception e) {
         // for codestyle check
         e.fillInStackTrace();
       }
       testReader = null;
     }
     if (expectedReader != null) {
       try {
         expectedReader.close();
       } catch (Exception e) {
         // for codestyle check
         e.fillInStackTrace();
       }
       expectedReader = null;
     }
   }
 }
  private void verifyModifyAndSaveBothSidesOfCompareEditor(String extention)
      throws InterruptedException, InvocationTargetException, IllegalArgumentException,
          SecurityException, IllegalAccessException, NoSuchFieldException, CoreException {

    // create files to compare
    IFile file1 = project.getFile("CompareFile1." + extention);
    IFile file2 = project.getFile("CompareFile2." + extention);
    file1.create(new ByteArrayInputStream(fileContents1.getBytes()), true, null);
    file2.create(new ByteArrayInputStream(fileContents2.getBytes()), true, null);

    // prepare comparison
    SaveablesCompareEditorInput input =
        new SaveablesCompareEditorInput(
            null,
            SaveablesCompareEditorInput.createFileElement(file1),
            SaveablesCompareEditorInput.createFileElement(file2),
            PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage());
    input.run(null);

    // open CompareEditor
    CompareEditor editor =
        (CompareEditor)
            PlatformUI.getWorkbench()
                .getActiveWorkbenchWindow()
                .getActivePage()
                .openEditor(input, COMPARE_EDITOR, true);

    CompareViewerSwitchingPane pane =
        (CompareViewerSwitchingPane) ReflectionUtils.getField(input, "fContentInputPane", true);

    Viewer viewer = pane.getViewer();

    MergeSourceViewer left = (MergeSourceViewer) ReflectionUtils.getField(viewer, "fLeft", true);
    MergeSourceViewer right = (MergeSourceViewer) ReflectionUtils.getField(viewer, "fRight", true);

    // modify both sides of CompareEditor
    StyledText leftText = left.getSourceViewer().getTextWidget();
    StyledText rightText = right.getSourceViewer().getTextWidget();
    leftText.append(appendFileContents);
    rightText.append(appendFileContents);

    // save both sides
    editor.doSave(null);

    assertFalse(editor.isDirty());

    PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeEditor(editor, false);

    // validate if both sides where saved
    assertTrue(
        compareContent(
            new ByteArrayInputStream((fileContents1 + appendFileContents).getBytes()),
            file1.getContents()));
    assertTrue(
        compareContent(
            new ByteArrayInputStream((fileContents2 + appendFileContents).getBytes()),
            file2.getContents()));
  }
 private String readHeader() {
   // TODO: use IRunnableWithProgress
   StringBuilder sb = new StringBuilder();
   IFile file = getHeaderFile();
   if (file.exists() && file.isAccessible()) {
     InputStream stream = null;
     try {
       stream = file.getContents();
       BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
       String line;
       while ((line = reader.readLine()) != null) {
         sb.append(line).append(System.lineSeparator());
       }
     } catch (Exception ex) {
       ex.printStackTrace();
     } finally {
       try {
         if (stream != null) stream.close();
       } catch (IOException ioe) {
         ioe.printStackTrace();
       }
     }
   }
   return sb.toString();
 }
  private void determineLinePositions(IFile file) throws CoreException, IOException {
    lineStarts = new ArrayList<Integer>();
    lineEnds = new ArrayList<Integer>();
    lineStartTabCount = new ArrayList<Integer>();

    InputStreamReader isr;
    isr = new InputStreamReader(file.getContents());

    int last = -1;
    int i = 0;
    int c;
    boolean countTabs = true;
    int tabCount = 0;
    while ((c = isr.read()) != -1) {
      if ((char) c == '\n') {
        lineStarts.add(new Integer(last + 1));
        lineEnds.add(new Integer(i));
        lineStartTabCount.add(new Integer(tabCount));
        ++linesCount;
        last = i;
        countTabs = true;
        tabCount = 0;
      } else if (countTabs && (char) c == '\t') {
        ++tabCount;
      } else if ((char) c != ' ') {
        countTabs = false;
      }
      i++;
    }

    lineStarts.add(new Integer(last + 1));
    lineEnds.add(new Integer(i));
    lineStartTabCount.add(new Integer(tabCount));
    ++linesCount;
  }
  public void testNewBeansXMLWizard() throws CoreException {
    NewBeansXMLWizardContext context = new NewBeansXMLWizardContext();
    context.init("org.jboss.tools.cdi.ui.wizard.NewBeansXMLCreationWizard");

    try {

      WizardNewFileCreationPage page =
          (WizardNewFileCreationPage) context.wizard.getPage("newFilePage1");
      String s = page.getFileName();
      assertEquals("beans.xml", s);
      assertFalse(context.wizard.canFinish());
      page.setFileName("beans2.xml");
      assertTrue(context.wizard.canFinish());
      String c = page.getContainerFullPath().toString();
      assertEquals("/tck/WebContent/WEB-INF", c);

      context.wizard.performFinish();

      IFile f =
          context.tck.getParent().getFile(page.getContainerFullPath().append(page.getFileName()));
      assertTrue(f.exists());

      String text = FileUtil.readStream(f.getContents());
      assertTrue(text.indexOf("http://java.sun.com/xml/ns/javaee") > 0);

    } finally {
      context.close();
    }
  }
  private static IFileEditorInput getFileStorage(int index) throws CoreException {
    String filename = getBatchDateString();
    filename += (index > 0 ? "_" + index : "") + ".tcl";
    IFolder templateFolder =
        SicsVisualBatchViewer.getProjectFolder(
            SicsVisualBatchViewer.EXPERIMENT_PROJECT, FOLDER_TEMPLATE);
    IFile templateFile = templateFolder.getFile(FILE_TEMPLATE);
    IFolder folder =
        SicsVisualBatchViewer.getProjectFolder(
            SicsVisualBatchViewer.EXPERIMENT_PROJECT, SicsVisualBatchViewer.AUTOSAVE_FOLDER);
    IFileEditorInput input = new FileEditorInput(folder.getFile(filename));
    if (input.exists()) {
      return getFileStorage(index++);
    } else {
      try {
        byte[] read = null;
        if (templateFile.exists()) {
          long size = EFS.getStore(templateFile.getLocationURI()).fetchInfo().getLength();
          //					long size = templateFolder.getLocation().toFile().length();
          read = new byte[(int) size];
          InputStream inputStream = templateFile.getContents();
          inputStream.read(read);
        } else {
          read = new byte[0];
          templateFile.create(new ByteArrayInputStream(read), IResource.ALLOW_MISSING_LOCAL, null);
        }
        input.getFile().create(new ByteArrayInputStream(read), IResource.ALLOW_MISSING_LOCAL, null);
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return input;
  }
  public static IStatus cssBuild(IProject project) throws CoreException {

    SDK sdk = SDKUtil.getSDK(project);

    if (sdk == null) {
      throw new CoreException(
          ThemeCore.createErrorStatus("No SDK for project configured. Could not build theme."));
    }

    ILiferayRuntime liferayRuntime = ServerUtil.getLiferayRuntime(project);

    if (liferayRuntime == null) {
      throw new CoreException(
          ThemeCore.createErrorStatus(
              "Could not get portal runtime for project.  Could not build theme."));
    }

    Map<String, String> appServerProperties = ServerUtil.configureAppServerProperties(project);

    IStatus status = sdk.compileThemePlugin(project, null, appServerProperties);

    if (!status.isOK()) {
      throw new CoreException(status);
    }

    IFolder docroot = CoreUtil.getDocroot(project);

    IFile lookAndFeelFile =
        docroot.getFile("WEB-INF/" + ILiferayConstants.LIFERAY_LOOK_AND_FEEL_XML_FILE);

    if (!lookAndFeelFile.exists()) {
      String id = project.getName().replaceAll(ISDKConstants.THEME_PLUGIN_PROJECT_SUFFIX, "");
      IFile propsFile =
          docroot.getFile("WEB-INF/" + ILiferayConstants.LIFERAY_PLUGIN_PACKAGE_PROPERTIES_FILE);
      String name = id;
      if (propsFile.exists()) {
        Properties props = new Properties();
        try {
          props.load(propsFile.getContents());
          String nameValue = props.getProperty("name");
          if (!CoreUtil.isNullOrEmpty(nameValue)) {
            name = nameValue;
          }
        } catch (IOException e) {
          ThemeCore.logError("Unable to load plugin package properties.", e);
        }
      }

      if (liferayRuntime != null) {
        ThemeDescriptorHelper.createDefaultFile(
            lookAndFeelFile, liferayRuntime.getPortalVersion() + "+", id, name);
      }
    }

    if (docroot != null && docroot.exists()) {
      docroot.refreshLocal(IResource.DEPTH_INFINITE, null);
    }

    return status;
  }
  /**
   * Load the model from the given file, if possible.
   *
   * @param modelFile The IFile which contains the persisted model
   */
  @SuppressWarnings("unchecked")
  private synchronized Properties updateModel(IFile modelFile) {

    if (PROPERTIES_EXT.equals(modelFile.getFileExtension())) {
      Properties model = new Properties();
      if (modelFile.exists()) {
        try {
          model.load(modelFile.getContents());

          String propertyName;
          List properties = new ArrayList();
          for (Enumeration names = model.propertyNames(); names.hasMoreElements(); ) {
            propertyName = (String) names.nextElement();
            properties.add(
                new PropertiesTreeData(propertyName, model.getProperty(propertyName), modelFile));
          }
          PropertiesTreeData[] propertiesTreeData =
              (PropertiesTreeData[]) properties.toArray(new PropertiesTreeData[properties.size()]);

          cachedModelMap.put(modelFile, propertiesTreeData);
          return model;
        } catch (IOException e) {
        } catch (CoreException e) {
        }
      } else {
        cachedModelMap.remove(modelFile);
      }
    }
    return null;
  }
  @Override
  public IFile exportToIFile(
      AFileResource res, ResourceDescriptor rd, String fkeyname, IProgressMonitor monitor)
      throws Exception {
    IFile f = super.exportToIFile(res, rd, fkeyname, monitor);
    if (f != null) {
      JasperReportsConfiguration jrConfig = res.getJasperConfiguration();
      if (jrConfig == null) {
        jrConfig = JasperReportsConfiguration.getDefaultJRConfig(f);
        res.setJasperConfiguration(jrConfig);
      } else jrConfig.init(f);
      try {
        JasperDesign jd = JRXmlLoader.load(jrConfig, f.getContents());
        setPropServerURL(res, jd);
        setPropReportUnit(res, jd);
        getResources(res, jd);

        MServerProfile sp = (MServerProfile) res.getRoot();
        if (sp != null)
          f.setContents(
              new ByteArrayInputStream(
                  JRXmlWriterHelper.writeReport(null, jd, sp.getValue().getJrVersion())
                      .getBytes("UTF-8")),
              IFile.KEEP_HISTORY | IFile.FORCE,
              monitor);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    if (f != null) f.setPersistentProperty(KEY_REPORT_ISMAIN, Boolean.toString(rd.isMainReport()));
    return f;
  }
 protected static final String readFile(IFile file) throws ContentProviderException {
   try {
     BufferedReader in = null;
     if (file.getClass()
         .getCanonicalName()
         .equals("org.eclipse.dirigible.ide.workspace.impl.File")) {
       in = new BufferedReader(new InputStreamReader(file.getContents()));
     } else {
       IResource resource = getFromRepository(file);
       in =
           new BufferedReader(
               new InputStreamReader(new ByteArrayInputStream(resource.getContent())));
     }
     StringBuilder builder = new StringBuilder();
     String line = null;
     while ((line = in.readLine()) != null) {
       builder.append(line);
       builder.append("\n"); // $NON-NLS-1$
     }
     return builder.toString();
   } catch (Exception ex) {
     LOGGER.error(CANNOT_READ_FILE_CONTENTS, ex);
     throw new ContentProviderException(CANNOT_READ_FILE_CONTENTS, ex);
   }
 }
 public void addNotationInfo(RootContainer rootContainer, IEditorInput input) {
   try {
     IFile file = getNotationInfoFile(((FileEditorInput) input).getFile());
     if (file.exists()) {
       Element notationInfo =
           documentBuilderFactory
               .newDocumentBuilder()
               .parse(file.getContents())
               .getDocumentElement();
       Element changedInfo = convertCheck(notationInfo);
       processRootContainer(rootContainer, changedInfo == null ? notationInfo : changedInfo);
       if (changedInfo != null) {
         file.setContents(
             new ByteArrayInputStream(toNotationInfoXml(rootContainer).getBytes()),
             true,
             true,
             null);
       }
     } else {
       file.create(
           new ByteArrayInputStream(createInitialNotationInfo().toString().getBytes()),
           true,
           null);
     }
   } catch (Exception e) {
     Logger.logError("Problem adding notation info", e);
     throw new RuntimeException(e);
   }
 }
  @Test
  public void testNewLiferayModuleProjectNewProperties() throws Exception {
    NewLiferayModuleProjectOp op = NewLiferayModuleProjectOp.TYPE.instantiate();

    op.setProjectName("test-properties-in-portlet");

    op.setProjectTemplateName("portlet");
    op.setComponentName("Test");

    PropertyKey pk = op.getPropertyKeys().insert();

    pk.setName("property-test-key");
    pk.setValue("property-test-value");

    Status exStatus =
        NewLiferayModuleProjectOpMethods.execute(
            op, ProgressMonitorBridge.create(new NullProgressMonitor()));

    assertEquals("OK", exStatus.message());

    IProject modPorject = CoreUtil.getProject(op.getProjectName().content());
    modPorject.open(new NullProgressMonitor());

    SearchFilesVisitor sv = new SearchFilesVisitor();
    List<IFile> searchFiles = sv.searchFiles(modPorject, "TestPortlet.java");
    IFile componentClassFile = searchFiles.get(0);

    assertEquals(componentClassFile.exists(), true);

    String actual = CoreUtil.readStreamToString(componentClassFile.getContents());

    assertTrue(actual, actual.contains("\"property-test-key=property-test-value\""));
  }
Beispiel #14
0
  private void refreshGraphicalViewer() {
    IEditorInput input = getEditorInput();
    if (input instanceof IFileEditorInput) {
      try {
        IFile file = ((IFileEditorInput) input).getFile();
        GraphicalViewer viewer = getGraphicalViewer();

        // desirialize
        RootModel newRoot = null;
        try {
          newRoot = DiagramSerializer.deserialize(file.getContents());
        } catch (Exception ex) {
          UMLPlugin.logException(ex);
          return;
        }

        // copy to editing model
        RootModel root = (RootModel) viewer.getContents().getModel();
        root.copyFrom(newRoot);

      } catch (Exception ex) {
        UMLPlugin.logException(ex);
      }
    }
  }
  public void testDirtyFlagOnLocalResourceTypedElementAndEmptyRight()
      throws CoreException, InvocationTargetException, InterruptedException,
          IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException,
          NoSuchMethodException, IOException {

    // Create left element by SaveableCompareEditorInput to be properly
    // saved, see javadoc to SaveableCompareEditorInput
    LocalResourceTypedElement el1 =
        (LocalResourceTypedElement) SaveableCompareEditorInput.createFileElement(file1);
    ITypedElement el2 = null;

    CompareConfiguration conf = new CompareConfiguration();
    conf.setLeftEditable(true);
    TestSaveableEditorInput compareEditorInput = new TestSaveableEditorInput(el1, el2, conf);

    compareEditorInput.prepareCompareInput(null);

    verifyDirtyStateChanges(compareEditorInput);

    // check whether file was saved

    assertTrue(
        compareContent(
            new ByteArrayInputStream((fileContents1 + appendFileContents).getBytes()),
            file1.getContents()));
  }
Beispiel #16
0
  public ArrayList<IProject> getProjects() {
    final ArrayList<IProject> result = new ArrayList<IProject>();
    try {
      IProject featureProject = getFeatureProject();
      IFile featureXMLFile = featureProject.getFile("feature.xml");
      SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

      DefaultHandler handler =
          new DefaultHandler() {
            @Override
            public void startElement(
                String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
              if ("plugin".equals(qName)) {
                String id = attributes.getValue("id");
                IProject eachProject = ResourcesPlugin.getWorkspace().getRoot().getProject(id);
                if (!eachProject.exists()) {
                  throw new BuildException(
                      MessageFormat.format(
                          "아이디가 {0}인 프로젝틀르 찾지 못했습니다. 프로젝트 아이디와 프로젝트 명은 동일한 것으로 간주합니다.", id));
                }
                result.add(eachProject);
              }
            }
          };
      parser.parse(featureXMLFile.getContents(), handler);
    } catch (Exception e) {
      throw new BuildException(e.getMessage(), e);
    }

    return result;
  }
Beispiel #17
0
  /**
   * Search for reviewed violations in that file
   *
   * @param file
   */
  private List<Review> findReviewedViolations(final IFile file) {
    final List<Review> reviews = new ArrayList<Review>();
    BufferedReader reader = null;
    try {
      int lineNumber = 0;
      boolean findLine = false;
      boolean comment = false;
      final Stack<String> pendingReviews = new Stack<String>();
      reader = new BufferedReader(new InputStreamReader(file.getContents()));
      while (reader.ready()) {
        String line = reader.readLine();
        if (line != null) {
          line = line.trim();
          lineNumber++;
          if (line.startsWith("/*")) {
            comment = line.indexOf("*/") == -1;
          } else if (comment && line.indexOf("*/") != -1) {
            comment = false;
          } else if (!comment && line.startsWith(PMDRuntimeConstants.PLUGIN_STYLE_REVIEW_COMMENT)) {
            final String tail =
                line.substring(PMDRuntimeConstants.PLUGIN_STYLE_REVIEW_COMMENT.length());
            final String ruleName = tail.substring(0, tail.indexOf(':'));
            pendingReviews.push(ruleName);
            findLine = true;
          } else if (!comment
              && findLine
              && StringUtil.isNotEmpty(line)
              && !line.startsWith("//")) {
            findLine = false;
            while (!pendingReviews.empty()) {
              // @PMD:REVIEWED:AvoidInstantiatingObjectsInLoops:
              // by Herlin on 01/05/05 18:36
              final Review review = new Review();
              review.ruleName = pendingReviews.pop();
              review.lineNumber = lineNumber;
              reviews.add(review);
            }
          }
        }
      }

      // if (log.isDebugEnabled()) {
      // for (int i = 0; i < reviewsList.size(); i++) {
      // final Review review = (Review) reviewsList.get(i);
      // log.debug("Review : rule " + review.ruleName + ", line " +
      // review.lineNumber);
      // }
      // }

    } catch (CoreException e) {
      PMDPlugin.getDefault().logError("Core Exception when searching reviewed violations", e);
    } catch (IOException e) {
      PMDPlugin.getDefault().logError("IO Exception when searching reviewed violations", e);
    } finally {
      IOUtil.closeQuietly(reader);
    }

    return reviews;
  }
Beispiel #18
0
 public IAccumulatingLexer createLexer(IFile file, ISourceForm sourceForm)
     throws CoreException, IOException {
   return createLexer(
       new BufferedReader(new InputStreamReader(file.getContents(true), file.getCharset())),
       file,
       SourceForm.determineFilename(file),
       sourceForm);
 }
  void collectAspectBindings(IFile file, SAXParser parser) {
    try {
      parser.parse(
          file.getContents(),
          new DefaultHandler() {
            String basePluginID = null;
            ArrayList<String> teamClasses = null;
            StringBuffer forcedExports = null;

            @Override
            public void startElement(
                String uri, String localName, String name, Attributes attributes)
                throws SAXException {
              if (name.equals(ASPECT_BINDING)) this.teamClasses = new ArrayList<String>();
              else if (this.teamClasses != null) { // within an aspectBinding element?
                if (name.equals(BASE_PLUGIN)) {
                  this.basePluginID = attributes.getValue(ID);
                } else if (name.equals(TEAM)) {
                  String teamClass = attributes.getValue(CLASS);
                  if (teamClass == null)
                    throw new SAXException(
                        "team element lacking \"class\" attribute"); //$NON-NLS-1$
                  this.teamClasses.add(teamClass);
                } else if (name.equals(FORCED_EXPORTS)) {
                  this.forcedExports = new StringBuffer();
                }
              }
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
              if (this.forcedExports != null) this.forcedExports.append(ch, start, length);
            }

            @Override
            public void endElement(String uri, String localName, String name) throws SAXException {
              if (name.equals(ASPECT_BINDING)) {
                if (this.basePluginID == null)
                  throw new SAXException(
                      "aspectBinding missing a \"basePlugin\" element"); //$NON-NLS-1$
                for (String teamClass : this.teamClasses)
                  recordAspectBinding(teamClass, this.basePluginID);
                this.basePluginID = null;
                this.teamClasses = null;
              } else if (name.equals(FORCED_EXPORTS)) {
                if (this.forcedExports != null && this.forcedExports.length() > 0)
                  recordForcedExports(this.basePluginID, this.forcedExports.toString());
                this.forcedExports = null;
              }
            }
          });
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /** Tries to delete a folder containing an unremovable file. Works only for Windows. */
  public void testDeleteFolderWindows() {
    if (!isWindows()) return;

    IProject project = null;
    InputStream input = null;
    File projectRoot = null;
    try {
      IWorkspace workspace = getWorkspace();
      project = workspace.getRoot().getProject(getUniqueString());
      IFolder folder = project.getFolder("a_folder");
      IFile file1 = folder.getFile("file1.txt");
      IFile file3 = folder.getFile("file3.txt");

      ensureExistsInWorkspace(new IResource[] {file1, file3}, true);
      projectRoot = project.getLocation().toFile();

      // opens a file so it cannot be removed on Windows
      try {
        input = file1.getContents();
      } catch (CoreException ce) {
        ce.printStackTrace();
        fail("1.0");
      }

      try {
        folder.delete(IResource.FORCE, getMonitor());
        fail("2.0 - should have failed");
      } catch (CoreException ce) {
        // success - a file couldn't be removed
      }
      assertTrue("2.2", file1.exists());
      assertTrue("2.4", !file3.exists());
      assertTrue("2.5", folder.exists());
      assertTrue("2.7", folder.isSynchronized(IResource.DEPTH_INFINITE));

      assertClose(input);

      assertTrue("3.5", project.isSynchronized(IResource.DEPTH_INFINITE));
      try {
        folder.delete(IResource.FORCE, getMonitor());
      } catch (CoreException ce) {
        ce.printStackTrace();
        fail("4.0", ce);
      }
      assertTrue("5.1", !file1.exists());
      assertTrue("5.2", !folder.exists());
      assertTrue("5.3", file1.isSynchronized(IResource.DEPTH_INFINITE));
      assertTrue("5.4", folder.isSynchronized(IResource.DEPTH_INFINITE));
    } finally {
      try {
        assertClose(input);
      } finally {
        if (projectRoot != null) ensureDoesNotExistInFileSystem(projectRoot);
      }
    }
  }
  /**
   * Write the contents of the file to the tar archive.
   *
   * @param entry
   * @param contents
   * @exception java.io.IOException
   * @exception org.eclipse.core.runtime.CoreException
   */
  private void write(ZipEntry entry, IFile contents) throws IOException, CoreException {
    byte[] readBuffer = new byte[4096];

    // If the contents are being compressed then we get the below for free.
    if (!useCompression) {
      entry.setMethod(ZipEntry.STORED);
      InputStream contentStream = contents.getContents(false);
      int length = 0;
      CRC32 checksumCalculator = new CRC32();
      try {
        int n;
        while ((n = contentStream.read(readBuffer)) > 0) {
          checksumCalculator.update(readBuffer, 0, n);
          length += n;
        }
      } finally {
        if (contentStream != null) {
          contentStream.close();
        }
      }

      entry.setSize(length);
      entry.setCrc(checksumCalculator.getValue());
    }

    // set the timestamp
    long localTimeStamp = contents.getLocalTimeStamp();
    if (localTimeStamp != IResource.NULL_STAMP) entry.setTime(localTimeStamp);

    outputStream.putNextEntry(entry);
    InputStream contentStream = contents.getContents(false);
    try {
      int n;
      while ((n = contentStream.read(readBuffer)) > 0) {
        outputStream.write(readBuffer, 0, n);
      }
    } finally {
      if (contentStream != null) {
        contentStream.close();
      }
    }
    outputStream.closeEntry();
  }
Beispiel #22
0
  /**
   * This operation scans the default project area for SerializedItems and loads them into the Core.
   * It returns false if it encounters and error and true if it is successful.
   *
   * @return True if the SerializedItems stored in the default project area were loaded
   *     successfully, false otherwise.
   */
  private boolean loadDefaultAreaItems() {

    // Local Declarations
    boolean status = false;
    ArrayList<String> serializedItemNames = new ArrayList<String>();
    SerializedItemBuilder builder = null;
    IProject project;
    IResource[] resources = null;
    IResource currentResource = null;
    IFile file = null;
    String filename = null;

    // Get the default project and grab its contents
    project = projectTable.get("defaultUser");
    if (project == null) {
      return status;
    }
    try {
      // Update the status
      status = true;
      // If the "jobProfiles" folder exists, loop over the resources and
      // get the serialized items
      if (project.getFolder("jobProfiles").exists()) {
        // Get the list of resources in the project
        resources = project.getFolder("jobProfiles").members();
        for (int i = 0; i < resources.length; i++) {
          currentResource = resources[i];
          filename = currentResource.getFullPath().toOSString();
          // Grab PSF or XML file
          if (filename.endsWith(".psf") | filename.endsWith(".xml")) {
            // Get the file
            file = project.getFile(currentResource.getProjectRelativePath());
            try {
              // Load the SerializedItemBuilder
              builder = new SerializedItemBuilder(file.getContents());
              // Register the builder
              itemManager.registerBuilder(builder);
            } catch (IOException e) {
              // TODO Auto-generated catch block
              logger.error(getClass().getName() + " Exception!", e);
              status = false;
            }
          }
        }
      } else {
        // Otherwise create the folder and return since there is nothing
        // to load
        project.getFolder("jobProfiles").create(true, true, null);
      }
    } catch (CoreException e) {
      logger.error(getClass().getName() + " Exception!", e);
    }

    return status;
  }
Beispiel #23
0
 protected StringBuilder getCodeFromFile(IFile file) throws Exception {
   BufferedReader br = new BufferedReader(new InputStreamReader(file.getContents()));
   StringBuilder code = new StringBuilder();
   String line;
   while ((line = br.readLine()) != null) {
     code.append(line);
     code.append('\n');
   }
   br.close();
   return code;
 }
  private void getChangedLines(Subscriber s, PatchFile p, IProgressMonitor monitor) {
    try {
      // For an outgoing changed resource, find out which lines
      // differ from the local file and its previous local version
      // (i.e. we don't want to force a diff with the repository).
      IDiff d = s.getDiff(p.getResource());
      if (d instanceof IThreeWayDiff
          && ((IThreeWayDiff) d).getDirection() == IThreeWayDiff.OUTGOING) {
        IThreeWayDiff diff = (IThreeWayDiff) d;
        monitor.beginTask(null, 100);
        IResourceDiff localDiff = (IResourceDiff) diff.getLocalChange();
        IResource resource = localDiff.getResource();
        if (resource instanceof IFile) {
          IFile file = (IFile) resource;
          monitor.subTask(Messages.getString("ChangeLog.MergingDiffs")); // $NON-NLS-1$
          String osEncoding = file.getCharset();
          IFileRevision ancestorState = localDiff.getBeforeState();
          IStorage ancestorStorage;
          if (ancestorState != null) {
            ancestorStorage = ancestorState.getStorage(monitor);
            p.setStorage(ancestorStorage);
          } else ancestorStorage = null;

          try {
            // We compare using a standard differencer to get ranges
            // of changes.  We modify them to be document-based (i.e.
            // first line is line 1) and store them for later parsing.
            LineComparator left = new LineComparator(ancestorStorage.getContents(), osEncoding);
            LineComparator right = new LineComparator(file.getContents(), osEncoding);
            for (RangeDifference tmp : RangeDifferencer.findDifferences(left, right)) {
              if (tmp.kind() == RangeDifference.CHANGE) {
                // Right side of diff are all changes found in local file.
                int rightLength = tmp.rightLength() > 0 ? tmp.rightLength() : tmp.rightLength() + 1;
                // We also want to store left side of the diff which are changes to the ancestor as
                // it may contain
                // functions/methods that have been removed.
                int leftLength = tmp.leftLength() > 0 ? tmp.leftLength() : tmp.leftLength() + 1;
                // Only store left side changes if the storage exists and we add one to the start
                // line number
                if (p.getStorage() != null)
                  p.addLineRange(tmp.leftStart(), tmp.leftStart() + leftLength, false);
                p.addLineRange(tmp.rightStart(), tmp.rightStart() + rightLength, true);
              }
            }
          } catch (UnsupportedEncodingException e) {
            // do nothing for now
          }
        }
        monitor.done();
      }
    } catch (CoreException e) {
      // Do nothing if error occurs
    }
  }
 private List<String> loadFile(IFile file)
     throws FileNotFoundException, IOException, CoreException {
   List<String> lines = new ArrayList<String>();
   DataInputStream in = new DataInputStream(file.getContents());
   BufferedReader br = new BufferedReader(new InputStreamReader(in));
   while (br.ready()) {
     String line = br.readLine();
     lines.add(line);
   }
   br.close();
   return lines;
 }
  private InputStream createInputStream(IFile propertiesFile) throws CoreException {
    ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager();
    if (manager != null) {
      ITextFileBuffer buffer =
          manager.getTextFileBuffer(propertiesFile.getFullPath(), LocationKind.IFILE);
      if (buffer != null) {
        return new ByteArrayInputStream(buffer.getDocument().get().getBytes());
      }
    }

    return propertiesFile.getContents();
  }
  public IProjectFacetVersion getWebFacetVersion(IProject project) {
    IFile webXml;
    String customWebXml = getCustomWebXml(project);
    if (customWebXml == null) {
      webXml = project.getFolder(getWarSourceDirectory()).getFile(WEB_XML);
    } else {
      webXml = project.getFile(customWebXml);
    }

    if (webXml.isAccessible()) {
      try {
        InputStream is = webXml.getContents();
        try {
          JavaEEQuickPeek jqp = new JavaEEQuickPeek(is);
          switch (jqp.getVersion()) {
            case J2EEVersionConstants.WEB_2_2_ID:
              return WebFacetUtils.WEB_22;
            case J2EEVersionConstants.WEB_2_3_ID:
              return WebFacetUtils.WEB_23;
            case J2EEVersionConstants.WEB_2_4_ID:
              return WebFacetUtils.WEB_24;
            case J2EEVersionConstants.WEB_2_5_ID:
              return WebFacetUtils.WEB_FACET.getVersion("2.5");
              // MNGECLIPSE-1978
            case WEB_3_0_ID: // JavaEEQuickPeek will return this value only if WTP version >= 3.2
              return WebFacetUtils.WEB_FACET.getVersion("3.0"); // only exists in WTP version >= 3.2
          }
        } finally {
          is.close();
        }
      } catch (IOException ex) {
        // expected
      } catch (CoreException ex) {
        // expected
      }
    }

    // MNGECLIPSE-1978 If no web.xml found and the project depends on some java EE 6 jar and WTP >=
    // 3.2, then set web facet to 3.0
    if (WTPProjectsUtil.isJavaEE6Available()
        && WTPProjectsUtil.hasInClassPath(project, "javax.servlet.annotation.WebServlet")) {
      return WebFacetUtils.WEB_FACET.getVersion("3.0");
    }

    // MNGECLIPSE-984 web.xml is optional for 2.5 Web Projects
    return WTPProjectsUtil.DEFAULT_WEB_FACET;
    // We don't want to prevent the project creation when the java compiler level is < 5, we coud
    // try that instead :
    // IProjectFacetVersion javaFv =
    // JavaFacetUtils.compilerLevelToFacet(JavaFacetUtils.getCompilerLevel(project));
    // return (JavaFacetUtils.JAVA_50.compareTo(javaFv) >
    // 0)?WebFacetUtils.WEB_24:WebFacetUtils.WEB_25;
  }
Beispiel #28
0
  private void filter(IFile diskFile, Transformer transformer, IProgressMonitor monitor)
      throws TransformerException, CoreException, IOException {

    InputStream is = diskFile.getContents();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Source source = new StreamSource(is);

    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes");

    /*
     * If we want to match the existing DXL as close as possible we omit the
     * transformer's declaration as it includes the encoding='UTF-8'
     * attribute that is not included in normal DXL Export
     */
    if (mimicDoraXmlDeclaration) {
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      baos.write(XML_DECL);
    }

    StreamResult result = new StreamResult(baos);

    transformer.transform(source, result);

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    diskFile.setContents(bais, 0, monitor);

    /*
     * When you export the DXL normally, there is an Newline at the end of
     * the file. However, this transformer does not include the Newline at
     * the end. By Default, we will just go with what the transformer does.
     *
     * However, if we choose to mimic what the DXL Export EOF does then we
     * will add the extra new lines to be the same as the normmal DXL
     * Export.
     */
    if (mimicDxlExportEOF) {

      // Add a New line Because that is what normally happens
      String linesep = System.getProperty("line.separator");

      linesep = linesep + linesep;
      bais = new ByteArrayInputStream(linesep.getBytes("UTF-8"));
      diskFile.appendContents(bais, 0, monitor);
    }

    is.close();

    SyncUtil.setModifiedBySync(diskFile);
  }
 private Image prepareImage(Device dev, IFile f) throws CoreException {
   try {
     Image image = new Image(dev, f.getContents());
     Rectangle size = image.getBounds();
     if (size.width > 16 || size.height > 16) {
       image = resize(image);
     }
     return image;
   } catch (Exception e) {
     // happens if the image isn't an image
     return null;
   }
 }
  /**
   * If a MED with the same NS Prefix is already registered, it will be removed and replaced with
   * the supplied MED
   *
   * @param medFile the file containing the med definition
   * @throws Exception throws exception if the add operation failed
   */
  private static void updateExtensionInRegistry(IFile medFile) throws Exception {
    ModelExtensionRegistry registry = ExtensionPlugin.getInstance().getRegistry();

    // If MED with this prefix is registered, remove it first
    ModelExtensionDefinition med =
        RegistryDeploymentValidator.parseMed(medFile.getContents(), false);
    if (registry.isNamespacePrefixRegistered(med.getNamespacePrefix())) {
      registry.removeDefinition(med.getNamespacePrefix());
    }

    // Add the supplied MED
    addExtensionToRegistry(medFile);
  }