@Override
  protected Control createContents(Composite parent) {
    Composite composite = new Composite(parent, SWT.NONE);
    composite.setLayout(new GridLayout(2, false));

    name = createTextWithLabel(composite, "Name");
    wkn = createTextWithLabel(composite, "WKN");
    isin = createTextWithLabel(composite, "Isin");
    ticker = createTextWithLabel(composite, "Ticker");
    morningstarSymbol = createTextWithLabel(composite, "Morningstar");
    fourTradersUrl = createTextWithLabel(composite, "4-Traders Url");

    Label label = new Label(composite, SWT.NONE);
    label.setText("Override existing price data");
    overridePriceDate = new Button(composite, SWT.CHECK);

    IAdaptable adapter = getElement();
    Security security = (Security) adapter.getAdapter(Security.class);
    name.setText(security.getName());
    wkn.setText(StringUtils.defaultString(security.getWKN()));
    isin.setText(StringUtils.defaultString(security.getISIN()));
    ticker.setText(StringUtils.defaultString(security.getTicker()));
    morningstarSymbol.setText(StringUtils.defaultString(security.getMorningstarSymbol()));
    fourTradersUrl.setText(
        StringUtils.defaultString(security.getConfigurationValue("fourTrasdersUrl")));
    overridePriceDate.setSelection(
        Boolean.valueOf(security.getConfigurationValue(OVERRIDE_EXISTING_PRICE_DATA))
            .booleanValue());

    return composite;
  }
Esempio n. 2
0
 public JSONObject toJsonObject() {
   JSONObject jsonObject = new JSONObject();
   jsonObject.put(JSON_PROPERTIES_UID, uid);
   jsonObject.put(JSON_PROPERTIES_COMPANY_NAME, StringUtils.defaultString(companyName));
   jsonObject.put(JSON_PROPERTIES_ADDRESS, StringUtils.defaultString(address));
   jsonObject.put(JSON_PROPERTIES_APPROVE_STATUS, approveStatus);
   jsonObject.put(JSON_PROPERTIES_JOB_TITLE, StringUtils.defaultString(jobTitle));
   return jsonObject;
 }
Esempio n. 3
0
 public static String makeGUID(
     final String catalog, final String schema, final String table, final String column) {
   final String t =
       StringUtils.defaultString(catalog)
           + StringUtils.defaultString(schema)
           + StringUtils.defaultString(table)
           + StringUtils.defaultString(column);
   return "v_" + (UUID.nameUUIDFromBytes(t.getBytes()).toString().replace("-", "_"));
 }
  private void checkCredentials(final String username, final String password) {
    final String nam = StringUtils.defaultString(username);
    final String pwd = StringUtils.defaultString(password);

    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
      ActivityMixin.showToast(this, R.string.err_missing_auth);
      return;
    }

    final Credentials credentials = new Credentials(nam, pwd);
    final AbstractCredentialsAuthorizationActivity authorizationActivity = this;

    final ProgressDialog loginDialog =
        ProgressDialog.show(
            authorizationActivity,
            res.getString(R.string.init_login_popup),
            getAuthDialogWait(),
            true);
    loginDialog.setCancelable(false);

    AppObservable.bindActivity(
            authorizationActivity,
            Observable.defer(
                new Func0<Observable<StatusCode>>() {
                  @Override
                  public Observable<StatusCode> call() {
                    return Observable.just(checkCredentials(credentials));
                  }
                }))
        .subscribeOn(AndroidRxUtils.networkScheduler)
        .subscribe(
            new Action1<StatusCode>() {
              @Override
              public void call(StatusCode statusCode) {
                loginDialog.dismiss();
                if (statusCode == StatusCode.NO_ERROR) {
                  setCredentials(credentials);
                  showToast(getAuthDialogCompleted());
                  setResult(RESULT_OK);
                  finish();
                } else {
                  Dialogs.message(
                      authorizationActivity,
                      R.string.init_login_popup,
                      res.getString(
                          R.string.init_login_popup_failed_reason, statusCode.getErrorString(res)));
                  checkButton.setText(getAuthCheckAgain());
                  checkButton.setOnClickListener(new CheckListener());
                  checkButton.setEnabled(true);
                }
              }
            });
  }
 protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
   String username = StringUtils.defaultString(this.getUsername(request));
   String password = StringUtils.defaultString(this.getPassword(request));
   String captcha = StringUtils.defaultString(this.getCaptcha(request));
   // boolean rememberMe = StringUtils.defaultString(isRememberMe(request));
   boolean rememberMe = false;
   String host = StringUtils.defaultString(getHost(request));
   char pwd[] = null;
   try {
     pwd = this.accountService.tranPassword(password).toCharArray();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return new GreenStepBaseUsernamePasswordToken(username, pwd, rememberMe, host, captcha);
 }
Esempio n. 6
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_base_without_drawer);

    setupNavCrossIcon();

    Intent intent = getIntent();
    String quotePostId = intent.getStringExtra(ARG_QUOTE_POST_ID);
    String titlePrefix =
        TextUtils.isEmpty(quotePostId)
            ? getString(R.string.reply_activity_title_prefix)
            : getString(
                R.string.reply_activity_quote_title_prefix,
                intent.getStringExtra(ARG_QUOTE_POST_COUNT));
    setTitle(
        titlePrefix
            + StringUtils.defaultString(
                intent.getStringExtra(ARG_THREAD_TITLE), StringUtils.EMPTY));

    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment fragment = fragmentManager.findFragmentByTag(ReplyFragment.TAG);
    if (fragment == null) {
      mReplyFragment = ReplyFragment.newInstance(intent.getStringExtra(ARG_THREAD_ID), quotePostId);
      fragmentManager
          .beginTransaction()
          .add(R.id.frame_layout, mReplyFragment, ReplyFragment.TAG)
          .commit();
    } else {
      mReplyFragment = (ReplyFragment) fragment;
    }
  }
Esempio n. 7
0
  private String cleanupHtml(
      String html, List<MacroInvocation> macroInvocations, boolean cacheable) {
    for (; ; ) {
      String newHtml = html;
      for (Replacement replacement : CLEANUP) {
        newHtml = replacement.replaceAll(newHtml);
      }
      for (MacroInvocation macroInvocation : macroInvocations) {
        IMacro macro = macroFactory.get(macroInvocation.getMacroName());
        if (macro != null) {
          IMacroDescriptor macroDescriptor = macro.getDescriptor();
          if (macroDescriptor.isCacheable() == cacheable) {
            IMacroRunnable macroRunnable = macro.createRunnable();
            newHtml = StringUtils.defaultString(macroRunnable.cleanupHtml(newHtml), newHtml);
          }
        }
      }

      if (newHtml.equals(html)) {
        break;
      }

      html = newHtml;
    }
    return html;
  }
 public void update() {
   Boolean idpRequired = null;
   try {
     idpRequired = Boolean.valueOf((String) pluginSettings.get(IDP_REQUIRED_SETTING));
   } catch (ClassCastException e) {
     idpRequired = false;
   }
   if (idpRequired == null) idpRequired = false;
   this.idpRequired = idpRequired;
   try {
     String s = StringUtils.defaultString((String) pluginSettings.get(SETTINGS));
     if (!s.isEmpty()) {
       settings =
           objectMapper.readValue(
               (String) pluginSettings.get(SETTINGS),
               new TypeReference<Map<String, SAMLJiraConfig>>() {});
       idps =
           settings
               .entrySet()
               .stream()
               .map(v -> new NameValuePair(v.getKey(), v.getValue().getId()))
               .sorted((u, v) -> v.getValue().compareTo(u.getValue()))
               .collect(Collectors.toList());
       String name = i18n.getText("saml2Plugin.admin.newIdP");
       if (!settings.containsKey(name)) {
         createEmpty();
       }
       return;
     }
   } catch (IOException e) {
     log.error(e.getMessage(), e);
   }
   createEmpty();
 }
Esempio n. 9
0
  @Override
  public <T extends IResource> Bundle search(
      final Class<T> theType, Map<String, List<IQueryParameterType>> theParams) {
    LinkedHashMap<String, List<String>> params = new LinkedHashMap<String, List<String>>();
    for (Entry<String, List<IQueryParameterType>> nextEntry : theParams.entrySet()) {
      ArrayList<String> valueList = new ArrayList<String>();
      String qualifier = null;
      for (IQueryParameterType nextValue : nextEntry.getValue()) {
        valueList.add(nextValue.getValueAsQueryToken());
        qualifier = nextValue.getQueryParameterQualifier();
      }
      qualifier = StringUtils.defaultString(qualifier);
      params.put(nextEntry.getKey() + qualifier, valueList);
    }

    BaseHttpClientInvocation invocation =
        SearchMethodBinding.createSearchInvocation(
            myContext, toResourceName(theType), params, null, null, null);
    if (isKeepResponses()) {
      myLastRequest = invocation.asHttpRequest(getServerBase(), createExtraParams(), getEncoding());
    }

    BundleResponseHandler binding = new BundleResponseHandler(theType);
    Bundle resp = invokeClient(myContext, binding, invocation, myLogRequestAndResponse);
    return resp;
  }
  @Override
  public void createPartControl(Composite parent) {
    Composite body = new Composite(parent, SWT.NONE);
    body.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
    body.setLayout(new GridLayout());

    Account account = getAccount();
    intervalReport =
        new TimeIntervalReport(
            account, TimeIntervalReport.Interval.DAY, PriceProviderFactory.getInstance());
    intervalReport.addPropertyChangeListener(changeListener);

    String chartType = StringUtils.defaultString(account.getConfigurationValue(CHART_TYPE), "all");
    JFreeChart chart = createChart(chartType);
    chartFrame = new ChartComposite(body, SWT.NONE, chart, true);
    chartFrame.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    displayType = new Combo(body, SWT.READ_ONLY);
    for (TimeChart.RANGE r : TimeChart.RANGE.values()) {
      displayType.add(r.getName());
    }
    displayType.setText(chartType);
    displayType.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            Combo c = (Combo) e.getSource();
            String type = c.getItem(c.getSelectionIndex());
            timeChart.setChartType(type);
            dirty = true;
            firePropertyChange(IEditorPart.PROP_DIRTY);
          }
        });
  }
  private void checkForm(PartnerActivityProductAudit form, String domain) {
    if (StringUtils.isBlank(form.getActId())) {
      throw new BizException(GlobalErrorCode.UNKNOWN, "活动Id不存在");
    }

    if (StringUtils.isBlank(form.getProductId())) {
      throw new BizException(GlobalErrorCode.UNKNOWN, "商品Id不存在");
    }

    if (form.getAuditState() == null) {
      throw new BizException(GlobalErrorCode.UNKNOWN, "审核状态不存在");
    }

    if (form.getAuditor() == null) {
      throw new BizException(GlobalErrorCode.UNKNOWN, "审核人不存在");
    }

    if (ActivityTicketAuditStatus.APPROVED.equals(form.getAuditState())) {
      if (form.getStartTime() == null || form.getEndTime() == null)
        throw new BizException(GlobalErrorCode.UNKNOWN, "审核通过必须分配活动开始结束时间");
      if (form.getProductId() == null) throw new BizException(GlobalErrorCode.UNKNOWN, "审核信息不完整");
    }

    User user =
        userService.loadExtUser(StringUtils.defaultString(domain, "xiangqu"), form.getAuditor());
    if (user == null) {
      throw new BizException(GlobalErrorCode.UNAUTHORIZED, "您没有权限审核该活动");
    }
  }
Esempio n. 12
0
 /**
  * Store the requested attachment on the filesystem and return a {@code file://} URL where FOP can
  * access that file.
  *
  * @param wiki the name of the owner document's wiki
  * @param space the name of the owner document's space
  * @param name the name of the owner document
  * @param filename the name of the attachment
  * @param revision an optional attachment version
  * @param context the current request context
  * @return a {@code file://} URL where the attachment has been stored
  * @throws Exception if the attachment can't be retrieved from the database and stored on the
  *     filesystem
  */
 private URL getURL(
     String wiki,
     String space,
     String name,
     String filename,
     String revision,
     XWikiContext context)
     throws Exception {
   Map<String, File> usedFiles = getFileMapping(context);
   String key = getAttachmentKey(space, name, filename, revision);
   if (!usedFiles.containsKey(key)) {
     File file = getTemporaryFile(key, context);
     XWikiDocument doc =
         context
             .getWiki()
             .getDocument(
                 new DocumentReference(
                     StringUtils.defaultString(wiki, context.getDatabase()), space, name),
                 context);
     XWikiAttachment attachment = doc.getAttachment(filename);
     if (StringUtils.isNotEmpty(revision)) {
       attachment = attachment.getAttachmentRevision(revision, context);
     }
     FileOutputStream fos = new FileOutputStream(file);
     IOUtils.copy(attachment.getContentInputStream(context), fos);
     fos.close();
     usedFiles.put(key, file);
   }
   return usedFiles.get(key).toURI().toURL();
 }
Esempio n. 13
0
  @Override
  public void translateClientArgumentIntoQueryArgument(
      FhirContext theContext,
      Object theSourceClientArgument,
      Map<String, List<String>> theTargetQueryArguments,
      IBaseResource theTargetResource)
      throws InternalErrorException {
    if (theSourceClientArgument == null) {
      if (isRequired()) {
        throw new NullPointerException(
            "SearchParameter '" + getName() + "' is required and may not be null");
      }
    } else {
      List<QualifiedParamList> value = encode(theContext, theSourceClientArgument);
      ArrayList<String> paramValues = new ArrayList<String>(value.size());
      String qualifier = null;

      for (QualifiedParamList nextParamEntry : value) {
        StringBuilder b = new StringBuilder();
        for (String str : nextParamEntry) {
          if (b.length() > 0) {
            b.append(",");
          }
          b.append(str.replace(",", "\\,"));
        }
        paramValues.add(b.toString());

        if (StringUtils.isBlank(qualifier)) {
          qualifier = nextParamEntry.getQualifier();
        }
      }

      theTargetQueryArguments.put(getName() + StringUtils.defaultString(qualifier), paramValues);
    }
  }
  private Dependency toDependency(String id, String version, String type) throws ResolveException {
    Matcher matcher = PARSER_ID.matcher(id);
    if (!matcher.matches()) {
      throw new ResolveException(
          "Bad id " + id + ", expected format is <groupId>:<artifactId>[:<classifier>]");
    }

    Dependency dependency = new Dependency();

    dependency.setGroupId(matcher.group(1));
    dependency.setArtifactId(matcher.group(2));
    if (matcher.group(4) != null) {
      dependency.setClassifier(StringUtils.defaultString(matcher.group(4), ""));
    }

    if (version != null) {
      dependency.setVersion(version);
    }

    if (type != null) {
      dependency.setType(type);
    }

    return dependency;
  }
Esempio n. 15
0
 @Override
 public String getDescription() {
   if (description == null) {
     description =
         StringUtils.defaultString(cgeoapplication.getInstance().getCacheDescription(geocode));
   }
   return description;
 }
 public void save(SAMLJiraConfig samlJiraConfig) {
   String id = StringUtils.defaultString(samlJiraConfig.getId());
   if (id.isEmpty() || id.equals(NEW_ID_EMPTY)) {
     samlJiraConfig.setId("id" + System.currentTimeMillis());
   }
   setIdpRequired(samlJiraConfig.isIdpRequired());
   add(samlJiraConfig);
 }
Esempio n. 17
0
 public static void addBotToMDC(PircBotX bot) {
   MDC.put("pircbotx.id", String.valueOf(bot.getBotId()));
   MDC.put(
       "pircbotx.connectionId",
       bot.getServerHostname() + "-" + bot.getBotId() + "-" + bot.getConnectionId());
   MDC.put("pircbotx.server", StringUtils.defaultString(bot.getServerHostname()));
   MDC.put("pircbotx.port", String.valueOf(bot.getServerPort()));
 }
 protected RuntimeResourceDefinition getResourceType(
     HomeRequest theRequest, HttpServletRequest theReq) throws ServletException {
   String resourceName = StringUtils.defaultString(theReq.getParameter(PARAM_RESOURCE));
   RuntimeResourceDefinition def = getContext(theRequest).getResourceDefinition(resourceName);
   if (def == null) {
     throw new ServletException("Invalid resourceName: " + resourceName);
   }
   return def;
 }
 private String replaceParameters(final Options options, final String resolvedValue) {
   String message = StringUtils.defaultString(resolvedValue);
   for (final Map.Entry<String, Object> entry : options.hash.entrySet()) {
     if (entry.getValue() != null) {
       final String parameter = "__" + entry.getKey() + "__";
       message = message.replace(parameter, entry.getValue().toString());
     }
   }
   return message;
 }
 Map<String, String> deserialiseDeviceRegistrations(String deviceRegistrations) {
   Map<String, String> result = new HashMap<>();
   Arrays.stream(StringUtils.defaultString(deviceRegistrations).split("\\|"))
       .forEach(
           deviceRegistration -> {
             String[] keyValue = deviceRegistration.split(":");
             if (keyValue.length == 2) {
               result.put(keyValue[0], keyValue[1]);
             }
           });
   return result;
 }
Esempio n. 21
0
 private void readResultJson(JsonObject object) {
   if (object.get("api_quest_name") != null) {
     this.questName = object.getString("api_quest_name");
   } else {
     // 演習の場合はない
     this.questName = null;
   }
   this.rank = ResultRank.fromRank(object.getString("api_win_rank"));
   // 完全勝利Sは分からないので戦闘結果を見る
   Phase lastPhase = this.getLastPhase();
   if ((lastPhase != null) && (lastPhase.getEstimatedRank() == ResultRank.PERFECT)) {
     this.rank = ResultRank.PERFECT;
   }
   this.enemyName = object.getJsonObject("api_enemy_info").getString("api_deck_name");
   this.dropShip = object.containsKey("api_get_ship");
   this.dropItem = object.containsKey("api_get_useitem");
   if (this.dropShip || this.dropItem) {
     if (this.dropShip) {
       JsonObject getShip = object.getJsonObject("api_get_ship");
       this.dropShipId = getShip.getInt("api_ship_id");
       this.dropType = getShip.getString("api_ship_type");
       this.dropName = getShip.getString("api_ship_name");
     } else {
       String name = UseItem.get(object.getJsonObject("api_get_useitem").getInt("api_useitem_id"));
       this.dropType = "アイテム";
       this.dropName = StringUtils.defaultString(name);
     }
   } else {
     this.dropType = "";
     this.dropName = "";
   }
   this.mvp = object.getInt("api_mvp");
   if (JsonUtils.hasKey(object, "api_mvp_combined")) {
     this.mvpCombined = object.getInt("api_mvp_combined");
   }
   this.hqLv = object.getInt("api_member_lv");
   if (JsonUtils.hasKey(object, "api_escape")) {
     JsonObject jsonEscape = object.getJsonObject("api_escape");
     this.escapeInfo =
         new int[] {
           jsonEscape.getJsonArray("api_escape_idx").getInt(0) - 1,
           jsonEscape.getJsonArray("api_tow_idx").getInt(0) - 1
         };
   }
   if (JsonUtils.hasKey(object, "api_lost_flag")) {
     this.lostflag = new boolean[6];
     JsonArray jsonLostflag = object.getJsonArray("api_lost_flag");
     for (int i = 1; i < jsonLostflag.size(); i++) {
       this.lostflag[i - 1] = (jsonLostflag.getInt(i) != 0);
     }
   }
 }
Esempio n. 22
0
 /**
  * Computes a safe identifier for an attachment, guaranteed to be collision-free.
  *
  * @param space the name of the owner document's space
  * @param name the name of the owner document
  * @param filename the name of the attachment
  * @param revision an optional attachment version
  * @return an identifier for this attachment
  */
 private String getAttachmentKey(String space, String name, String filename, String revision) {
   try {
     return "attachment"
         + SEPARATOR
         + URLEncoder.encode(space, XWiki.DEFAULT_ENCODING)
         + SEPARATOR
         + URLEncoder.encode(name, XWiki.DEFAULT_ENCODING)
         + SEPARATOR
         + URLEncoder.encode(filename, XWiki.DEFAULT_ENCODING)
         + SEPARATOR
         + URLEncoder.encode(StringUtils.defaultString(revision), XWiki.DEFAULT_ENCODING);
   } catch (UnsupportedEncodingException ex) {
     // This should never happen, UTF-8 is always available
     return space
         + SEPARATOR
         + name
         + SEPARATOR
         + filename
         + SEPARATOR
         + StringUtils.defaultString(revision);
   }
 }
  private void changeToken(final String verifier) {

    int status = NOT_AUTHENTICATED;

    try {
      final Parameters params = new Parameters("oauth_verifier", verifier);

      final String method = "POST";
      OAuth.signOAuth(
          host,
          pathAccess,
          method,
          https,
          params,
          OAtoken,
          OAtokenSecret,
          consumerKey,
          consumerSecret);
      final String line =
          StringUtils.defaultString(
              Network.getResponseData(
                  Network.postRequest(getUrlPrefix() + host + pathAccess, params)));

      OAtoken = "";
      OAtokenSecret = "";

      final MatcherWrapper paramsMatcher1 = new MatcherWrapper(paramsPattern1, line);
      if (paramsMatcher1.find()) {
        OAtoken = paramsMatcher1.group(1);
      }
      final MatcherWrapper paramsMatcher2 = new MatcherWrapper(paramsPattern2, line);
      if (paramsMatcher2.find() && paramsMatcher2.groupCount() > 0) {
        OAtokenSecret = paramsMatcher2.group(1);
      }

      if (StringUtils.isBlank(OAtoken) && StringUtils.isBlank(OAtokenSecret)) {
        OAtoken = "";
        OAtokenSecret = "";
        setTokens(null, null, false);
      } else {
        setTokens(OAtoken, OAtokenSecret, true);
        status = AUTHENTICATED;
      }
    } catch (Exception e) {
      Log.e("OAuthAuthorizationActivity.changeToken", e);
    }

    changeTokensHandler.sendEmptyMessage(status);
  }
Esempio n. 24
0
  public static String printer() {
    StringBuilder buf = new StringBuilder();

    int[] colWidths = colWidths();

    for (String[] row : rows) {
      for (int colNum = 0; colNum < row.length; colNum++) {
        buf.append(StringUtils.rightPad(StringUtils.defaultString(row[colNum]), colWidths[colNum]));
        buf.append(' ');
      }

      buf.append('\n');
    }

    return buf.toString();
  }
 private String parseNarrative(
     HomeRequest theRequest, EncodingEnum theCtEnum, String theResultBody) {
   try {
     IBaseResource par = theCtEnum.newParser(getContext(theRequest)).parseResource(theResultBody);
     String retVal;
     if (par instanceof IResource) {
       IResource resource = (IResource) par;
       retVal = resource.getText().getDiv().getValueAsString();
     } else if (par instanceof IDomainResource) {
       retVal = ((IDomainResource) par).getText().getDivAsString();
     } else {
       retVal = null;
     }
     return StringUtils.defaultString(retVal);
   } catch (Exception e) {
     ourLog.error("Failed to parse resource", e);
     return "";
   }
 }
  private void checkForm(PartnerActivityProductStop form, String domain) {
    if (StringUtils.isBlank(form.getActId())) {
      throw new BizException(GlobalErrorCode.UNKNOWN, "活动Id不存在");
    }

    if (StringUtils.isBlank(form.getProductId())) {
      throw new BizException(GlobalErrorCode.UNKNOWN, "商品Id不存在");
    }

    if (form.getAuditor() == null) {
      throw new BizException(GlobalErrorCode.UNKNOWN, "审核人不存在");
    }

    User user =
        userService.loadExtUser(StringUtils.defaultString(domain, "xiangqu"), form.getAuditor());
    if (user == null) {
      throw new BizException(GlobalErrorCode.UNAUTHORIZED, "您没有权限审核该活动");
    }
  }
  private void validateGroups(
      List<ValidationMessage> theErrors,
      List<GroupComponent> theQuestionGroups,
      List<org.hl7.fhir.instance.model.QuestionnaireResponse.GroupComponent> theAnswerGroups,
      LinkedList<String> thePathStack,
      QuestionnaireResponse theAnswers,
      boolean theValidateRequired) {
    Set<String> linkIds = new HashSet<String>();
    for (GroupComponent nextQuestionGroup : theQuestionGroups) {
      String nextLinkId = StringUtils.defaultString(nextQuestionGroup.getLinkId());
      if (!linkIds.add(nextLinkId)) {
        if (isBlank(nextLinkId)) {
          fail(
              theErrors,
              IssueType.BUSINESSRULE,
              thePathStack,
              false,
              "Questionnaire in invalid, unable to validate QuestionnaireResponse: Multiple groups found at this position with blank/missing linkId",
              nextLinkId);
        } else {
          fail(
              theErrors,
              IssueType.BUSINESSRULE,
              thePathStack,
              false,
              "Questionnaire in invalid, unable to validate QuestionnaireResponse: Multiple groups found at this position with linkId[{0}]",
              nextLinkId);
        }
      }
    }

    Set<String> allowedGroups = new HashSet<String>();
    for (GroupComponent nextQuestionGroup : theQuestionGroups) {
      String linkId = nextQuestionGroup.getLinkId();
      allowedGroups.add(linkId);

      List<org.hl7.fhir.instance.model.QuestionnaireResponse.GroupComponent> answerGroups =
          findGroupByLinkId(theAnswerGroups, linkId);
      if (answerGroups.isEmpty()) {
        if (nextQuestionGroup.getRequired()) {
          if (theValidateRequired) {
            rule(
                theErrors,
                IssueType.BUSINESSRULE,
                thePathStack,
                false,
                "Missing required group with linkId[{0}]",
                linkId);
          } else {
            hint(
                theErrors,
                IssueType.BUSINESSRULE,
                thePathStack,
                false,
                "Missing required group with linkId[{0}]",
                linkId);
          }
        }
        continue;
      }
      if (answerGroups.size() > 1) {
        if (nextQuestionGroup.getRepeats() == false) {
          int index = theAnswerGroups.indexOf(answerGroups.get(1));
          thePathStack.add("group[" + index + "]");
          rule(
              theErrors,
              IssueType.BUSINESSRULE,
              thePathStack,
              false,
              "Multiple repetitions of group with linkId[{0}] found at this position, but this group can not repeat",
              linkId);
          thePathStack.removeLast();
        }
      }
      for (org.hl7.fhir.instance.model.QuestionnaireResponse.GroupComponent nextAnswerGroup :
          answerGroups) {
        int index = theAnswerGroups.indexOf(nextAnswerGroup);
        thePathStack.add("group[" + index + "]");
        validateGroup(
            theErrors,
            nextQuestionGroup,
            nextAnswerGroup,
            thePathStack,
            theAnswers,
            theValidateRequired);
        thePathStack.removeLast();
      }
    }

    // Make sure there are no groups in answers that aren't in the questionnaire
    int idx = -1;
    for (org.hl7.fhir.instance.model.QuestionnaireResponse.GroupComponent next : theAnswerGroups) {
      idx++;
      if (!allowedGroups.contains(next.getLinkId())) {
        thePathStack.add("group[" + idx + "]");
        rule(
            theErrors,
            IssueType.BUSINESSRULE,
            thePathStack,
            false,
            "Group with linkId[{0}] found at this position, but this group does not exist at this position in Questionnaire",
            next.getLinkId());
        thePathStack.removeLast();
      }
    }
  }
Esempio n. 28
0
 protected String localizePlainOrKey(String key, Object... parameters) {
   return StringUtils.defaultString(getLocalization().getTranslationPlain(key, parameters), key);
 }
Esempio n. 29
0
 /**
  * 获取属性值
  *
  * @param key 键
  * @param defaultValue 默认值
  * @return 值
  */
 public static String get(String key, String defaultValue) {
   String propertyValue = properties.getProperty(key);
   String value = StringUtils.defaultString(propertyValue, defaultValue);
   logger.debug("获取属性:{},值:{}", key, value);
   return value;
 }
Esempio n. 30
0
    @Override
    public String lookup(String theKey) {

      /*
       * TODO: this method could be made more efficient through some sort of lookup map
       */

      if ("operationType".equals(theKey)) {
        if (myRequestDetails.getRestOperationType() != null) {
          return myRequestDetails.getRestOperationType().getCode();
        }
        return "";
      } else if ("operationName".equals(theKey)) {
        if (myRequestDetails.getRestOperationType() != null) {
          switch (myRequestDetails.getRestOperationType()) {
            case EXTENDED_OPERATION_INSTANCE:
            case EXTENDED_OPERATION_SERVER:
            case EXTENDED_OPERATION_TYPE:
              return myRequestDetails.getOperation();
            default:
              return "";
          }
        } else {
          return "";
        }
      } else if ("id".equals(theKey)) {
        if (myRequestDetails.getId() != null) {
          return myRequestDetails.getId().getValue();
        }
        return "";
      } else if ("servletPath".equals(theKey)) {
        return StringUtils.defaultString(myRequest.getServletPath());
      } else if ("idOrResourceName".equals(theKey)) {
        if (myRequestDetails.getId() != null) {
          return myRequestDetails.getId().getValue();
        }
        if (myRequestDetails.getResourceName() != null) {
          return myRequestDetails.getResourceName();
        }
        return "";
      } else if (theKey.equals("requestParameters")) {
        StringBuilder b = new StringBuilder();
        for (Entry<String, String[]> next : myRequestDetails.getParameters().entrySet()) {
          for (String nextValue : next.getValue()) {
            if (b.length() == 0) {
              b.append('?');
            } else {
              b.append('&');
            }
            try {
              b.append(URLEncoder.encode(next.getKey(), "UTF-8"));
              b.append('=');
              b.append(URLEncoder.encode(nextValue, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
              throw new ca.uhn.fhir.context.ConfigurationException("UTF-8 not supported", e);
            }
          }
        }
        return b.toString();
      } else if (theKey.startsWith("requestHeader.")) {
        String val = myRequest.getHeader(theKey.substring("requestHeader.".length()));
        return StringUtils.defaultString(val);
      } else if (theKey.startsWith("remoteAddr")) {
        return StringUtils.defaultString(myRequest.getRemoteAddr());
      } else if (theKey.equals("responseEncodingNoDefault")) {
        EncodingEnum encoding =
            RestfulServerUtils.determineResponseEncodingNoDefault(
                myRequestDetails, myRequestDetails.getServer().getDefaultResponseEncoding());
        if (encoding != null) {
          return encoding.name();
        } else {
          return "";
        }
      } else if (theKey.equals("exceptionMessage")) {
        return myException != null ? myException.getMessage() : null;
      } else if (theKey.equals("requestUrl")) {
        return myRequest.getRequestURL().toString();
      } else if (theKey.equals("requestVerb")) {
        return myRequest.getMethod();
      } else if (theKey.equals("requestBodyFhir")) {
        String contentType = myRequest.getContentType();
        if (isNotBlank(contentType)) {
          int colonIndex = contentType.indexOf(';');
          if (colonIndex != -1) {
            contentType = contentType.substring(0, colonIndex);
          }
          contentType = contentType.trim();

          EncodingEnum encoding = EncodingEnum.forContentType(contentType);
          if (encoding != null) {
            byte[] requestContents = myRequestDetails.loadRequestContents();
            return new String(requestContents, Charsets.UTF_8);
          }
        }
        return "";
      }

      return "!VAL!";
    }