@Test
 public void testUpdatePomArtifactId() {
   PomXmlWriter.updatePomArtifactId(document, "koala-commons-codechecker-2");
   DocumentUtil.document2Xml(xmlPath, document);
   Document document2 = DocumentUtil.readDocument(xmlPath);
   String artifactId = PomXmlReader.queryText("/xmlns:project/xmlns:artifactId", document2);
   Assert.assertEquals(artifactId, "koala-commons-codechecker-2");
 }
  /**
   * Deletes the specified object from the object set.
   *
   * <p>{@inheritDoc}
   *
   * @throws NotFoundException if the specified object could not be found.
   * @throws ForbiddenException if access to the object is forbidden.
   * @throws ConflictException if version is required but is {@code null}.
   * @throws PreconditionFailedException if version did not match the existing object in the set.
   */
  @Override
  public ResourceResponse delete(DeleteRequest request) throws ResourceException {
    if (request.getResourcePathObject().size() < 2) {
      throw new NotFoundException(
          "The object identifier did not include sufficient information to determine the object type and identifier of the object to update: "
              + request.getResourcePath());
    }

    if (request.getRevision() == null || "".equals(request.getRevision())) {
      throw new ConflictException(
          "Object passed into delete does not have revision it expects set.");
    }

    final String type = request.getResourcePathObject().parent().toString();
    final String localId = request.getResourcePathObject().leaf();

    int ver =
        DocumentUtil.parseVersion(
            request.getRevision()); // This throws ConflictException if parse fails

    ODatabaseDocumentTx db = getConnection();
    try {
      ODocument existingDoc = predefinedQueries.getByID(localId, type, db);
      if (existingDoc == null) {
        throw new NotFoundException(
            "Object does not exist for delete on: " + request.getResourcePath());
      }

      db.delete(existingDoc.getIdentity(), new OSimpleVersion(ver));
      logger.debug("delete for id succeeded: {} revision: {}", localId, request.getRevision());
      return DocumentUtil.toResource(existingDoc);
    } catch (ODatabaseException ex) {
      // Without transaction the concurrent modification exception gets nested instead
      if (isCauseConcurrentModificationException(ex, 10)) {
        throw new PreconditionFailedException(
            "Delete rejected as current Object revision is different than expected by caller, the object has changed since retrieval. "
                + ex.getMessage(),
            ex);
      } else {
        throw ex;
      }

    } catch (OConcurrentModificationException ex) {
      throw new PreconditionFailedException(
          "Delete rejected as current Object revision is different than expected by caller, the object has changed since retrieval."
              + ex.getMessage(),
          ex);
    } catch (RuntimeException e) {
      throw e;
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
  /**
   * The object will contain metadata properties, including object identifier {@code _id}, and
   * object version {@code _rev} to enable optimistic concurrency supported by OrientDB and OpenIDM.
   *
   * @param request the identifier of the object to retrieve from the object set.
   * @throws NotFoundException if the specified object could not be found.
   * @throws ForbiddenException if access to the object is forbidden.
   * @throws BadRequestException if the passed identifier is invalid
   * @return the requested object.
   */
  @Override
  public ResourceResponse read(ReadRequest request) throws ResourceException {
    if (request.getResourcePathObject().size() < 2) {
      throw new NotFoundException(
          "The object identifier did not include sufficient information to determine the object type and identifier of the object to read: "
              + request.getResourcePath());
    }

    final String type = request.getResourcePathObject().parent().toString();
    final String localId = request.getResourcePathObject().leaf();
    ResourceResponse result = null;
    ODatabaseDocumentTx db = getConnection();
    try {
      ODocument doc = predefinedQueries.getByID(localId, type, db);
      if (doc == null) {
        throw new NotFoundException("Object " + localId + " not found in " + type);
      }
      result = DocumentUtil.toResource(doc);
      logger.trace("Completed get for id: {} result: {}", request.getResourcePath(), result);
      return result;
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
 public static void doPostponedFormatting(final Project project) {
   DocumentUtil.writeInRunUndoTransparentAction(
       new Runnable() {
         @Override
         public void run() {
           PsiDocumentManager.getInstance(project).commitAllDocuments();
           PostprocessReformattingAspect.getInstance(project).doPostponedFormatting();
         }
       });
 }
  @Override
  public List<ResourceResponse> query(final QueryRequest request) throws ResourceException {
    List<ResourceResponse> results = new ArrayList<ResourceResponse>();

    logger.trace(
        "Full id: {} Extracted type: {}", request.getResourcePath(), request.getResourcePath());
    // TODO: Statistics is not returned in result anymore
    // TODO: result is not needed in map form anymore
    Map<String, Object> result = new HashMap<String, Object>();
    ODatabaseDocumentTx db = getConnection();
    try {
      // List<Map<String, Object>> docs = new ArrayList<Map<String, Object>>();
      // result.put(QueryConstants.QUERY_RESULT, docs);
      long start = System.currentTimeMillis();
      List<ODocument> queryResult = queries.query(request.getResourcePath(), request, db);
      long end = System.currentTimeMillis();
      if (queryResult != null) {
        long convStart = System.currentTimeMillis();
        for (ODocument entry : queryResult) {
          Map<String, Object> convertedEntry = DocumentUtil.toMap(entry);
          // docs.add(convertedEntry);
          results.add(
              newResourceResponse(
                  (String) convertedEntry.get(DocumentUtil.TAG_ID),
                  (String) convertedEntry.get(DocumentUtil.TAG_REV),
                  new JsonValue(convertedEntry)));
        }
        long convEnd = System.currentTimeMillis();
        result.put(QueryConstants.STATISTICS_CONVERSION_TIME, Long.valueOf(convEnd - convStart));
      }
      result.put(QueryConstants.STATISTICS_QUERY_TIME, Long.valueOf(end - start));

      if (logger.isDebugEnabled()) {
        logger.debug(
            "Query result contains {} records, took {} ms and took {} ms to convert result.",
            new Object[] {
              results.size(),
              result.get(QueryConstants.STATISTICS_QUERY_TIME),
              result.get(QueryConstants.STATISTICS_CONVERSION_TIME)
            });
      }
      return results;
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
  public int[] moveWidget(
      final int oldContainerOffset,
      final int oldContainerLength,
      final int oldContainerIndex,
      final int newContainerOffset,
      final int newContainerLength,
      final int newContainerIndex) {
    try {
      IEGLFile modelFile = (IEGLFile) EGLCore.create(currentFile);
      IEGLFile sharedWorkingCopy =
          (IEGLFile) modelFile.getSharedWorkingCopy(null, EGLUI.getBufferFactory(), null);
      sharedWorkingCopy.open(null);
      sharedWorkingCopy.reconcile(false, null);

      try {
        final Node oldContainer =
            DocumentUtil.getWidgetNode(currentDocument, oldContainerOffset, oldContainerLength);
        final Node newContainer =
            DocumentUtil.getWidgetNode(currentDocument, newContainerOffset, newContainerLength);
        final int newIndex =
            calculateNewIndex(oldContainer, newContainer, oldContainerIndex, newContainerIndex);
        oldContainer.accept(
            new DefaultASTVisitor() {
              public boolean visit(Handler handler) {
                // Assume this is a RUIHandler
                EGLRUIHandlerLocatorStrategy strategy = new EGLRUIHandlerLocatorStrategy(handler);
                final Node nodeToMove = strategy.locateIndex(oldContainerIndex);
                MoveNodeOperation moveOp =
                    new MoveNodeOperation(
                        oldContainerOffset,
                        oldContainerLength,
                        oldContainerIndex,
                        newContainerOffset,
                        newContainerIndex,
                        newIndex);
                nodeToMove.accept(moveOp);
                return false;
              }

              public boolean visit(final NewExpression newExpression) {
                EGLContainerLocatorStrategy strategy =
                    new EGLContainerLocatorStrategy(oldContainer);
                final Node nodeToMove = strategy.locateIndex(oldContainerIndex);
                MoveNodeOperation moveOp =
                    new MoveNodeOperation(
                        oldContainerOffset,
                        oldContainerLength,
                        oldContainerIndex,
                        newContainerOffset,
                        newContainerIndex,
                        newIndex);
                nodeToMove.accept(moveOp);
                return false;
              }

              public boolean visit(final SimpleName simpleName) {
                EGLContainerLocatorStrategy strategy =
                    new EGLContainerLocatorStrategy(oldContainer);
                final Node nodeToMove = strategy.locateIndex(oldContainerIndex);
                MoveNodeOperation moveOp =
                    new MoveNodeOperation(
                        oldContainerOffset,
                        oldContainerLength,
                        oldContainerIndex,
                        newContainerOffset,
                        newContainerIndex,
                        newIndex);
                nodeToMove.accept(moveOp);
                return false;
              }
            });
      } catch (Exception e) {
        Activator.getDefault()
            .getLog()
            .log(
                new Status(
                    Status.ERROR,
                    Activator.PLUGIN_ID,
                    "Move Widget Reference: Error moving reference",
                    e));
      } finally {
        sharedWorkingCopy.destroy();
      }
    } catch (EGLModelException e) {
      Activator.getDefault()
          .getLog()
          .log(
              new Status(
                  Status.ERROR,
                  Activator.PLUGIN_ID,
                  "Move Widget Reference: Error creating working copy",
                  e));
    }
    return charactersChanged;
  }
  /**
   * Updates the specified object in the object set.
   *
   * <p>This implementation does not require MVCC and uses the current revision if no revision is
   * specified in the request.
   *
   * <p>If successful, this method updates metadata properties within the passed object, including:
   * a new {@code _rev} value for the revised object's version
   *
   * @param request the contents of the object to update
   * @throws ConflictException if version is required but is {@code null}.
   * @throws ForbiddenException if access to the object is forbidden.
   * @throws NotFoundException if the specified object could not be found.
   * @throws PreconditionFailedException if version did not match the existing object in the set.
   * @throws BadRequestException if the passed identifier is invalid
   */
  @Override
  public ResourceResponse update(UpdateRequest request) throws ResourceException {
    if (request.getResourcePathObject().size() < 2) {
      throw new NotFoundException(
          "The object identifier did not include sufficient information to determine the object type and identifier of the object to update: "
              + request.getResourcePath());
    }

    final String type = request.getResourcePathObject().parent().toString();
    final String localId = request.getResourcePathObject().leaf();

    String orientClassName = typeToOrientClassName(type);
    JsonValue obj = request.getContent();

    if (request.getRevision() != null && !"".equals(request.getRevision())) {
      obj.put(DocumentUtil.TAG_REV, request.getRevision());
    }

    ODatabaseDocumentTx db = getConnection();
    try {
      ODocument existingDoc = predefinedQueries.getByID(localId, type, db);
      if (existingDoc == null) {
        throw new NotFoundException(
            "Update on object " + request.getResourcePath() + " could not find existing object.");
      }
      ODocument updatedDoc = DocumentUtil.toDocument(obj, existingDoc, db, orientClassName);
      logger.trace("Updated doc for id {} to save {}", request.getResourcePath(), updatedDoc);

      updatedDoc.save();

      obj.put(DocumentUtil.TAG_REV, Integer.toString(updatedDoc.getVersion()));
      // Set ID to return to caller
      obj.put(DocumentUtil.TAG_ID, updatedDoc.field(DocumentUtil.ORIENTDB_PRIMARY_KEY));
      logger.debug(
          "Committed update for id: {} revision: {}",
          request.getResourcePath(),
          updatedDoc.getVersion());
      logger.trace("Update payload for id: {} doc: {}", request.getResourcePath(), updatedDoc);
      return newResourceResponse(
          obj.get(DocumentUtil.TAG_ID).asString(), obj.get(DocumentUtil.TAG_REV).asString(), obj);
    } catch (ODatabaseException ex) {
      // Without transaction the concurrent modification exception gets nested instead
      if (isCauseConcurrentModificationException(ex, 10)) {
        throw new PreconditionFailedException(
            "Update rejected as current Object revision is different than expected by caller, the object has changed since retrieval: "
                + ex.getMessage(),
            ex);
      } else {
        throw ex;
      }
    } catch (OConcurrentModificationException ex) {
      throw new PreconditionFailedException(
          "Update rejected as current Object revision is different than expected by caller, the object has changed since retrieval: "
              + ex.getMessage(),
          ex);
    } catch (RuntimeException e) {
      throw e;
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
  /**
   * Creates a new object in the object set.
   *
   * <p>This method sets the {@code _id} property to the assigned identifier for the object, and the
   * {@code _rev} property to the revised object version (For optimistic concurrency)
   *
   * @param request the contents of the object to create in the object set.
   * @throws NotFoundException if the specified id could not be resolved.
   * @throws ForbiddenException if access to the object or object set is forbidden.
   * @throws ConflictException if an object with the same ID already exists.
   */
  @Override
  public ResourceResponse create(CreateRequest request) throws ResourceException {
    if (request.getResourcePathObject().isEmpty()) {
      throw new NotFoundException(
          "The object identifier did not include sufficient information to determine the object type: "
              + request.getResourcePath());
    }

    final String type = request.getResourcePath();
    // TODO: should CREST support server side generation of ID itself?
    final String localId =
        (request.getNewResourceId() == null || "".equals(request.getNewResourceId()))
            ? UUID.randomUUID().toString() // Generate ID server side.
            : request.getNewResourceId();

    // Used currently for logging
    String fullId = request.getResourcePathObject().child(localId).toString();

    String orientClassName = typeToOrientClassName(type);
    JsonValue obj = request.getContent();

    obj.put(DocumentUtil.TAG_ID, localId);

    ODatabaseDocumentTx db = getConnection();
    try {
      // Rather than using MVCC for insert, rely on primary key uniqueness constraints to detect
      // duplicate create
      ODocument newDoc = DocumentUtil.toDocument(obj, null, db, orientClassName);
      logger.trace("Created doc for id: {} to save {}", fullId, newDoc);
      newDoc.save();

      obj.put(DocumentUtil.TAG_REV, Integer.toString(newDoc.getVersion()));
      logger.debug("Completed create for id: {} revision: {}", fullId, newDoc.getVersion());
      logger.trace("Create payload for id: {} doc: {}", fullId, newDoc);
      return newResourceResponse(
          obj.get(DocumentUtil.TAG_ID).asString(), obj.get(DocumentUtil.TAG_REV).asString(), obj);
    } catch (ORecordDuplicatedException ex) {
      // Because the OpenIDM ID is defined as unique, duplicate inserts must fail
      throw new PreconditionFailedException(
          "Create rejected as Object with same ID already exists. " + ex.getMessage(), ex);
    } catch (OIndexException ex) {
      // Because the OpenIDM ID is defined as unique, duplicate inserts must fail
      throw new PreconditionFailedException(
          "Create rejected as Object with same ID already exists. " + ex.getMessage(), ex);
    } catch (ODatabaseException ex) {
      // Because the OpenIDM ID is defined as unique, duplicate inserts must fail.
      // OrientDB may wrap the IndexException root cause.
      if (isCauseIndexException(ex, 10) || isCauseRecordDuplicatedException(ex, 10)) {
        throw new PreconditionFailedException(
            "Create rejected as Object with same ID already exists and was detected. "
                + ex.getMessage(),
            ex);
      } else {
        throw ex;
      }
    } catch (RuntimeException e) {
      throw e;
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
 private void initDoucment() {
   document = DocumentUtil.readDocument(xmlPath);
 }