Exemplo n.º 1
0
  /**
   * For Editing : adds an attribute from a metadata ([add] link). FIXME: Modify and use within Ajax
   * controls
   *
   * @param dbms
   * @param id
   * @param ref
   * @param name
   * @param currVersion
   * @return
   * @throws Exception
   */
  public synchronized boolean addAttribute(
      Dbms dbms, String id, String ref, String name, String currVersion) throws Exception {
    Element md = xmlSerializer.select(dbms, "Metadata", id);

    // --- check if the metadata has been deleted
    if (md == null) return false;

    String schema = dataManager.getMetadataSchema(dbms, id);
    EditLib editLib = dataManager.getEditLib();
    editLib.expandElements(schema, md);
    editLib.enumerateTree(md);

    // --- get element to add
    Element el = editLib.findElement(md, ref);

    if (el == null) Log.error(Geonet.DATA_MANAGER, MSG_ELEMENT_NOT_FOUND_AT_REF + ref);
    // throw new IllegalStateException("Element not found at ref = " + ref);

    // --- remove editing info added by previous call
    editLib.removeEditingInfo(md);

    if (el != null) {
      el.setAttribute(new Attribute(name, ""));
    }

    editLib.contractElements(md);
    String parentUuid = null;
    md =
        dataManager.updateFixedInfo(
            schema, id, null, md, parentUuid, DataManager.UpdateDatestamp.no, dbms);
    String changeDate = null;
    xmlSerializer.update(dbms, id, md, changeDate, false, context);

    // Notifies the metadata change to metatada notifier service
    dataManager.notifyMetadataChange(dbms, md, id);

    // --- update search criteria
    boolean workspace = false;
    dataManager.indexInThreadPoolIfPossible(dbms, id, workspace);

    return true;
  }
Exemplo n.º 2
0
  public int evaluate(int timeout) {
    try {
      if (Log.isDebugEnabled(Geonet.Z3950_SERVER))
        Log.debug(Geonet.Z3950_SERVER, "INCOMING XML QUERY:\n" + query);

      Element request = new Element("request");
      request.addContent(query.toGNXMLRep());

      List<String> categories = query.getCollections();
      for (String category : categories) {
        if (!category.equals("geonetwork") && !category.equals("Default"))
          request.addContent(new Element("category").setText(category));
      }

      ServiceConfig config = new ServiceConfig();

      // perform the search and save search results

      metasearcher.search(this.srvxtx, request, config);

      // System.out.println("summary:\n" + Xml.getString(s.getSummary()));
      // // DEBUG

      // Random number of records.. Set up the result set
      setFragmentCount(metasearcher.getSize());
      setTaskStatusCode(IRResultSetStatus.COMPLETE);

      this.srvxtx.getResourceManager().close();
    } catch (Throwable e) {
      Log.error(Geonet.Z3950_SERVER, "error evaluating query.." + e);
      e.printStackTrace();

      try {
        this.srvxtx.getResourceManager().abort();
      } catch (Exception e2) {
        e2.printStackTrace();
      }
    }
    return (getStatus());
  }
Exemplo n.º 3
0
  public Element execute(Element request, ServiceContext context) throws CatalogException {
    checkService(request);
    checkVersion(request);

    Element response = new Element(getName() + "Response", Csw.NAMESPACE_CSW);

    String[] propertyNames = getParameters(request, "PropertyName");
    String[] parameterNames = getParameters(request, "ParameterName");

    String cswServiceSpecificConstraint = request.getChildText(Geonet.Elem.FILTER);

    // PropertyName handled first.
    if (propertyNames != null) {
      List<Element> domainValues;
      try {
        domainValues =
            handlePropertyName(
                propertyNames,
                context,
                false,
                CatalogConfiguration.getMaxNumberOfRecordsForPropertyNames(),
                cswServiceSpecificConstraint,
                _luceneConfig);
      } catch (Exception e) {
        Log.error(Geonet.CSW, "Error getting domain value for specified PropertyName : " + e);
        throw new NoApplicableCodeEx(
            "Raised exception while getting domain value for specified PropertyName  : " + e);
      }
      response.addContent(domainValues);
      return response;
    }

    if (parameterNames != null) {
      List<Element> domainValues = handleParameterName(parameterNames);
      response.addContent(domainValues);
    }

    return response;
  }
Exemplo n.º 4
0
  private void execute(HttpServletRequest req, HttpServletResponse res) throws IOException {
    String ip = req.getRemoteAddr();
    // if we do have the optional x-forwarded-for request header then
    // use whatever is in it to record ip address of client
    String forwardedFor = req.getHeader("x-forwarded-for");
    if (forwardedFor != null) ip = forwardedFor;

    Log.info(Log.REQUEST, "==========================================================");
    Log.info(Log.REQUEST, "HTML Request (from " + ip + ") : " + req.getRequestURI());
    Log.debug(Log.REQUEST, "Method       : " + req.getMethod());
    Log.debug(Log.REQUEST, "Content type : " + req.getContentType());
    //		Log.debug(Log.REQUEST, "Context path : "+ req.getContextPath());
    //		Log.debug(Log.REQUEST, "Char encoding: "+ req.getCharacterEncoding());
    Log.debug(Log.REQUEST, "Accept       : " + req.getHeader("Accept"));
    //		Log.debug(Log.REQUEST, "Server name  : "+ req.getServerName());
    //		Log.debug(Log.REQUEST, "Server port  : "+ req.getServerPort());

    //		for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
    //			String theHeader = (String)e.nextElement();
    //			Log.debug(Log.REQUEST, "Got header: "+theHeader);
    //			Log.debug(Log.REQUEST, "With value: "+req.getHeader(theHeader));
    //		}
    HttpSession httpSession = req.getSession();
    Log.debug(Log.REQUEST, "Session id is " + httpSession.getId());
    UserSession session = (UserSession) httpSession.getAttribute("session");

    // ------------------------------------------------------------------------
    // --- create a new session if doesn't exist

    if (session == null) {
      // --- create session

      session = new UserSession();

      httpSession.setAttribute("session", session);
      Log.debug(Log.REQUEST, "Session created for client : " + ip);
    }

    // ------------------------------------------------------------------------
    // --- build service request

    ServiceRequest srvReq = null;

    // --- create request

    try {
      srvReq =
          ServiceRequestFactory.create(req, res, jeeves.getUploadDir(), jeeves.getMaxUploadSize());
    } catch (FileUploadTooBigEx e) {
      StringBuffer sb = new StringBuffer();
      sb.append("File upload too big - exceeds " + jeeves.getMaxUploadSize() + " Mb\n");
      sb.append("Error : " + e.getClass().getName() + "\n");
      res.sendError(400, sb.toString());

      // now stick the stack trace on the end and log the whole lot
      sb.append("Stack :\n");
      sb.append(Util.getStackTrace(e));
      Log.error(Log.REQUEST, sb.toString());
      return;
    } catch (Exception e) {
      StringBuffer sb = new StringBuffer();

      sb.append("Cannot build ServiceRequest\n");
      sb.append("Cause : " + e.getMessage() + "\n");
      sb.append("Error : " + e.getClass().getName() + "\n");
      res.sendError(400, sb.toString());

      // now stick the stack trace on the end and log the whole lot
      sb.append("Stack :\n");
      sb.append(Util.getStackTrace(e));
      Log.error(Log.REQUEST, sb.toString());
      return;
    }

    // --- execute request

    jeeves.dispatch(srvReq, session);
  }
Exemplo n.º 5
0
  /**
   * Apply a list of changes to the metadata record in current editing session.
   *
   * <p>The changes are a list of KVP. A key contains at least the element identifier from the
   * meta-document. A key starting with an "X" should contain an XML fragment for the value. The
   * following KVP combinations are allowed:
   *
   * <ul>
   *   <li>ElementId=ElementValue
   *   <li>ElementId_AttributeName=AttributeValue
   *   <li>ElementId_AttributeNamespacePrefixCOLONAttributeName=AttributeValue
   *   <li>XElementId=ElementValue
   *   <li>XElementId_ElementName=ElementValue
   * </ul>
   *
   * ElementName MUST contain "{@value #COLON_SEPARATOR}" instead of ":" for prefixed elements.
   *
   * <p>When using X key, value could contains many XML fragments (eg. &lt;gmd:keywords
   * .../&gt;{@value #XML_FRAGMENT_SEPARATOR}&lt;gmd:keywords .../&gt;) separated by {@link
   * #XML_FRAGMENT_SEPARATOR}. All those fragments are inserted to the last element of this type in
   * its parent if ElementName is set. If not, the element with ElementId is replaced.
   *
   * <p>
   *
   * @param dbms
   * @param id Metadata internal identifier.
   * @param changes List of changes to apply.
   * @return The update metadata record
   * @throws Exception
   */
  protected Element applyChangesEmbedded(Dbms dbms, String id, Hashtable changes) throws Exception {
    String schema = dataManager.getMetadataSchema(dbms, id);
    EditLib editLib = dataManager.getEditLib();

    // --- get metadata from session
    Element md = getMetadataFromSession(session, id);

    // Store XML fragments to be handled after other elements update
    Map<String, String> xmlInputs = new HashMap<String, String>();

    // --- update elements
    for (Enumeration e = changes.keys(); e.hasMoreElements(); ) {
      String ref = ((String) e.nextElement()).trim();
      String value = ((String) changes.get(ref)).trim();
      String attribute = null;

      // Avoid empty key
      if (ref.equals("")) {
        continue;
      }

      // Catch element starting with a X to replace XML fragments
      if (ref.startsWith("X")) {
        ref = ref.substring(1);
        xmlInputs.put(ref, value);
        continue;
      }

      if (updatedLocalizedTextElement(md, ref, value, editLib)) {
        continue;
      }

      int at = ref.indexOf('_');
      if (at != -1) {
        attribute = ref.substring(at + 1);
        ref = ref.substring(0, at);
      }

      Element el = editLib.findElement(md, ref);
      if (el == null) {
        Log.error(Geonet.EDITOR, MSG_ELEMENT_NOT_FOUND_AT_REF + ref);
        continue;
      }

      // Process attribute
      if (attribute != null) {
        Pair<Namespace, String> attInfo =
            parseAttributeName(attribute, COLON_SEPARATOR, id, md, dbms, editLib);
        String localname = attInfo.two();
        Namespace attrNS = attInfo.one();
        if (el.getAttribute(localname, attrNS) != null) {
          el.setAttribute(new Attribute(localname, value, attrNS));
        }
      } else {
        // Process element value
        List content = el.getContent();

        for (int i = 0; i < content.size(); i++) {
          if (content.get(i) instanceof Text) {
            el.removeContent((Text) content.get(i));
            i--;
          }
        }
        el.addContent(value);
      }
    }

    // Deals with XML fragments to insert or update
    if (!xmlInputs.isEmpty()) {

      // Loop over each XML fragments to insert or replace
      for (String ref : xmlInputs.keySet()) {
        String value = xmlInputs.get(ref);
        String name = null;
        int addIndex = ref.indexOf('_');
        if (addIndex != -1) {
          name = ref.substring(addIndex + 1);
          ref = ref.substring(0, addIndex);
        }

        // Get element to fill
        Element el = editLib.findElement(md, ref);
        if (el == null) {
          Log.error(Geonet.EDITOR, MSG_ELEMENT_NOT_FOUND_AT_REF + ref);
          continue;
        }

        if (value != null && !value.equals("")) {
          String[] fragments = value.split(XML_FRAGMENT_SEPARATOR);
          for (String fragment : fragments) {
            if (name != null) {
              if (Log.isDebugEnabled(Geonet.EDITOR))
                Log.debug(
                    Geonet.EDITOR,
                    "Add XML fragment; " + fragment + " to element with ref: " + ref);
              name = name.replace(COLON_SEPARATOR, ":");
              editLib.addFragment(schema, el, name, fragment);
            } else {
              if (Log.isDebugEnabled(Geonet.EDITOR))
                Log.debug(
                    Geonet.EDITOR,
                    "Add XML fragment; "
                        + fragment
                        + " to element with ref: "
                        + ref
                        + " replacing content.");

              // clean before update
              el.removeContent();
              fragment = addNamespaceToFragment(fragment);

              // Add content
              el.addContent(Xml.loadString(fragment, false));
            }
          }
        }
      }
    }

    // --- remove editing info
    editLib.removeEditingInfo(md);
    editLib.contractElements(md);

    return (Element) md.detach();
  }
Exemplo n.º 6
0
 protected void error(String message) {
   Log.error(Log.DBMSPOOL, message);
 }
  public Element execute(Element request, ServiceContext context) throws CatalogException {
    checkService(request);
    checkVersion(request);

    // num counter
    int totalInserted = 0;
    int totalUpdated = 0;
    int totalDeleted = 0;

    // Response element
    Element response = new Element(getName() + "Response", Csw.NAMESPACE_CSW);

    List<String> strFileIds = new ArrayList<String>();

    // process the transaction from the first to the last
    List<Element> childList = request.getChildren();

    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    DataManager dataMan = gc.getDataManager();

    Set<String> toIndex = new HashSet<String>();

    try {
      // process the childlist
      for (Element transRequest : childList) {
        String transactionType = transRequest.getName().toLowerCase();
        if (transactionType.equals("insert")
            || transactionType.equals("update")
            || transactionType.equals("delete")) {
          List<Element> mdList = transRequest.getChildren();

          // insert to database, and get the number of inserted successful
          if (transactionType.equals("insert")) {
            Iterator<Element> inIt = mdList.iterator();
            while (inIt.hasNext()) {
              Element metadata = (Element) inIt.next().clone();
              boolean insertSuccess = insertTransaction(metadata, strFileIds, context, toIndex);
              if (insertSuccess) {
                totalInserted++;
              }
            }
          }
          // Update
          else if (transactionType.equals("update")) {
            Iterator<Element> inIt = mdList.iterator();
            Element metadata = null;

            while (inIt.hasNext()) {
              Element reqElem = (Element) inIt.next();
              if (reqElem.getNamespace() != Csw.NAMESPACE_CSW) {
                metadata = (Element) reqElem.clone();
              }
            }

            totalUpdated = updateTransaction(transRequest, metadata, context, toIndex);
          }
          // Delete
          else {
            totalDeleted = deleteTransaction(transRequest, context);
          }
        }
      }
    } catch (Exception e) {
      Log.error(Geonet.CSW, "Cannot process transaction");
      Log.error(Geonet.CSW, " (C) StackTrace\n" + Util.getStackTrace(e));

      throw new NoApplicableCodeEx("Cannot process transaction: " + e.getMessage());
    } finally {
      try {
        dataMan.indexInThreadPool(context, new ArrayList<String>(toIndex), null);
      } catch (SQLException e) {
        Log.error(Geonet.CSW, "cannot index");
        Log.error(Geonet.CSW, " (C) StackTrace\n" + Util.getStackTrace(e));
      }
      getResponseResult(request, response, strFileIds, totalInserted, totalUpdated, totalDeleted);
    }

    return response;
  }
Exemplo n.º 8
0
  public Element execute(LocalServiceRequest request) throws Exception {
    ServiceContext context =
        new ServiceContext(
            request.getService(),
            getApplicationContext(),
            getXmlCacheManager(),
            getMonitorManager(),
            getProviderManager(),
            getSerialFactory(),
            getProfileManager(),
            htContexts) {
          /* This override causes database connections to be consumed.....
             Comment out for now. sppigot May, 2014
          public ResourceManager getResourceManager() {
          	return new ResourceManager(getMonitorManager(), getProviderManager()) {
          		@Override
          		public synchronized void abort() throws Exception {
          		}
          		@Override
          		public synchronized void close() throws Exception {
          		}
          		@Override
          		public synchronized void close(String name, Object resource)
          				throws Exception {
          		}
          		@Override
          		public synchronized void abort(String name, Object resource)
          				throws Exception {
          		}
          		@Override
          		protected void openMetrics(Object resource) {
          		}
          		@Override
          		protected void closeMetrics(Object resource) {
          		}
          	};
          }
          */
        };

    UserSession session = userSession;
    if (userSession == null) {
      session = new UserSession();
    }

    try {
      servlet.getEngine().getServiceManager().dispatch(request, session, context);
    } catch (Exception e) {
      Log.error(Log.XLINK_PROCESSOR, "Failed to parse result xml" + request.getService());
      throw new ServiceExecutionFailedException(request.getService(), e);
    } finally {
      // set old context back as thread local
      setAsThreadLocal();
    }
    try {
      return request.getResult();
    } catch (Exception e) {
      Log.error(
          Log.XLINK_PROCESSOR,
          "Failed to parse result xml from service:"
              + request.getService()
              + "\n"
              + request.getResultString());
      throw new ServiceExecutionFailedException(request.getService(), e);
    }
  }