// Add wordnet test ?
  public static String getSecondaryEntity(String title) {
    String potentialEntity = null;

    // e.g. National_Party_(South_Africa)
    if (title.contains("(") && title.endsWith(")")) {
      potentialEntity = StringUtils.substringBetween(title, "(", ")");
      String[] parts = potentialEntity.split(",");

      // e.g. National_Party_(UK,_1976)
      if (parts.length > 1 && StringUtils.containsOnly(parts[1], "_0123456789")) {
        potentialEntity = parts[0];
      }
    }

    // e.g. Chicago,_Illinois
    else if (title.contains(",")) {
      potentialEntity = StringUtils.substringAfterLast(title, ",");
    }

    // e.g. New_Progressive_Party_of_Puerto_Rico
    // Might need to be careful
    else if (title.contains("of")) {
      potentialEntity = StringUtils.substringAfterLast(title, "of");
      if (title.startsWith("List_of")) {
        String[] tokens = potentialEntity.split("_");
        int capPos = 0;
        StringBuilder sb = new StringBuilder();
        while (capPos < tokens.length
            && (StringUtils.isEmpty(tokens[capPos])
                || WordFeatures.isCapitalized(tokens[capPos]))) {
          sb.append(tokens[capPos]).append('_');
          capPos++;
        }
        potentialEntity = sb.toString();
      }
    }

    // Removes extra chars
    if (potentialEntity != null)
      potentialEntity = potentialEntity.replace('_', ' ').trim().replace(' ', '_');

    try {
      if (wiki == null || wiki.getTitleIdOf(potentialEntity) >= 0) return potentialEntity;
    } catch (Exception e) {
    }

    return null;
  }
 /**
  * Computes the best file to save the response to the given URL.
  *
  * @param url the requested URL
  * @param extension the preferred extension
  * @return the file to create
  * @throws IOException if a problem occurs creating the file
  */
 private File createFile(final URL url, final String extension) throws IOException {
   String name = url.getPath().replaceFirst("/$", "").replaceAll(".*/", "");
   name = StringUtils.substringBefore(name, "?"); // remove query
   name = StringUtils.substringBefore(name, ";"); // remove additional info
   name = StringUtils.substring(name, 0, 30); // avoid exceptions due to too long file names
   if (!name.endsWith(extension)) {
     name += extension;
   }
   int counter = 0;
   while (true) {
     final String fileName;
     if (counter != 0) {
       fileName =
           StringUtils.substringBeforeLast(name, ".")
               + "_"
               + counter
               + "."
               + StringUtils.substringAfterLast(name, ".");
     } else {
       fileName = name;
     }
     final File f = new File(reportFolder_, fileName);
     if (f.createNewFile()) {
       return f;
     }
     counter++;
   }
 }
  public void index(final Entity entity, final Tenant tenant) throws SearchEngineException {
    try {
      Map<String, Object> source = entityIndexDocumentPurveyor.purveyDocument(entity, tenant);

      if (source.keySet().size() > 0) {
        String entityName =
            StringUtils.substringAfterLast(entity.getClass().getName(), ".").toLowerCase();

        this.logger.debug("Indexing {} with id {}...", entityName, entity.getId());

        IndexRequestBuilder builder =
            this.client
                .prepareIndex("entities", entityName, entity.getId().toString())
                .setSource(source);

        if (tenant != null && !Tenant.class.isAssignableFrom(entity.getClass())) {
          builder.setParent(tenant.getId().toString());
        }

        IndexResponse response = builder.execute().actionGet();
        this.logger.debug("" + response.getType());
      }
    } catch (Exception e) {
      throw new SearchEngineException("Failed to index entity", e);
    }
  }
Example #4
0
  @Override
  public FlowSnippetDTO instantiateTemplate(
      String groupId, Double originX, Double originY, String templateId, String idGenerationSeed) {
    ProcessGroup group = locateProcessGroup(flowController, groupId);

    // get the template id and find the template
    Template template = getTemplate(templateId);

    // ensure the template could be found
    if (template == null) {
      throw new ResourceNotFoundException(
          String.format("Unable to locate template with id '%s'.", templateId));
    }

    try {
      // copy the template which pre-processes all ids
      TemplateDTO templateDetails = template.getDetails();
      FlowSnippetDTO snippet =
          snippetUtils.copy(templateDetails.getSnippet(), group, idGenerationSeed);

      // calculate scaling factors based on the template encoding version
      // attempt to parse the encoding version
      final FlowEncodingVersion templateEncodingVersion =
          FlowEncodingVersion.parse(templateDetails.getEncodingVersion());
      // get the major version, or 0 if no version could be parsed
      int templateEncodingMajorVersion =
          templateEncodingVersion != null ? templateEncodingVersion.getMajorVersion() : 0;
      // based on the major version < 1, use the default scaling factors.  Otherwise, don't scale
      // (use factor of 1.0)
      double factorX =
          templateEncodingMajorVersion < 1 ? FlowController.DEFAULT_POSITION_SCALE_FACTOR_X : 1.0;
      double factorY =
          templateEncodingMajorVersion < 1 ? FlowController.DEFAULT_POSITION_SCALE_FACTOR_Y : 1.0;

      // reposition and scale the template contents
      org.apache.nifi.util.SnippetUtils.moveAndScaleSnippet(
          snippet, originX, originY, factorX, factorY);

      // find all the child process groups in each process group in the top level of this snippet
      final List<ProcessGroupDTO> childProcessGroups =
          org.apache.nifi.util.SnippetUtils.findAllProcessGroups(snippet);
      // scale (but don't reposition) child process groups
      childProcessGroups
          .stream()
          .forEach(
              processGroup ->
                  org.apache.nifi.util.SnippetUtils.scaleSnippet(
                      processGroup.getContents(), factorX, factorY));

      // instantiate the template into this group
      flowController.instantiateSnippet(group, snippet);

      return snippet;
    } catch (ProcessorInstantiationException pie) {
      throw new NiFiCoreException(
          String.format(
              "Unable to instantiate template because processor type '%s' is unknown to this NiFi.",
              StringUtils.substringAfterLast(pie.getMessage(), ".")));
    }
  }
  /**
   * Extracts the username from the specified DN. If the username cannot be extracted because the CN
   * is in an unrecognized format, the entire CN is returned. If the CN cannot be extracted because
   * the DN is in an unrecognized format, the entire DN is returned.
   *
   * @param dn the dn to extract the username from
   * @return the exatracted username
   */
  public static String extractUsername(String dn) {
    String username = dn;
    String cn = "";

    // ensure the dn is specified
    if (StringUtils.isNotBlank(dn)) {

      // attempt to locate the cn
      if (dn.startsWith("CN=")) {
        cn = StringUtils.substringBetween(dn, "CN=", ",");
      } else if (dn.startsWith("/CN=")) {
        cn = StringUtils.substringBetween(dn, "CN=", "/");
      } else if (dn.startsWith("C=") || dn.startsWith("/C=")) {
        cn = StringUtils.substringAfter(dn, "CN=");
      } else if (dn.startsWith("/") && StringUtils.contains(dn, "CN=")) {
        cn = StringUtils.substringAfter(dn, "CN=");
      }

      // attempt to get the username from the cn
      if (StringUtils.isNotBlank(cn)) {
        if (cn.endsWith(")")) {
          username = StringUtils.substringBetween(cn, "(", ")");
        } else if (cn.contains(" ")) {
          username = StringUtils.substringAfterLast(cn, " ");
        } else {
          username = cn;
        }
      }
    }

    return username;
  }
Example #6
0
  @Override
  public FlowSnippetDTO instantiateTemplate(
      String groupId, Double originX, Double originY, String templateId) {
    ProcessGroup group = locateProcessGroup(flowController, groupId);

    // get the template id and find the template
    Template template = flowController.getTemplate(templateId);

    // ensure the template could be found
    if (template == null) {
      throw new ResourceNotFoundException(
          String.format("Unable to locate template with id '%s'.", templateId));
    }

    try {
      // copy the template which pre-processes all ids
      TemplateDTO templateDetails = template.getDetails();
      FlowSnippetDTO snippet = snippetUtils.copy(templateDetails.getSnippet(), group);

      // reposition the template contents
      org.apache.nifi.util.SnippetUtils.moveSnippet(snippet, originX, originY);

      // instantiate the template into this group
      flowController.instantiateSnippet(group, snippet);

      return snippet;
    } catch (ProcessorInstantiationException pie) {
      throw new NiFiCoreException(
          String.format(
              "Unable to instantiate template because processor type '%s' is unknown to this NiFi.",
              StringUtils.substringAfterLast(pie.getMessage(), ".")));
    }
  }
Example #7
0
  /** 创建/更新/删除任务. */
  @Test
  @Category(Smoke.class)
  public void createUpdateAndDeleteTask() {

    // create
    Task task = TaskData.randomTask();

    URI createdTaskUri = restTemplate.postForLocation(resourceUrl, task);
    System.out.println(createdTaskUri.toString());
    Task createdTask = restTemplate.getForObject(createdTaskUri, Task.class);
    assertThat(createdTask.getTitle()).isEqualTo(task.getTitle());

    // update
    String id = StringUtils.substringAfterLast(createdTaskUri.toString(), "/");
    task.setId(new Long(id));
    task.setTitle(TaskData.randomTitle());

    restTemplate.put(createdTaskUri, task);

    Task updatedTask = restTemplate.getForObject(createdTaskUri, Task.class);
    assertThat(updatedTask.getTitle()).isEqualTo(task.getTitle());

    // delete
    restTemplate.delete(createdTaskUri);

    try {
      restTemplate.getForObject(createdTaskUri, Task.class);
      fail("Get should fail while feth a deleted task");
    } catch (HttpStatusCodeException e) {
      assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
    }
  }
Example #8
0
  @Override
  public boolean move(FtpFile target) {
    try (Tx tx = StructrApp.getInstance().tx()) {

      logger.log(Level.INFO, "move()");

      final AbstractStructrFtpFile targetFile = (AbstractStructrFtpFile) target;
      final String path = targetFile instanceof StructrFtpFile ? "/" : targetFile.getAbsolutePath();

      try {

        if (!("/".equals(path))) {
          final String newName =
              path.contains("/") ? StringUtils.substringAfterLast(path, "/") : path;
          setProperty(AbstractNode.name, newName);
        }

      } catch (FrameworkException ex) {
        logger.log(Level.SEVERE, "Could not move ftp file", ex);
        return false;
      }

      tx.success();

      return true;
    } catch (FrameworkException ex) {
      logger.log(Level.SEVERE, null, ex);
    }

    return false;
  }
 @Override
 public Negotiator<?> findNegotiator(
     HttpServletRequest req, NegotiatingView view, ViewNegotiatorRegistry viewNegotiatorRegistry) {
   String requestUri = req.getRequestURI();
   String extension = StringUtils.trimToEmpty(StringUtils.substringAfterLast(requestUri, "."));
   String mimeType = MimeTypes.lookupMimeType(extension);
   return viewNegotiatorRegistry.getNegotiator(mimeType);
 }
Example #10
0
 @Override
 public String getProductVersion() {
   return getBrandingPlugins()
       .stream()
       .map(plugin -> StringUtils.substringAfterLast(plugin.getProductName(), " "))
       .filter(Objects::nonNull)
       .findFirst()
       .orElse("");
 }
Example #11
0
 @Override
 @Nullable
 public String getTrackableCodeFromUrl(@NonNull final String url) {
   final String geocode = StringUtils.upperCase(StringUtils.substringAfterLast(url, "swaggie/"));
   if (canHandleTrackable(geocode)) {
     return geocode;
   }
   return null;
 }
Example #12
0
 public MultipartFile mockImage(String path) {
   try (InputStream in = getClass().getResourceAsStream(path)) {
     byte[] content = IOUtils.toByteArray(in);
     return new MockMultipartFile(
         StringUtils.substringAfterLast(path, "/"), path, "image/png", content);
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   }
 }
 public static String getSuffix(File file) throws IOException {
   if (file == null) {
     Throw.ioe(TAG, "File is null.");
     return null; // To make static analysis happy
   }
   String path = file.getAbsolutePath();
   String suffix = "." + StringUtils.substringAfterLast(path, ".");
   checkValidSuffix(suffix);
   return suffix;
 }
  /**
   * 处理其他方法
   *
   * @throws Exception
   * @throws
   * @throws InstantiationException
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  protected boolean handleOther(
      HttpServletRequest request,
      Set<SearchFilter> filterSet,
      Method method,
      DataControl dataControl,
      Module module)
      throws Exception {

    String[] ids = null;
    if (method.getName().endsWith(MANY_METHOD_SUFFIX)) { // 多对象操作方法
      ids = request.getParameterValues(MANY_KEY);
      if (ids != null) {
        filterSet.add(new SearchFilter("id", Operator.IN, ids));
      }
    } else {
      String id = request.getParameter("id");
      if (id != null) {
        filterSet.add(new SearchFilter("id", Operator.EQ, id));
      } else {
        // 截取类似/update/{id}的id
        String uri = request.getRequestURI();
        String tmp = StringUtils.substringAfterLast(uri, "/");
        Long longId = NumberUtils.toLong(tmp);
        if (longId != 0L) {
          filterSet.add(new SearchFilter("id", Operator.EQ, longId));
        }
      }
    }

    Object clazz = Class.forName(module.getClassName()).newInstance();
    // Object clazz = null;
    Specification spec = DynamicSpecifications.bySearchFilter(request, clazz.getClass(), filterSet);

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery criteriaQuery = builder.createQuery(clazz.getClass());
    Root root = criteriaQuery.from(clazz.getClass());

    Predicate predicate = spec.toPredicate(root, criteriaQuery, builder);
    criteriaQuery.where(predicate);

    List<Object> objects = em.createQuery(criteriaQuery).getResultList();
    if (ids != null) {
      if (objects.size() == ids.length) {
        return true;
      }
    } else {
      if (objects.size() > 0) {
        return true;
      }
    }

    return false;
  }
Example #15
0
 /**
  * Get the guessed file extension of an URL. A file extension can contain up-to 4 characters in
  * addition to the dot.
  *
  * @param url the relative or absolute URL
  * @return the file extension, including the leading dot, or the empty string if none could be
  *     determined
  */
 static String getExtension(final String url) {
   final String urlExt;
   if (url.startsWith("data:")) {
     // "data:image/png;base64,i53…" -> ".png"
     urlExt = StringUtils.substringAfter(StringUtils.substringBefore(url, ";"), "/");
   } else {
     // "http://example.com/foo/bar.png" -> ".png"
     urlExt = StringUtils.substringAfterLast(url, ".");
   }
   return urlExt.length() >= 1 && urlExt.length() <= 4 ? "." + urlExt : "";
 }
 /**
  * *
  * <li><b>Substring/Left/Right/Mid</b> - null-safe substring extractions
  * <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b> - substring extraction relative to
  *     other strings
  */
 @Test
 public void testSubstringLeftStringUtils() {
   System.out.println(strOne + ":" + strOne.length());
   System.out.println(StringUtils.substring(strOne, 3));
   System.out.println(StringUtils.substring(strOne, 3, 7));
   System.out.println(StringUtils.substringAfter(strOne, " "));
   System.out.println(StringUtils.substringAfterLast(strOne, " "));
   System.out.println(StringUtils.substringBefore(strOne, " "));
   System.out.println(StringUtils.substringBeforeLast(strOne, " "));
   System.out.println(StringUtils.substringBetween(strOne, "the", "not"));
 }
Example #17
0
 @Override
 public PropertyInterface get(String name) {
   PropertyInterface property = safeget(name);
   if (property == null) {
     // In previous versions the property name was the full Java class name of the property class
     // implementation.
     // Extract the actual property name (the hint used to lookup the property class provider) by
     // removing the
     // Java package prefix and the Class suffix.
     property = safeget(StringUtils.removeEnd(StringUtils.substringAfterLast(name, "."), "Class"));
   }
   return property;
 }
  /** Logs the event type and some information about the associated proposal person bio */
  protected void logEvent() {
    StringBuffer logMessage =
        new StringBuffer(StringUtils.substringAfterLast(this.getClass().getName(), "."));
    logMessage.append(" with ");

    // vary logging detail as needed
    if (getProposalPersonBiography() == null) {
      logMessage.append("null proposalPersonBiography");
    } else {
      logMessage.append(getProposalPersonBiography().toString());
    }

    LOG.debug(logMessage);
  }
  @Override
  protected void logEvent() {
    StringBuffer logMessage =
        new StringBuffer(StringUtils.substringAfterLast(this.getClass().getName(), "."));
    logMessage.append(" with ");

    // vary logging detail as needed
    if (this.actionBean == null) {
      logMessage.append("null actionBean");
    } else {
      logMessage.append(actionBean.toString());
    }

    LOG.debug(logMessage);
  }
Example #20
0
 private void createThumbnail(String idImage, Integer size, String prefix) {
   File image = Paths.get(getRoot()).resolve(idImage).toFile();
   BufferedImage i = null;
   try {
     i = ImageIO.read(image);
     BufferedImage thumbnail = i;
     if (i.getWidth() > size
         || i.getHeight() > size) { // dont resize if image is smaller that max_size
       thumbnail = Scalr.resize(i, Method.QUALITY, size, size);
     }
     File outputfile = Paths.get(getRoot()).resolve(prefix.concat(idImage)).toFile();
     ImageIO.write(thumbnail, StringUtils.substringAfterLast(idImage, "."), outputfile);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #21
0
  /** Logs the event type and some information about the associated special review */
  protected void logEvent() {
    if (LOG.isDebugEnabled()) {
      StringBuilder logMessage =
          new StringBuilder(StringUtils.substringAfterLast(this.getClass().getName(), "."));
      logMessage.append(" with ");

      // vary logging detail as needed
      if (getAwardFandaRate() == null) {
        logMessage.append("null award F and a Rate Event");
      } else {
        logMessage.append(getAwardFandaRate().toString());
      }

      LOG.debug(logMessage);
    }
  }
  @SuppressWarnings("unchecked")
  List<String> getListOfPlayerIDs() throws Exception {
    final List<String> playerList = new ArrayList<String>();

    final HtmlPage page = (HtmlPage) this.webClient.getPage(STATS_PAGE_2012);
    final HtmlTable battingStatsTable = (HtmlTable) page.getElementById(BATTING_TABLE_ID);

    final List<HtmlTableRow> statRows =
        (List<HtmlTableRow>) battingStatsTable.getByXPath("//tr[contains(@class, 'full_table')]");
    for (HtmlTableRow row : statRows) {
      final DomNodeList<HtmlElement> dataCells =
          (DomNodeList<HtmlElement>) row.getElementsByTagName("td");
      final HtmlAnchor playerLink = (HtmlAnchor) dataCells.get(1).getElementsByTagName("a").get(0);
      playerList.add(
          StringUtils.substringAfterLast(playerLink.getHrefAttribute().replace(".shtml", ""), "/"));
    }

    return playerList;
  }
Example #23
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String requestPath =
        request
            .getRequestURI()
            .replaceFirst("^" + request.getContextPath() + request.getServletPath() + "/", "");

    if (!requestPath.endsWith("/")) {
      String fileName =
          (requestPath.contains("/"))
              ? StringUtils.substringAfterLast(requestPath, "/")
              : requestPath;
      String mimeType = servletContext.getMimeType(fileName);
      if (mimeType != null) {
        response.setHeader(CONTENT_TYPE, mimeType);
      }
    }

    ThreadSafeStaticBRJSAccessor.aquireModel();
    UrlContentAccessor contentAccessor =
        new ServletContentAccessor(app, servletContext, request, response);
    try (ResponseContent content =
        app.requestHandler()
            .handleLogicalRequest(requestPath, contentAccessor, RequestMode.Dev); ) {
      if (!response
          .isCommitted()) { // check the ServletContentAccessor hasnt been used to handle a request
                            // and sent headers
        content.write(response.getOutputStream());
      }
    } catch (MalformedRequestException e) {
      response.sendError(400, e.getMessage());
    } catch (ResourceNotFoundException e) {
      response.sendError(404, e.getMessage());
    } catch (ContentProcessingException e) {
      response.sendError(500, e.getMessage());
    } catch (ModelOperationException e) {
      throw new ServletException(e);
    } finally {
      ThreadSafeStaticBRJSAccessor.releaseModel();
    }
  }
  private void processBinding(
      EnvironmentReferenceService envRefService,
      JNDIResourceService jndiResourceService,
      Set<ProjectModel> applications,
      Element resourceRef,
      String tagName) {
    String href = $(resourceRef).child(tagName).attr("href");
    String resourceId = StringUtils.substringAfterLast(href, "ejb-jar.xml#");
    String jndiLocation = $(resourceRef).attr("jndiName");

    if (StringUtils.isNotBlank(jndiLocation) && StringUtils.isNotBlank(resourceId)) {
      JNDIResourceModel resource = jndiResourceService.createUnique(applications, jndiLocation);
      LOG.info("JNDI Name: " + jndiLocation + " to Resource: " + resourceId);
      // now, look up the resource which is resolved by DiscoverEjbConfigurationXmlRuleProvider
      for (EnvironmentReferenceModel ref :
          envRefService.findAllByProperty(EnvironmentReferenceModel.REFERENCE_ID, resourceId)) {
        envRefService.associateEnvironmentToJndi(resource, ref);
      }
    }
  }
Example #25
0
  /**
   * Transforms the given image (i.e. shrinks the image and changes its quality) before it is
   * downloaded.
   *
   * @param image the image to be downloaded
   * @param width the desired image width; this value is taken into account only if it is greater
   *     than zero and less than the current image width
   * @param height the desired image height; this value is taken into account only if it is greater
   *     than zero and less than the current image height
   * @param quality the desired compression quality
   * @param context the XWiki context
   * @return the transformed image
   * @throws Exception if transforming the image fails
   */
  private XWikiAttachment downloadImage(
      XWikiAttachment image, int width, int height, float quality, XWikiContext context)
      throws Exception {
    initCache(context);

    boolean keepAspectRatio = Boolean.valueOf(context.getRequest().getParameter("keepAspectRatio"));

    XWikiAttachment thumbnail =
        (this.imageCache == null)
            ? shrinkImage(image, width, height, keepAspectRatio, quality, context)
            : downloadImageFromCache(image, width, height, keepAspectRatio, quality, context);

    // If the image has been transformed, update the file name extension to match the image format.
    String fileName = thumbnail.getFilename();
    String extension =
        StringUtils.lowerCase(StringUtils.substringAfterLast(fileName, String.valueOf('.')));
    if (thumbnail != image && !Arrays.asList("jpeg", "jpg", "png").contains(extension)) {
      // The scaled image is PNG, so correct the extension in order to output the correct MIME type.
      thumbnail.setFilename(StringUtils.substringBeforeLast(fileName, ".") + ".png");
    }
    return thumbnail;
  }
Example #26
0
 public static void main(String[] args) {
   String path = Take.class.getResource("/").getPath();
   String proFile = path + "file.json";
   final List<String> urls = new ArrayList<String>();
   Files.readLine(
       Files.findFile(proFile),
       new Callback<String>() {
         @Override
         public void invoke(String str) {
           urls.add(str);
         }
       });
   for (String url : urls) {
     if (StringUtils.isBlank(url)) {
       continue;
     }
     Response req = Http.get(url);
     String savePath = path + "/temp/" + StringUtils.substringAfterLast(url, "/");
     savePath = StringUtils.substringBefore(savePath, "?");
     Files.write(savePath, req.getStream());
     System.out.println("save Path:" + savePath);
   }
 }
  @Override
  public void perform(GraphRewrite event, EvaluationContext context, XmlFileModel payload) {
    EnvironmentReferenceService envRefService =
        new EnvironmentReferenceService(event.getGraphContext());

    XmlFileService xmlFileService = new XmlFileService(event.getGraphContext());
    JNDIResourceService jndiResourceService = new JNDIResourceService(event.getGraphContext());
    JmsDestinationService jmsDestinationService =
        new JmsDestinationService(event.getGraphContext());
    GraphService<EjbSessionBeanModel> ejbSessionBeanService =
        new GraphService<>(event.getGraphContext(), EjbSessionBeanModel.class);
    GraphService<EjbMessageDrivenModel> mdbService =
        new GraphService<>(event.getGraphContext(), EjbMessageDrivenModel.class);

    ClassificationService classificationService =
        new ClassificationService(event.getGraphContext());
    ClassificationModel classification =
        classificationService.attachClassification(
            context,
            payload,
            "WebSphere EJB Binding",
            "WebSphere Enterprise Java Bean Binding XML Descriptor");
    classification.setEffort(1);

    TechnologyTagService technologyTagService = new TechnologyTagService(event.getGraphContext());
    technologyTagService.addTagToFileModel(payload, "WebSphere EJB", TechnologyTagLevel.IMPORTANT);

    Document doc = xmlFileService.loadDocumentQuiet(context, payload);

    if (doc == null) {
      return;
    }

    VendorSpecificationExtensionService vendorSpecificationService =
        new VendorSpecificationExtensionService(event.getGraphContext());
    // mark as vendor extension; create reference to ejb-jar.xml
    vendorSpecificationService.associateAsVendorExtension(payload, "ejb-jar.xml");

    Set<ProjectModel> applications =
        ProjectTraversalCache.getApplicationsForProject(
            event.getGraphContext(), payload.getProjectModel());

    // register beans to JNDI
    for (Element resourceRef : $(doc).find("ejbBindings").get()) {
      String href = $(resourceRef).child("enterpriseBean").attr("href");
      String resourceId = StringUtils.substringAfterLast(href, "ejb-jar.xml#");
      String jndiLocation = $(resourceRef).attr("jndiName");

      // determine type:
      String type = $(resourceRef).child("enterpriseBean").attr("type");

      LOG.info("Type: " + type);

      if (StringUtils.isNotBlank(jndiLocation) && StringUtils.isNotBlank(resourceId)) {
        JNDIResourceModel resource = jndiResourceService.createUnique(applications, jndiLocation);
        LOG.info("JNDI Name: " + jndiLocation + " to Resource: " + resourceId);
        // now, look up the resource which is resolved by DiscoverEjbConfigurationXmlRuleProvider
        for (EnvironmentReferenceModel ref :
            envRefService.findAllByProperty(EnvironmentReferenceModel.REFERENCE_ID, resourceId)) {
          envRefService.associateEnvironmentToJndi(resource, ref);
        }

        for (EjbSessionBeanModel ejb :
            ejbSessionBeanService.findAllByProperty(EjbSessionBeanModel.EJB_ID, resourceId)) {
          ejb.setGlobalJndiReference(resource);
        }
      }
    }

    // register beans to JNDI
    for (Element resourceRef : $(doc).find("resRefBindings").get()) {
      processBinding(
          envRefService, jndiResourceService, applications, resourceRef, "bindingResourceRef");
    }
    for (Element resourceRef : $(doc).find("ejbRefBindings").get()) {
      processBinding(
          envRefService, jndiResourceService, applications, resourceRef, "bindingEjbRef");
    }
    for (Element resourceRef : $(doc).find("messageDestinationRefBindings").get()) {
      processBinding(
          envRefService,
          jndiResourceService,
          applications,
          resourceRef,
          "bindingMessageDestinationRef");
    }

    // Bind MDBs to Destinations
    for (Element resourceRef : $(doc).find("messageDestinationRefBindings").get()) {
      String jndiLocation = $(resourceRef).attr("jndiName");

      // get the parent, as that has the reference to the MDB...
      String mdbRef = $(resourceRef).siblings("enterpriseBean").attr("href");
      String mdbId = StringUtils.substringAfterLast(mdbRef, "ejb-jar.xml#");

      if (StringUtils.isNotBlank(mdbId)) {
        for (EjbMessageDrivenModel mdb :
            mdbService.findAllByProperty(EjbMessageDrivenModel.EJB_ID, mdbId)) {
          String destination = jndiLocation;
          if (StringUtils.isNotBlank(destination)) {
            JmsDestinationModel jndiRef =
                jmsDestinationService.createUnique(applications, destination);
            mdb.setDestination(jndiRef);
          }
        }
      }
    }
  }
Example #28
0
 private static Long time(String value) {
   return Long.valueOf(StringUtils.substringAfterLast(value, "]"));
 }
  @SuppressWarnings({"resource", "rawtypes", "unchecked"})
  public static void main(String[] args) throws Exception {
    Configuration cfg = new Configuration();
    // 设置FreeMarker的模版文件位置
    cfg.setClassForTemplateLoading(
        SourceCodeFrameworkBuilder.class, "/lab/s2jh/tool/builder/freemarker");
    cfg.setDefaultEncoding("UTF-8");
    String rootPath = args[0];

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

    String entityListFile = rootPath + "entity_list.properties";
    BufferedReader reader = new BufferedReader(new FileReader(entityListFile));
    String line;
    while ((line = reader.readLine()) != null) {
      if (StringUtils.isNotBlank(line) && !line.startsWith("#")) {
        entityNames.add(line);
      }
    }

    new File(rootPath + "\\codes").mkdir();
    new File(rootPath + "\\codes\\integrate").mkdir();
    new File(rootPath + "\\codes\\standalone").mkdir();

    for (String entityName : entityNames) {

      String integrateRootPath = rootPath + "\\codes\\integrate\\";
      String standaloneRootPath = rootPath + "\\codes\\standalone\\";

      String rootPackage = StringUtils.substringBetween(entityName, "[", "]");
      String rootPackagePath = StringUtils.replace(rootPackage, ".", "\\");

      String className = StringUtils.substringAfterLast(entityName, ".");
      String classFullName =
          StringUtils.replaceEach(entityName, new String[] {"[", "]"}, new String[] {"", ""});

      String modelName = StringUtils.substringBetween(entityName, "].", ".entity");
      String modelPath = StringUtils.replace(modelName, ".", "/");
      modelPath = "/" + modelPath;
      String modelPackagePath = StringUtils.replace(modelName, ".", "\\");
      modelPackagePath = "\\" + modelPackagePath;

      Map<String, Object> root = new HashMap<String, Object>();
      String nameField = propertyToField(StringUtils.uncapitalize(className)).toLowerCase();
      root.put("model_name", modelName);
      root.put("model_path", modelPath);
      root.put("entity_name", className);
      root.put("entity_name_uncapitalize", StringUtils.uncapitalize(className));
      root.put("entity_name_field", nameField);
      root.put("root_package", rootPackage + "." + modelName);
      root.put("action_package", rootPackage);
      root.put("table_name", "T_TODO_" + className.toUpperCase());
      root.put("base", "${base}");
      Class entityClass = Class.forName(classFullName);
      root.put("id_type", entityClass.getMethod("getId").getReturnType().getSimpleName());
      MetaData classEntityComment = (MetaData) entityClass.getAnnotation(MetaData.class);
      if (classEntityComment != null) {
        root.put("model_title", classEntityComment.value());
      } else {
        root.put("model_title", entityName);
      }
      debug("Entity Data Map=" + root);

      Set<Field> fields = new HashSet<Field>();

      Field[] curfields = entityClass.getDeclaredFields();
      for (Field field : curfields) {
        fields.add(field);
      }

      Class superClass = entityClass.getSuperclass();
      while (superClass != null && !superClass.equals(BaseEntity.class)) {
        Field[] superfields = superClass.getDeclaredFields();
        for (Field field : superfields) {
          fields.add(field);
        }
        superClass = superClass.getSuperclass();
      }

      // 定义用于OneToOne关联对象的Fetch参数
      Map<String, String> fetchJoinFields = Maps.newHashMap();
      List<EntityCodeField> entityFields = new ArrayList<EntityCodeField>();
      int cnt = 1;
      for (Field field : fields) {
        if ((field.getModifiers() & Modifier.FINAL) != 0 || "id".equals(field.getName())) {
          continue;
        }
        debug(" - Field=" + field);
        Class fieldType = field.getType();

        EntityCodeField entityCodeField = null;
        if (fieldType.isEnum()) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);
          entityCodeField.setListWidth(80);
          entityCodeField.setListAlign("center");
        } else if (fieldType == Boolean.class) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);
          entityCodeField.setListWidth(60);
          entityCodeField.setListAlign("center");
        } else if (PersistableEntity.class.isAssignableFrom(fieldType)) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setFieldType("Entity");

        } else if (Number.class.isAssignableFrom(fieldType)) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);
          entityCodeField.setListWidth(60);
          entityCodeField.setListAlign("right");
        } else if (fieldType == String.class) {
          entityCodeField = new EntityCodeField();

          // 根据Hibernate注解的字符串类型和长度设定是否列表显示
          Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName()));
          Column fieldColumn = getMethod.getAnnotation(Column.class);
          if (fieldColumn != null) {
            int length = fieldColumn.length();
            if (length > 255) {
              entityCodeField.setList(false);
              entityCodeField.setListWidth(length);
            }
          }
          Lob fieldLob = getMethod.getAnnotation(Lob.class);
          if (fieldLob != null) {
            entityCodeField.setList(false);
            entityCodeField.setListWidth(Integer.MAX_VALUE);
          }
        } else if (fieldType == Date.class) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);

          // 根据Json注解设定合理的列宽
          entityCodeField.setListWidth(120);
          Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName()));
          JsonSerialize fieldJsonSerialize = getMethod.getAnnotation(JsonSerialize.class);
          if (fieldJsonSerialize != null) {
            if (DateJsonSerializer.class.equals(fieldJsonSerialize.using())) {
              entityCodeField.setListWidth(80);
            }
          }
          entityCodeField.setListAlign("center");
        }

        if (entityCodeField != null) {
          if (fieldType.isEnum()) {
            entityCodeField.setEnumField(true);
          }
          if (StringUtils.isBlank(entityCodeField.getFieldType())) {
            entityCodeField.setFieldType(fieldType.getSimpleName());
          }
          entityCodeField.setFieldName(field.getName());
          EntityAutoCode entityAutoCode = field.getAnnotation(EntityAutoCode.class);
          if (entityAutoCode != null) {
            entityCodeField.setListHidden(entityAutoCode.listHidden());
            entityCodeField.setEdit(entityAutoCode.edit());
            entityCodeField.setList(entityAutoCode.listHidden() || entityAutoCode.listShow());
            entityCodeField.setOrder(entityAutoCode.order());
          } else {
            entityCodeField.setTitle(field.getName());
            entityCodeField.setOrder(cnt++);
          }

          MetaData entityMetaData = field.getAnnotation(MetaData.class);
          if (entityMetaData != null) {
            entityCodeField.setTitle(entityMetaData.value());
          }

          Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName()));
          JsonProperty fieldJsonProperty = getMethod.getAnnotation(JsonProperty.class);
          if (fieldJsonProperty != null) {
            entityCodeField.setList(true);
          }

          if (entityCodeField.getList() || entityCodeField.getListHidden()) {
            JoinColumn fieldJoinColumn = getMethod.getAnnotation(JoinColumn.class);
            if (fieldJoinColumn != null) {
              if (fieldJoinColumn.nullable() == false) {
                fetchJoinFields.put(field.getName(), "INNER");
              } else {
                fetchJoinFields.put(field.getName(), "LEFT");
              }
            }
          }

          entityFields.add(entityCodeField);
        }
      }
      Collections.sort(entityFields);
      root.put("entityFields", entityFields);
      if (fetchJoinFields.size() > 0) {
        root.put("fetchJoinFields", fetchJoinFields);
      }

      integrateRootPath = integrateRootPath + rootPackagePath + modelPackagePath;
      // process(cfg.getTemplate("Entity.ftl"), root, integrateRootPath + "\\entity\\", className +
      // ".java");
      process(
          cfg.getTemplate("Dao.ftl"), root, integrateRootPath + "\\dao\\", className + "Dao.java");
      process(
          cfg.getTemplate("Service.ftl"),
          root,
          integrateRootPath + "\\service\\",
          className + "Service.java");
      process(
          cfg.getTemplate("Controller.ftl"),
          root,
          integrateRootPath + "\\web\\action\\",
          className + "Controller.java");
      process(
          cfg.getTemplate("Test.ftl"),
          root,
          integrateRootPath + "\\test\\service\\",
          className + "ServiceTest.java");
      process(
          cfg.getTemplate("JSP_Index.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-index.jsp");
      process(
          cfg.getTemplate("JSP_Input_Tabs.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-inputTabs.jsp");
      process(
          cfg.getTemplate("JSP_Input_Basic.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-inputBasic.jsp");
      process(
          cfg.getTemplate("JSP_View_Tabs.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-viewTabs.jsp");
      process(
          cfg.getTemplate("JSP_View_Basic.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-viewBasic.jsp");

      standaloneRootPath =
          standaloneRootPath + rootPackagePath + modelPackagePath + "\\" + className;
      // process(cfg.getTemplate("Entity.ftl"), root, standaloneRootPath + "\\entity\\", className +
      // ".java");
      process(
          cfg.getTemplate("Dao.ftl"), root, standaloneRootPath + "\\dao\\", className + "Dao.java");
      process(
          cfg.getTemplate("Service.ftl"),
          root,
          standaloneRootPath + "\\service\\",
          className + "Service.java");
      process(
          cfg.getTemplate("Controller.ftl"),
          root,
          standaloneRootPath + "\\web\\action\\",
          className + "Controller.java");
      process(
          cfg.getTemplate("Test.ftl"),
          root,
          standaloneRootPath + "\\test\\service\\",
          className + "ServiceTest.java");
      process(
          cfg.getTemplate("JSP_Index.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-index.jsp");
      process(
          cfg.getTemplate("JSP_Input_Tabs.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-inputTabs.jsp");
      process(
          cfg.getTemplate("JSP_Input_Basic.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-inputBasic.jsp");
      process(
          cfg.getTemplate("JSP_View_Tabs.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-viewTabs.jsp");
      process(
          cfg.getTemplate("JSP_View_Basic.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-viewBasic.jsp");
    }
  }
  @Override
  protected void init() throws OAuth2Exception {
    final URI authURI =
        OAuthClientUtils.getAuthorizationURI(
            oauth2GrantServiceURI.toASCIIString(),
            OAuth2Provider.CLIENT_ID,
            OAuth2Provider.REDIRECT_URI,
            null,
            null);

    // Disable automatic redirects handling
    final HttpParams params = new BasicHttpParams();
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    final DefaultHttpClient httpClient = new DefaultHttpClient(params);

    JsonNode oAuthAuthorizationData = null;
    String authenticityCookie = null;
    try {
      // 1. Need to (basic) authenticate against the OAuth2 service
      final HttpGet method = new HttpGet(authURI);
      method.addHeader(
          "Authorization",
          "Basic " + Base64.encodeBase64String("odatajclient:odatajclient".getBytes()));
      final HttpResponse response = httpClient.execute(method);

      // 2. Pull out OAuth2 authorization data and "authenticity" cookie (CXF specific)
      oAuthAuthorizationData = new XmlMapper().readTree(EntityUtils.toString(response.getEntity()));

      final Header setCookieHeader = response.getFirstHeader("Set-Cookie");
      if (setCookieHeader == null) {
        throw new IllegalStateException("OAuth flow is broken");
      }
      authenticityCookie = setCookieHeader.getValue();
    } catch (Exception e) {
      throw new OAuth2Exception(e);
    }

    String code = null;
    try {
      // 3. Submit the HTTP form for allowing access to the application
      final URI location =
          new URIBuilder(oAuthAuthorizationData.get("replyTo").asText())
              .addParameter(
                  "session_authenticity_token",
                  oAuthAuthorizationData.get("authenticityToken").asText())
              .addParameter("client_id", oAuthAuthorizationData.get("clientId").asText())
              .addParameter("redirect_uri", oAuthAuthorizationData.get("redirectUri").asText())
              .addParameter("oauthDecision", "allow")
              .build();
      final HttpGet method = new HttpGet(location);
      method.addHeader(
          "Authorization",
          "Basic " + Base64.encodeBase64String("odatajclient:odatajclient".getBytes()));
      method.addHeader("Cookie", authenticityCookie);

      final HttpResponse response = httpClient.execute(method);

      final Header locationHeader = response.getFirstHeader("Location");
      if (response.getStatusLine().getStatusCode() != 303 || locationHeader == null) {
        throw new IllegalStateException("OAuth flow is broken");
      }

      // 4. Get the authorization code value out of this last redirect
      code = StringUtils.substringAfterLast(locationHeader.getValue(), "=");

      EntityUtils.consumeQuietly(response.getEntity());
    } catch (Exception e) {
      throw new OAuth2Exception(e);
    }

    // 5. Obtain the access token
    try {
      accessToken =
          OAuthClientUtils.getAccessToken(
              getAccessTokenService(), OAUTH2_CONSUMER, new AuthorizationCodeGrant(code));
    } catch (OAuthServiceException e) {
      throw new OAuth2Exception(e);
    }

    if (accessToken == null) {
      throw new OAuth2Exception("No OAuth2 access token");
    }
  }