/**
  * Checks if the identifier is valid on the specified date.
  *
  * @param date the date to check for validity on, null returns true
  * @return true if valid on the specified date
  */
 public boolean isValidOn(LocalDate date) {
   if (date == null) {
     return true;
   }
   LocalDate from =
       Objects.firstNonNull(
           getValidFrom(), LocalDate.of(Year.MIN_YEAR, 1, 1)); // TODO: JSR-310 far past/future
   LocalDate to = Objects.firstNonNull(getValidTo(), LocalDate.of(Year.MAX_YEAR, 12, 31));
   return date.isBefore(from) == false && date.isAfter(to) == false;
 }
Example #2
0
  protected void buildPython(IndentingAppender ia) throws IOException {
    String name = getClass().getSimpleName();

    ia.append("def ").append(name).append("(self");
    ia.incrementIndent().incrementIndent();
    for (Argument arg : _arguments) {
      ia.append(", ").append(arg._name);
      if (!arg._required) ia.append("=None");
    }
    ia.appendln("):");
    ia.decrementIndent().decrementIndent();
    ia.incrementIndent();
    ia.appendln("'''");
    ia.appendln(Objects.firstNonNull(_requestHelp, "MISSING HELP STRING"));

    if (!_arguments.isEmpty()) ia.appendln("Arguments:");
    ia.incrementIndent();
    for (Argument arg : _arguments) {
      ia.append(arg._name).append(" -- ");
      if (arg._required) ia.append("required -- ");
      ia.appendln(arg.queryDescription());
      ia.incrementIndent();
      ia.appendln(Objects.firstNonNull(arg._requestHelp, "MISSING HELP STRING"));
      ia.decrementIndent();
    }
    ia.decrementIndent();
    ia.appendln("'''");
    ia.appendln("pass");
    ia.decrementIndent();
  }
Example #3
0
 public ModMetadata(JsonNode node) {
   Map<JsonStringNode, Object> processedFields =
       Maps.transformValues(node.getFields(), new JsonStringConverter());
   modId = (String) processedFields.get(aStringBuilder("modid"));
   if (Strings.isNullOrEmpty(modId)) {
     FMLLog.log(Level.SEVERE, "Found an invalid mod metadata file - missing modid");
     throw new LoaderException();
   }
   name = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("name")));
   description = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("description")));
   url = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("url")));
   updateUrl = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("updateUrl")));
   logoFile = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("logoFile")));
   version = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("version")));
   credits = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("credits")));
   parent = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("parent")));
   authorList =
       Objects.firstNonNull(
           ((List<String>) processedFields.get(aStringBuilder("authors"))),
           Objects.firstNonNull(
               ((List<String>) processedFields.get(aStringBuilder("authorList"))), authorList));
   requiredMods =
       processReferences(processedFields.get(aStringBuilder("requiredMods")), HashSet.class);
   dependencies =
       processReferences(processedFields.get(aStringBuilder("dependencies")), ArrayList.class);
   dependants =
       processReferences(processedFields.get(aStringBuilder("dependants")), ArrayList.class);
   useDependencyInformation =
       Boolean.parseBoolean(
           Strings.nullToEmpty(
               (String) processedFields.get(aStringBuilder("useDependencyInformation"))));
 }
  @Override
  public Response<Paging<RequirementSolution>> findByRequirementId(
      Long requirementId, String statusArray, Integer pageNo, Integer size) {
    Response<Paging<RequirementSolution>> result = new Response<Paging<RequirementSolution>>();

    if (requirementId == null) {
      log.error("find requirement solutions need requirementId");
      result.setError("solution.requirementId.null");
      return result;
    }

    try {
      Map<String, Object> params = Maps.newHashMap();
      PageInfo pageInfo = new PageInfo(pageNo, Objects.firstNonNull(size, 10));
      params.putAll(pageInfo.toMap());
      params.put(
          "statusArray", statusArray == null ? null : Splitters.COMMA.splitToList(statusArray));
      result.setResult(requirementSolutionDao.findByParams(requirementId, params));
    } catch (Exception e) {
      log.error(
          "find requirement solutions failed, requirementId={}, error code={}",
          requirementId,
          Throwables.getStackTraceAsString(e));
      result.setError("solution.find.failed");
    }

    return result;
  }
  @POST
  @Consumes("application/json")
  public Response post(StaticAnnouncement announcement, @Context UriInfo uriInfo) {
    if (!nodeInfo.getEnvironment().equals(announcement.getEnvironment())) {
      return Response.status(BAD_REQUEST)
          .entity(
              format(
                  "Environment mismatch. Expected: %s, Provided: %s",
                  nodeInfo.getEnvironment(), announcement.getEnvironment()))
          .build();
    }

    Id<Service> id = Id.random();
    String location = Objects.firstNonNull(announcement.getLocation(), "/somewhere/" + id);

    Service service = Service.copyOf(announcement).setId(id).setLocation(location).build();

    store.put(service);

    URI uri =
        UriBuilder.fromUri(uriInfo.getBaseUri())
            .path(StaticAnnouncementResource.class)
            .path("{id}")
            .build(id);
    return Response.created(uri).entity(service).build();
  }
 private String getAnalyzer(final OIndex classIndex) {
   // analyzer is stored only in metadata and there is no way to get default analyzer.. just assume
   // it
   final ODocument metadata = classIndex.getMetadata();
   final String analyzer = metadata != null ? metadata.<String>field(ANALYZER) : null;
   return Objects.firstNonNull(analyzer, StandardAnalyzer.class.getName());
 }
    @Override
    public void allocate(Allocation allocInfo) throws Exception {
      try {
        final VmInstanceLifecycleHelper helper = VmInstanceLifecycleHelpers.get();

        final PrepareNetworkResourcesType request = new PrepareNetworkResourcesType();
        request.setAvailabilityZone(allocInfo.getPartition().getName());
        request.setVpc(
            allocInfo.getSubnet() == null
                ? null
                : CloudMetadatas.toDisplayName().apply(allocInfo.getSubnet().getVpc()));
        request.setSubnet(CloudMetadatas.toDisplayName().apply(allocInfo.getSubnet()));
        request.setFeatures(Lists.<NetworkFeature>newArrayList(new DnsHostNamesFeature()));
        helper.prepareNetworkAllocation(allocInfo, request);
        final PrepareNetworkResourcesResultType result = Networking.getInstance().prepare(request);

        for (final ResourceToken token : allocInfo.getAllocationTokens()) {
          for (final NetworkResource networkResource : result.getResources()) {
            if (token.getInstanceId().equals(networkResource.getOwnerId())) {
              token
                  .getAttribute(NetworkResourceVmInstanceLifecycleHelper.NetworkResourcesKey)
                  .add(networkResource);
            }
          }
        }
      } catch (Exception e) {
        throw Objects.firstNonNull(Exceptions.findCause(e, NotEnoughResourcesException.class), e);
      }
    }
Example #8
0
  @Override
  public List<NiveauEtudeProxy> getNiveauEtudeList(Long filiere, Boolean isSuperUser) {
    if (niveauEtudeMap == null && !niveauEtudeMap.containsKey(filiere)) {
      initNiveauEtudeMap(isSuperUser);
    }

    return Objects.firstNonNull(niveauEtudeMap.get(filiere), new ArrayList<NiveauEtudeProxy>());
  }
  @LoginRequired
  @RequestMapping(value = "/profile", method = RequestMethod.GET)
  @ResponseBody
  public JSONObject getProfile() {

    long userId = HehuaRequestContext.getUserId();
    User user = userManager.getUserById(userId);
    Baby baby = babyService.getBabyByUidxUid(userId);
    Address defaultAddress = addressService.getDefaultAddress(userId);

    Map<Integer, Integer> statuesMap = orderService.getStatusesMap(userId);
    int unpays = Objects.firstNonNull(statuesMap.get(OrdersModel.STATUS_NEW), 0);
    int unrececives = Objects.firstNonNull(statuesMap.get(OrdersModel.STATUS_DELIVERIED), 0);

    return ResponseRender.renderResponse(
        profileRender.renderProfile(user, baby, defaultAddress, unpays, unrececives));
  }
Example #10
0
 public TeredoInfo(
     Inet4Address paramInet4Address1,
     Inet4Address paramInet4Address2,
     int paramInt1,
     int paramInt2) {
   Preconditions.checkArgument(
       (paramInt1 >= 0) && (paramInt1 <= 65535),
       "port '%s' is out of range (0 <= port <= 0xffff)",
       new Object[] {Integer.valueOf(paramInt1)});
   Preconditions.checkArgument(
       (paramInt2 >= 0) && (paramInt2 <= 65535),
       "flags '%s' is out of range (0 <= flags <= 0xffff)",
       new Object[] {Integer.valueOf(paramInt2)});
   this.server = ((Inet4Address) Objects.firstNonNull(paramInet4Address1, InetAddresses.ANY4));
   this.client = ((Inet4Address) Objects.firstNonNull(paramInet4Address2, InetAddresses.ANY4));
   this.port = paramInt1;
   this.flags = paramInt2;
 }
 private int getSplitsPerNode(Map<String, String> properties) {
   try {
     return Integer.parseInt(
         Objects.firstNonNull(
             properties.get("tpch.splits-per-node"), String.valueOf(defaultSplitsPerNode)));
   } catch (NumberFormatException e) {
     throw new IllegalArgumentException("Invalid property tpch.splits-per-node");
   }
 }
  public GenerateReportResponseType generateReport(final GenerateReportType request)
      throws EucalyptusCloudException {
    final GenerateReportResponseType reply = request.getReply();
    reply.getResponseMetadata().setRequestId(reply.getCorrelationId());

    checkAuthorized();

    final Period period = Period.defaultPeriod();
    long startTime = period.getBeginningMs();
    long endTime = period.getEndingMs();
    if (request.getStartDate() != null) {
      startTime = parseDate(request.getStartDate());
    }
    if (request.getEndDate() != null) {
      endTime = parseDate(request.getEndDate());
    }

    final String reportData;
    try {
      reportData =
          ReportGenerationFacade.generateReport(
              Objects.firstNonNull(request.getType(), "instance"),
              Objects.firstNonNull(request.getFormat(), "html"),
              units(request),
              startTime,
              endTime);
    } catch (final ReportGenerationArgumentException e) {
      throw new ReportingException(
          HttpResponseStatus.BAD_REQUEST,
          ReportingException.BAD_REQUEST,
          "Bad request: Invalid start or end date");
    } catch (final Exception e) {
      logger.error(e, e);
      throw new ReportingException(
          HttpResponseStatus.INTERNAL_SERVER_ERROR,
          ReportingException.INTERNAL_SERVER_ERROR,
          "Error generating report");
    }

    reply.setResult(new GenerateReportResultType(reportData));

    return reply;
  }
  public ExportReportDataResponseType exportData(final ExportReportDataType request)
      throws EucalyptusCloudException {
    final ExportReportDataResponseType reply = request.getReply();
    reply.getResponseMetadata().setRequestId(reply.getCorrelationId());

    checkAuthorized();

    Date startDate = null;
    Date endDate = null;
    if (request.getStartDate() != null) {
      startDate = new Date(parseDate(request.getStartDate()));
    }
    if (request.getEndDate() != null) {
      endDate = new Date(parseDate(request.getEndDate()));
    }
    if (endDate != null && startDate != null && endDate.getTime() <= startDate.getTime()) {
      throw new ReportingException(
          HttpResponseStatus.BAD_REQUEST,
          ReportingException.BAD_REQUEST,
          "Bad request: Invalid start or end date");
    }

    final ReportingExport export = Export.export(startDate, endDate, request.isDependencies());
    reply.setResult(new ExportDataResultType(export));

    logger.info(
        "Exporting report data from "
            + Objects.firstNonNull(request.getStartDate(), "-")
            + " to "
            + Objects.firstNonNull(request.getEndDate(), "-"));

    try {
      RestfulMarshallingHandler.streamResponse(reply);
    } catch (final Exception e) {
      logger.error(e, e);
      throw new ReportingException(
          HttpResponseStatus.INTERNAL_SERVER_ERROR,
          ReportingException.INTERNAL_SERVER_ERROR,
          "Error exporting data");
    }

    return null;
  }
Example #14
0
 @Override
 public String toString() {
   return Objects.toStringHelper(DataContainer.class)
       .add("\n\toffset", offset)
       .add("\n\tlimit", limit)
       .add("\n\ttotal", total)
       .add("\n\tcall", call)
       .add("\n\tresults", Objects.firstNonNull(results, "").toString().replaceAll("\n", "\n\t"))
       .addValue('\n')
       .toString();
 }
  /**
   * Create an adjustment for a given invoice item. This just creates the object in memory, it
   * doesn't write it to disk.
   *
   * @param invoiceToBeAdjusted the invoice
   * @param invoiceItemId the invoice item id to adjust
   * @param positiveAdjAmount the amount to adjust. Pass null to adjust the full amount of the
   *     original item
   * @param currency the currency of the amount. Pass null to default to the original currency used
   * @param effectiveDate adjustment effective date, in the account timezone
   * @return the adjustment item
   */
  public InvoiceItem createAdjustmentItem(
      final Invoice invoiceToBeAdjusted,
      final UUID invoiceItemId,
      @Nullable final BigDecimal positiveAdjAmount,
      @Nullable final Currency currency,
      final LocalDate effectiveDate,
      final InternalCallContext context)
      throws InvoiceApiException {
    final InvoiceItem invoiceItemToBeAdjusted =
        Iterables.<InvoiceItem>tryFind(
                invoiceToBeAdjusted.getInvoiceItems(),
                new Predicate<InvoiceItem>() {
                  @Override
                  public boolean apply(final InvoiceItem input) {
                    return input.getId().equals(invoiceItemId);
                  }
                })
            .orNull();
    if (invoiceItemToBeAdjusted == null) {
      throw new InvoiceApiException(ErrorCode.INVOICE_ITEM_NOT_FOUND, invoiceItemId);
    }

    // Check the specified currency matches the one of the existing invoice
    final Currency currencyForAdjustment =
        Objects.firstNonNull(currency, invoiceItemToBeAdjusted.getCurrency());
    if (invoiceItemToBeAdjusted.getCurrency() != currencyForAdjustment) {
      throw new InvoiceApiException(
          ErrorCode.CURRENCY_INVALID, currency, invoiceItemToBeAdjusted.getCurrency());
    }

    // Reuse the same logic we have for refund with item adjustment
    final Map<UUID, BigDecimal> input = new HashMap<UUID, BigDecimal>();
    input.put(invoiceItemId, positiveAdjAmount);

    final Map<UUID, BigDecimal> output =
        dao.computeItemAdjustments(invoiceToBeAdjusted.getId().toString(), input, context);

    // If we pass that stage, it means the validation succeeded so we just need to extract resulting
    // amount and negate the result.
    final BigDecimal amountToAdjust = output.get(invoiceItemId).negate();
    // Finally, create the adjustment
    return new ItemAdjInvoiceItem(
        UUIDs.randomUUID(),
        context.getCreatedDate(),
        invoiceItemToBeAdjusted.getInvoiceId(),
        invoiceItemToBeAdjusted.getAccountId(),
        effectiveDate,
        null,
        amountToAdjust,
        currencyForAdjustment,
        invoiceItemToBeAdjusted.getId());
  }
 @Override
 public void image(Attributes attributes, String url) {
   writer.writeEmptyElement(getHtmlNsUri(), "img"); // $NON-NLS-1$
   writer.writeAttribute("src", makeUrlAbsolute(url)); // $NON-NLS-1$
   if (attributes instanceof ImageAttributes) {
     ImageAttributes imageAttributes = (ImageAttributes) attributes;
     writer.writeAttribute(
         getHtmlNsUri(), "alt", Objects.firstNonNull(imageAttributes.getAlt(), ""));
     if (imageAttributes.getTitle() != null) {
       writer.writeAttribute(getHtmlNsUri(), "title", imageAttributes.getTitle());
     }
   }
 }
Example #17
0
  public DefaultIssue createManualIssue(
      String componentKey,
      RuleKey ruleKey,
      @Nullable Integer line,
      @Nullable String message,
      @Nullable String severity) {
    verifyLoggedIn();

    DbSession dbSession = dbClient.openSession(false);
    try {
      Optional<ComponentDto> componentOptional =
          dbClient.componentDao().selectByKey(dbSession, componentKey);
      if (!componentOptional.isPresent()) {
        throw new BadRequestException(
            String.format("Component with key '%s' not found", componentKey));
      }
      ComponentDto component = componentOptional.get();
      ComponentDto project =
          dbClient.componentDao().selectOrFailByUuid(dbSession, component.projectUuid());

      userSession.checkComponentPermission(UserRole.USER, project.getKey());
      if (!ruleKey.isManual()) {
        throw new IllegalArgumentException(
            "Issues can be created only on rules marked as 'manual': " + ruleKey);
      }
      Rule rule = getNullableRuleByKey(ruleKey);
      if (rule == null) {
        throw new IllegalArgumentException("Unknown rule: " + ruleKey);
      }

      DefaultIssue issue =
          new DefaultIssueBuilder()
              .componentKey(component.getKey())
              .projectKey(project.getKey())
              .line(line)
              .message(!Strings.isNullOrEmpty(message) ? message : rule.getName())
              .severity(Objects.firstNonNull(severity, Severity.MAJOR))
              .ruleKey(ruleKey)
              .reporter(userSession.getLogin())
              .assignee(findSourceLineUser(dbSession, component.uuid(), line))
              .build();

      Date now = new Date();
      issue.setCreationDate(now);
      issue.setUpdateDate(now);
      issueStorage.save(issue);
      return issue;
    } finally {
      dbSession.close();
    }
  }
  @Override
  public Response<Paging<SupplierSolutionDto>> findSignByParam(
      final Long requirementId, Integer pageNo, Integer size) {
    Response<Paging<SupplierSolutionDto>> result = new Response<Paging<SupplierSolutionDto>>();

    if (requirementId == null) {
      log.error("find requirement solution need requirementId");
      result.setError("solution.requirementId.null");
      return result;
    }

    try {
      Map<String, Object> params = Maps.newHashMap();
      params.put("requirementId", requirementId);

      PageInfo pageInfo = new PageInfo(pageNo, Objects.firstNonNull(size, 10));
      params.putAll(pageInfo.toMap());

      Requirement requirement = requirementDao.findById(requirementId);

      // 获取需求下的供应商提交的方案
      Paging<RequirementSolution> solutionPaging =
          requirementSolutionDao.findSolutionsByParams(params);

      // 获取后台三级类目信息
      List<BackendJSON> categoryList =
          JSON_MAPPER.fromJson(
              requirement.getSeriesIds(),
              JSON_MAPPER.createCollectionType(List.class, BackendJSON.class));
      List<Long> categoryIds = Lists.newArrayList();
      for (BackendJSON backendJSON : categoryList) {
        categoryIds.add(backendJSON.getBcId());
      }

      List<SupplierSolutionDto> supplierSolutionDtoList = Lists.newArrayList();
      for (RequirementSolution solution : solutionPaging.getData()) {
        supplierSolutionDtoList.add(querySupplierDto(requirementId, solution, categoryIds));
      }

      result.setResult(
          new Paging<SupplierSolutionDto>(solutionPaging.getTotal(), supplierSolutionDtoList));
    } catch (Exception e) {
      log.error(
          "find requirement solution have sign secrecy failed , requirementId={} error code={}",
          requirementId,
          Throwables.getStackTraceAsString(e));
      result.setError("solution.supplier.findFailed");
    }

    return result;
  }
 SystemDatasetInstantiator(
     DatasetFramework datasetFramework,
     @Nullable ClassLoader parentClassLoader,
     DatasetClassLoaderProvider classLoaderProvider,
     @Nullable Iterable<? extends Id> owners) {
   this.owners = owners;
   this.classLoaderProvider = classLoaderProvider;
   this.datasetFramework = datasetFramework;
   this.parentClassLoader =
       parentClassLoader == null
           ? Objects.firstNonNull(
               Thread.currentThread().getContextClassLoader(), getClass().getClassLoader())
           : parentClassLoader;
 }
  @Override
  public Response<Paging<Requirement>> findByParams(
      BaseUser user,
      Integer qualifyStatus,
      Integer status,
      String reqName,
      String startAt,
      String endAt,
      Integer pageNo,
      Integer size) {
    Response<Paging<Requirement>> result = new Response<Paging<Requirement>>();

    // 验证用户是否已登入
    if (user == null) {
      log.error("create requirement solution, user must login.");
      result.setError("user.not.login");
      return result;
    }

    // 获取用户对应的供应商信息
    Response<Company> companyRes = companyService.findCompanyByUserId(user.getId());
    if (!companyRes.isSuccess()) {
      log.error("query company failed, error code={}", companyRes.getError());
      result.setError(companyRes.getError());
      return result;
    }

    try {
      Map<String, Object> params = Maps.newHashMap();
      params.put("name", Strings.isNullOrEmpty(reqName) ? null : reqName);
      params.put("qualifyStatus", qualifyStatus);
      params.put("status", status);
      params.put("startAt", startAt);
      params.put("endAt", endAt);

      PageInfo pageInfo = new PageInfo(pageNo, Objects.firstNonNull(size, 10));
      params.putAll(pageInfo.toMap());

      result.setResult(requirementDao.findBySupplier(companyRes.getResult().getId(), params));
    } catch (Exception e) {
      log.error(
          "find requirement solutions failed, supplierId={}, error code={}",
          companyRes.getResult().getId(),
          Throwables.getStackTraceAsString(e));
      result.setError("solution.find.failed");
    }

    return result;
  }
Example #21
0
  public void tickStart(EnumSet<TickType> ticks, Side side, Object... data) {
    List<IScheduledTickHandler> scheduledTicks =
        side.isClient() ? scheduledClientTicks : scheduledServerTicks;

    if (scheduledTicks.size() == 0) {
      return;
    }
    for (IScheduledTickHandler ticker : scheduledTicks) {
      EnumSet<TickType> ticksToRun =
          EnumSet.copyOf(Objects.firstNonNull(ticker.ticks(), EnumSet.noneOf(TickType.class)));
      ticksToRun.removeAll(EnumSet.complementOf(ticks));
      if (!ticksToRun.isEmpty()) {
        ticker.tickStart(ticksToRun, data);
      }
    }
  }
  public void put(@Nullable final UUID kbTenantId, @Nullable final C configurableForTenant) {
    final String key = getKey(kbTenantId);
    final C oldConfigurable =
        perTenantConfigurable.put(
            key, Objects.firstNonNull(configurableForTenant, defaultConfigurable));

    // Cleanup the old value
    if (oldConfigurable != null
        && oldConfigurable instanceof Closeable
        && oldConfigurable != defaultConfigurable) {
      try {
        ((Closeable) oldConfigurable).close();
      } catch (final IOException ignored) {
      }
    }
  }
 public BusinessFactoryBase(
     final CurrencyConversionDao currencyConversionDao,
     final OSGIKillbillLogService logService,
     final OSGIKillbillAPI osgiKillbillAPI,
     final OSGIConfigPropertiesService osgiConfigPropertiesService,
     final Clock clock) {
   this.logService = logService;
   this.osgiKillbillAPI = osgiKillbillAPI;
   this.clock = clock;
   this.referenceCurrency =
       Objects.firstNonNull(
           Strings.emptyToNull(
               osgiConfigPropertiesService.getString(ANALYTICS_REFERENCE_CURRENCY_PROPERTY)),
           "USD");
   this.currencyConversionDao = currencyConversionDao;
 }
Example #24
0
  public MediaType withParameter(String attribute, String value) {
    Preconditions.checkNotNull(attribute);
    Preconditions.checkNotNull(value);
    String normalizedAttribute = normalizeToken(attribute);
    ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
    for (Map.Entry<String, String> entry : this.parameters.entries()) {
      String key = (String) entry.getKey();
      if (!normalizedAttribute.equals(key)) {
        builder.put(key, entry.getValue());
      }
    }
    builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
    MediaType mediaType = new MediaType(this.type, this.subtype, builder.build());

    return (MediaType) Objects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
  }
  public Map func_178446_a() {
    IdentityHashMap var1 = Maps.newIdentityHashMap();
    Iterator var2 = Block.blockRegistry.iterator();

    while (var2.hasNext()) {
      Block var3 = (Block) var2.next();

      if (!this.field_178449_b.contains(var3)) {
        var1.putAll(
            ((IStateMapper)
                    Objects.firstNonNull(this.field_178450_a.get(var3), new DefaultStateMapper()))
                .func_178130_a(var3));
      }
    }

    return var1;
  }
  @Override
  public void afterRegistration(
      final OObjectDatabaseTx db,
      final SchemeDescriptor descriptor,
      final Field field,
      final LuceneIndex annotation) {
    db.getMetadata().getIndexManager().reload();
    final String property = field.getName();
    final String model = descriptor.schemeClass;
    final String name =
        Objects.firstNonNull(Strings.emptyToNull(annotation.name().trim()), model + '.' + property);
    final OClass clazz = db.getMetadata().getSchema().getClass(model);
    final OIndex<?> classIndex = clazz.getClassIndex(name);
    final OClass.INDEX_TYPE type = OClass.INDEX_TYPE.FULLTEXT;
    if (!descriptor.initialRegistration && classIndex != null) {
      final IndexValidationSupport support = new IndexValidationSupport(classIndex, logger);
      support.checkTypeCompatible(type);
      support.checkFieldsCompatible(property);

      final boolean correct =
          support
              .isIndexSigns(
                  classIndex.getConfiguration().field("algorithm"), getAnalyzer(classIndex))
              .matchRequiredSigns(
                  type, OLuceneIndexFactory.LUCENE_ALGORITHM, annotation.value().getName());
      if (!correct) {
        support.dropIndex(db);
      } else {
        // index ok
        return;
      }
    }
    final ODocument metadata = createMetadata(annotation);
    SchemeUtils.command(
        db,
        "create index %s on %s (%s) %s engine %s metadata %s",
        name,
        model,
        property,
        type.name(),
        OLuceneIndexFactory.LUCENE_ALGORITHM,
        metadata.toJSON());
    logger.info("Lucene fulltext index '{}' ({} [{}]) created", name, model, property);
  }
Example #27
0
  @Override
  public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    ZimbraSoapContext zsc = getZimbraSoapContext(context);
    Mailbox mbox = getRequestedMailbox(zsc);
    Account account = getRequestedAccount(zsc);
    OperationContext octxt = getOperationContext(zsc, context);

    SearchRequest req = JaxbUtil.elementToJaxb(request);
    if (Objects.firstNonNull(req.getWarmup(), false)) {
      mbox.index.getIndexStore().warmup();
      return zsc.createElement(MailConstants.SEARCH_RESPONSE);
    }

    SearchParams params = SearchParams.parse(req, zsc, account.getPrefMailInitialSearch());
    if (params.getLocale() == null) {
      params.setLocale(mbox.getAccount().getLocale());
    }
    if (params.inDumpster() && params.getTypes().contains(MailItem.Type.CONVERSATION)) {
      throw ServiceException.INVALID_REQUEST("cannot search for conversations in dumpster", null);
    }

    if (LC.calendar_cache_enabled.booleanValue()) {
      List<String> apptFolderIds = getFolderIdListIfSimpleAppointmentsQuery(params, zsc);
      if (apptFolderIds != null) {
        Account authAcct = getAuthenticatedAccount(zsc);
        Element response = zsc.createElement(MailConstants.SEARCH_RESPONSE);
        runSimpleAppointmentQuery(response, params, octxt, zsc, authAcct, mbox, apptFolderIds);
        return response;
      }
    }

    ZimbraQueryResults results = mbox.index.search(zsc.getResponseProtocol(), octxt, params);
    try {
      // create the XML response Element
      Element response = zsc.createElement(MailConstants.SEARCH_RESPONSE);
      // must use results.getSortBy() because the results might have ignored our sortBy
      // request and used something else...
      response.addAttribute(MailConstants.A_SORTBY, results.getSortBy().toString());
      putHits(zsc, octxt, response, results, params);
      return response;
    } finally {
      Closeables.closeQuietly(results);
    }
  }
Example #28
0
  private static MediaType create(
      String type, String subtype, Multimap<String, String> parameters) {
    Preconditions.checkNotNull(type);
    Preconditions.checkNotNull(subtype);
    Preconditions.checkNotNull(parameters);
    String normalizedType = normalizeToken(type);
    String normalizedSubtype = normalizeToken(subtype);
    Preconditions.checkArgument(
        (!"*".equals(normalizedType)) || ("*".equals(normalizedSubtype)),
        "A wildcard type cannot be used with a non-wildcard subtype");

    ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
    for (Map.Entry<String, String> entry : parameters.entries()) {
      String attribute = normalizeToken((String) entry.getKey());
      builder.put(attribute, normalizeParameterValue(attribute, (String) entry.getValue()));
    }
    MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());

    return (MediaType) Objects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
  }
  @Override
  public Response<List<RequirementSolution>> findAllSolution(Long requirementId, Integer status) {
    Response<List<RequirementSolution>> result = new Response<List<RequirementSolution>>();

    if (requirementId == null) {
      log.error("find requirement solution need requirementId");
      result.setError("solution.requirementId.null");
      return result;
    }

    if (RequirementStatus.from(status) == null) {
      log.error("can't find the status type.");
      result.setError("requirement.status.null");
      return result;
    }

    // 当查询阶段为空时默认方案交互阶段
    Objects.firstNonNull(status, 3);

    try {
      List<RequirementSolution> solutionList;
      if (Objects.equal(RequirementStatus.SOL_END, RequirementStatus.from(status))) {
        // 当处于方案终投阶段(只能查询到最终确认最终方案的供应商的方案)
        solutionList =
            requirementSolutionDao.findSolutionEnds(
                requirementId, null, 5, RequirementSolution.Status.SEND_END.value());
      } else {
        solutionList = requirementSolutionDao.findAllSolution(requirementId);
      }
      result.setResult(solutionList);
    } catch (Exception e) {
      log.error(
          "find requirement solution failed, requirementId={}, error code={}",
          requirementId,
          Throwables.getStackTraceAsString(e));
      result.setError("requirement.find.failed");
    }

    return result;
  }
Example #30
0
  public Paginator<Orcamento> getPaginator(Page page, String s, Date dInicio, Date dFim) {
    // SANITAZING
    DateTime dateTimeInicio =
        new DateTime(Objects.firstNonNull(dInicio, new LocalDate(2015, 01, 01).toDate()));
    DateTime dateTimeFim =
        new LocalDate(dFim == null ? dateTimeInicio.plusYears(1) : dFim)
            .plusDays(1)
            .toDateTimeAtStartOfDay()
            .minusMinutes(5);

    if (dInicio != null || dFim != null) {
      if (Strings.isNullOrEmpty(s)) {
        return paginatedQuery
            .jpql(
                "select o from Orcamento o where o.createTime >= :inicio and o.createTime <= :fim order by o.id desc")
            .setParameter("inicio", dateTimeInicio.toDate())
            .setParameter("fim", dateTimeFim.toDate())
            .paginate(page);
      } else {
        return paginatedQuery
            .jpql(
                "select o from Orcamento o where o.createTime >= :inicio and o.createTime <= :fim and (o.nome like :s or o.empresa like :s or o.local like :s or o.evento like :s ) order by o.id desc")
            .setParameter("inicio", dateTimeInicio.toDate())
            .setParameter("fim", dateTimeFim.toDate())
            .setParameter("s", "%" + s + "%")
            .paginate(page);
      }
    } else {
      if (Strings.isNullOrEmpty(s)) {
        return paginatedQuery.jpql("select o from Orcamento o order by o.id desc").paginate(page);
      } else {
        return paginatedQuery
            .jpql(
                "select o from Orcamento o where (o.nome like :s or o.empresa like :s or o.local like :s or o.evento like :s ) order by o.id desc")
            .setParameter("s", "%" + s + "%")
            .paginate(page);
      }
    }
  }