Ejemplo n.º 1
0
  @Test
  public void shouldSearchForExistingGroupBeforeUpdating() throws Exception {
    FlwGroup toBeUpdatedGroup =
        new FlwGroupBuilder()
            .groupId("5ba9a0928dde95d187544babf6c0ad24")
            .name("afrisis team 1")
            .domain("care-bihar")
            .awcCode("001")
            .caseSharing(true)
            .reporting(true)
            .build();
    FlwGroup notToBeUpdatedGroup =
        flwGroupWithNameAndId("5ba9a0928dde95d187544babf6c0af36", "ashok team 1");

    template.saveOrUpdateAll(Arrays.asList(toBeUpdatedGroup, notToBeUpdatedGroup));

    FlwGroup updatedGroup = updatedGroup();

    careService.saveOrUpdateAllByExternalPrimaryKey(FlwGroup.class, Arrays.asList(updatedGroup));

    FlwGroup loadedFlwGroup = template.load(FlwGroup.class, toBeUpdatedGroup.getId());
    FlwGroup unchangedFlwGroup = template.load(FlwGroup.class, notToBeUpdatedGroup.getId());
    assertReflectionEqualsWithIgnore(
        updatedGroup(), loadedFlwGroup, new String[] {"id", "creationTime", "lastModifiedTime"});
    assertDateIgnoringSeconds(new Date(), loadedFlwGroup.getCreationTime());
    assertDateIgnoringSeconds(new Date(), loadedFlwGroup.getLastModifiedTime());
    assertEquals("ashok team 1", unchangedFlwGroup.getName());
  }
  public static SafeDeleteProcessor createInstance(
      Project project,
      @Nullable Runnable prepareSuccessfulCallBack,
      PsiElement[] elementsToDelete,
      boolean isSearchInComments,
      boolean isSearchNonJava,
      boolean askForAccessors) {
    ArrayList<PsiElement> elements = new ArrayList<PsiElement>(Arrays.asList(elementsToDelete));
    HashSet<PsiElement> elementsToDeleteSet =
        new HashSet<PsiElement>(Arrays.asList(elementsToDelete));

    for (PsiElement psiElement : elementsToDelete) {
      for (SafeDeleteProcessorDelegate delegate :
          Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
        if (delegate.handlesElement(psiElement)) {
          Collection<PsiElement> addedElements =
              delegate.getAdditionalElementsToDelete(
                  psiElement, elementsToDeleteSet, askForAccessors);
          if (addedElements != null) {
            elements.addAll(addedElements);
          }
          break;
        }
      }
    }

    return new SafeDeleteProcessor(
        project,
        prepareSuccessfulCallBack,
        PsiUtilCore.toPsiElementArray(elements),
        isSearchInComments,
        isSearchNonJava);
  }
Ejemplo n.º 3
0
 private Expr nud(Token tk) {
   System.err.println(tab(depth) + "nud " + tk);
   if (is(tk, Token.Type.SYM, "-")) {
     depth++;
     Expr expr = expr(100);
     depth--;
     return new Expr.EAp(new Expr.EName("-/1"), expr); // unary minus
   } else if (is(tk, Token.Type.NUM)) {
     return new Expr.ENum(Integer.parseInt(tk.text));
   } else if (is(tk, Token.Type.NAME)) {
     return new Expr.EName(tk.text);
   } else if (is(tk, Token.Type.SYM, "(")) {
     depth++;
     Expr res = expr(1);
     depth--;
     expect(Token.Type.SYM, ")");
     return res;
   } else if (is(tk, Token.Type.KEYWORD, "if")) {
     depth++;
     Expr cond = expr(1);
     depth--;
     expect(Token.Type.KEYWORD, "then");
     depth++;
     Expr thenArm = expr(1);
     depth--;
     expect(Token.Type.KEYWORD, "else");
     depth++;
     Expr elseArm = expr(1);
     depth--;
     return new Expr.EIf(cond, Arrays.asList(thenArm), Arrays.asList(elseArm));
   } else {
     throw new IllegalArgumentException("Invalid symbol found " + tk);
   }
 }
Ejemplo n.º 4
0
  /**
   * Tests a simple split: {A,B} and {C,D} need to merge back into one subgroup. Checks how many
   * MergeViews are installed
   */
  public void testSplitInTheMiddle2() throws Exception {
    View v1 = View.create(a.getAddress(), 10, a.getAddress(), b.getAddress());
    View v2 = View.create(c.getAddress(), 10, c.getAddress(), d.getAddress());
    injectView(v1, a, b);
    injectView(v2, c, d);
    enableInfoSender(false, a, b, c, d);
    Util.waitUntilAllChannelsHaveSameSize(10000, 500, a, b);
    Util.waitUntilAllChannelsHaveSameSize(10000, 500, c, d);
    enableInfoSender(false, a, b, c, d);
    for (JChannel ch : Arrays.asList(a, b, c, d))
      System.out.println(ch.getName() + ": " + ch.getView());
    System.out.println("\nEnabling INFO sending in merge protocols to merge subclusters");
    enableInfoSender(true, a, b, c, d);

    Util.waitUntilAllChannelsHaveSameSize(30000, 1000, a, b, c, d);
    System.out.println("\nResulting views:");
    for (JChannel ch : Arrays.asList(a, b, c, d)) {
      GMS gms = (GMS) ch.getProtocolStack().findProtocol(GMS.class);
      View mv = gms.view();
      System.out.println(mv);
    }
    for (JChannel ch : Arrays.asList(a, b, c, d)) {
      GMS gms = (GMS) ch.getProtocolStack().findProtocol(GMS.class);
      View mv = gms.view();
      assert mv instanceof MergeView;
      assert mv.size() == 4;
      assert ((MergeView) mv).getSubgroups().size() == 2;
    }
    for (JChannel ch : Arrays.asList(a, b, c, d)) {
      View view = ch.getView();
      assert view.size() == 4 : "view should have 4 members: " + view;
    }
  }
Ejemplo n.º 5
0
 public static void main(String[] args) {
   LetterToSound text = LetterToSound.getInstance();
   System.out.println(Arrays.asList(text.getPhones("laggin", "n")));
   System.out.println(Arrays.asList(text.getPhones("dragon", "n")));
   System.out.println(Arrays.asList(text.getPhones("hello", "n")));
   // System.out.println(Arrays.asList(text.getPhones("antelope", "n")));
 }
  public static Set<Artifact> getArtifactsToBuild(
      final Project project,
      final CompileScope compileScope,
      final boolean addIncludedArtifactsWithOutputPathsOnly) {
    final Artifact[] artifactsFromScope = getArtifacts(compileScope);
    final ArtifactManager artifactManager = ArtifactManager.getInstance(project);
    PackagingElementResolvingContext context = artifactManager.getResolvingContext();
    if (artifactsFromScope != null) {
      return addIncludedArtifacts(
          Arrays.asList(artifactsFromScope), context, addIncludedArtifactsWithOutputPathsOnly);
    }

    final Set<Artifact> cached = compileScope.getUserData(CACHED_ARTIFACTS_KEY);
    if (cached != null) {
      return cached;
    }

    Set<Artifact> artifacts = new HashSet<Artifact>();
    final Set<Module> modules =
        new HashSet<Module>(Arrays.asList(compileScope.getAffectedModules()));
    final List<Module> allModules = Arrays.asList(ModuleManager.getInstance(project).getModules());
    for (Artifact artifact : artifactManager.getArtifacts()) {
      if (artifact.isBuildOnMake()) {
        if (modules.containsAll(allModules) || containsModuleOutput(artifact, modules, context)) {
          artifacts.add(artifact);
        }
      }
    }
    Set<Artifact> result =
        addIncludedArtifacts(artifacts, context, addIncludedArtifactsWithOutputPathsOnly);
    compileScope.putUserData(CACHED_ARTIFACTS_KEY, result);
    return result;
  }
Ejemplo n.º 7
0
  /**
   * Creates a java process that executes the given main class and waits for the process to
   * terminate.
   *
   * @return a {@link ProcessOutputReader} that can be used to get the exit code and stdout+stderr
   *     of the terminated process.
   */
  public static ProcessOutputReader fg(Class main, String[] vmArgs, String[] mainArgs)
      throws IOException {
    File javabindir = new File(System.getProperty("java.home"), "bin");
    File javaexe = new File(javabindir, "java");

    int bits = Integer.getInteger("sun.arch.data.model", 0).intValue();
    String vmKindArg = (bits == 64) ? "-d64" : null;

    ArrayList argList = new ArrayList();
    argList.add(javaexe.getPath());
    if (vmKindArg != null) {
      argList.add(vmKindArg);
    }
    // argList.add("-Dgemfire.systemDirectory=" +
    // GemFireConnectionFactory.getDefaultSystemDirectory());
    argList.add("-Djava.class.path=" + System.getProperty("java.class.path"));
    argList.add("-Djava.library.path=" + System.getProperty("java.library.path"));
    if (vmArgs != null) {
      argList.addAll(Arrays.asList(vmArgs));
    }
    argList.add(main.getName());
    if (mainArgs != null) {
      argList.addAll(Arrays.asList(mainArgs));
    }
    String[] cmd = (String[]) argList.toArray(new String[argList.size()]);
    return new ProcessOutputReader(Runtime.getRuntime().exec(cmd));
  }
Ejemplo n.º 8
0
 /**
  * @deprecated (3.1) remove this test when lucene 3.0 "broken unicode 4" support is no longer
  *     needed.
  */
 @Deprecated
 public void testSupplementaryCharsBWCompat() {
   String missing = "Term %s is missing in the set";
   String falsePos = "Term %s is in the set but shouldn't";
   // for reference see
   // http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[[%3ACase_Sensitive%3DTrue%3A]%26[^[\u0000-\uFFFF]]]&esc=on
   String[] upperArr =
       new String[] {"Abc\ud801\udc1c", "\ud801\udc1c\ud801\udc1cCDE", "A\ud801\udc1cB"};
   String[] lowerArr =
       new String[] {"abc\ud801\udc44", "\ud801\udc44\ud801\udc44cde", "a\ud801\udc44b"};
   CharArraySet set = new CharArraySet(Version.LUCENE_3_0, Arrays.asList(TEST_STOP_WORDS), true);
   for (String upper : upperArr) {
     set.add(upper);
   }
   for (int i = 0; i < upperArr.length; i++) {
     assertTrue(String.format(Locale.ROOT, missing, upperArr[i]), set.contains(upperArr[i]));
     assertFalse(String.format(Locale.ROOT, falsePos, lowerArr[i]), set.contains(lowerArr[i]));
   }
   set = new CharArraySet(Version.LUCENE_3_0, Arrays.asList(TEST_STOP_WORDS), false);
   for (String upper : upperArr) {
     set.add(upper);
   }
   for (int i = 0; i < upperArr.length; i++) {
     assertTrue(String.format(Locale.ROOT, missing, upperArr[i]), set.contains(upperArr[i]));
     assertFalse(String.format(Locale.ROOT, falsePos, lowerArr[i]), set.contains(lowerArr[i]));
   }
 }
Ejemplo n.º 9
0
  /**
   * @deprecated (3.1) remove this test when lucene 3.0 "broken unicode 4" support is no longer
   *     needed.
   */
  @Deprecated
  public void testSingleHighSurrogateBWComapt() {
    String missing = "Term %s is missing in the set";
    String falsePos = "Term %s is in the set but shouldn't";
    String[] upperArr =
        new String[] {"ABC\uD800", "ABC\uD800EfG", "\uD800EfG", "\uD800\ud801\udc1cB"};

    String[] lowerArr =
        new String[] {"abc\uD800", "abc\uD800efg", "\uD800efg", "\uD800\ud801\udc44b"};
    CharArraySet set = new CharArraySet(Version.LUCENE_3_0, Arrays.asList(TEST_STOP_WORDS), true);
    for (String upper : upperArr) {
      set.add(upper);
    }
    for (int i = 0; i < upperArr.length; i++) {
      assertTrue(String.format(Locale.ROOT, missing, upperArr[i]), set.contains(upperArr[i]));
      if (i == lowerArr.length - 1)
        assertFalse(String.format(Locale.ROOT, falsePos, lowerArr[i]), set.contains(lowerArr[i]));
      else assertTrue(String.format(Locale.ROOT, missing, lowerArr[i]), set.contains(lowerArr[i]));
    }
    set = new CharArraySet(Version.LUCENE_3_0, Arrays.asList(TEST_STOP_WORDS), false);
    for (String upper : upperArr) {
      set.add(upper);
    }
    for (int i = 0; i < upperArr.length; i++) {
      assertTrue(String.format(Locale.ROOT, missing, upperArr[i]), set.contains(upperArr[i]));
      assertFalse(String.format(Locale.ROOT, falsePos, lowerArr[i]), set.contains(lowerArr[i]));
    }
  }
Ejemplo n.º 10
0
 @Test
 public void testTake() {
   List<String> data = Arrays.asList("hello", "world");
   Dataset<String> ds = context.createDataset(data, Encoders.STRING());
   List<String> collected = ds.takeAsList(1);
   Assert.assertEquals(Arrays.asList("hello"), collected);
 }
Ejemplo n.º 11
0
  @Test
  public void testWrongRouting() throws Exception {

    expectedException.expect(UnhandledServerException.class);
    expectedException.expectMessage("unsupported routing");

    CollectPhase collectNode =
        new CollectPhase(
            UUID.randomUUID(),
            0,
            "wrong",
            new Routing(
                TreeMapBuilder.<String, Map<String, List<Integer>>>newMapBuilder()
                    .put(
                        "bla",
                        TreeMapBuilder.<String, List<Integer>>newMapBuilder()
                            .put("my_index", Arrays.asList(1))
                            .put("my_index", Arrays.asList(1))
                            .map())
                    .map()),
            ImmutableList.<Symbol>of(),
            EMPTY_PROJECTIONS);
    collectNode.maxRowGranularity(RowGranularity.DOC);
    operation.collect(collectNode, new CollectingProjector(), null);
  }
Ejemplo n.º 12
0
  @Test
  public void testTypedAggregation() {
    Encoder<Tuple2<String, Integer>> encoder = Encoders.tuple(Encoders.STRING(), Encoders.INT());
    List<Tuple2<String, Integer>> data =
        Arrays.asList(tuple2("a", 1), tuple2("a", 2), tuple2("b", 3));
    Dataset<Tuple2<String, Integer>> ds = context.createDataset(data, encoder);

    GroupedDataset<String, Tuple2<String, Integer>> grouped =
        ds.groupBy(
            new MapFunction<Tuple2<String, Integer>, String>() {
              @Override
              public String call(Tuple2<String, Integer> value) throws Exception {
                return value._1();
              }
            },
            Encoders.STRING());

    Dataset<Tuple2<String, Integer>> agged =
        grouped.agg(new IntSumOf().toColumn(Encoders.INT(), Encoders.INT()));
    Assert.assertEquals(Arrays.asList(tuple2("a", 3), tuple2("b", 3)), agged.collectAsList());

    Dataset<Tuple2<String, Integer>> agged2 =
        grouped
            .agg(new IntSumOf().toColumn(Encoders.INT(), Encoders.INT()))
            .as(Encoders.tuple(Encoders.STRING(), Encoders.INT()));
    Assert.assertEquals(
        Arrays.asList(new Tuple2<>("a", 3), new Tuple2<>("b", 3)), agged2.collectAsList());
  }
Ejemplo n.º 13
0
  @Test
  public void testNestedTupleEncoder() {
    // test ((int, string), string)
    Encoder<Tuple2<Tuple2<Integer, String>, String>> encoder =
        Encoders.tuple(Encoders.tuple(Encoders.INT(), Encoders.STRING()), Encoders.STRING());
    List<Tuple2<Tuple2<Integer, String>, String>> data =
        Arrays.asList(tuple2(tuple2(1, "a"), "a"), tuple2(tuple2(2, "b"), "b"));
    Dataset<Tuple2<Tuple2<Integer, String>, String>> ds = context.createDataset(data, encoder);
    Assert.assertEquals(data, ds.collectAsList());

    // test (int, (string, string, long))
    Encoder<Tuple2<Integer, Tuple3<String, String, Long>>> encoder2 =
        Encoders.tuple(
            Encoders.INT(), Encoders.tuple(Encoders.STRING(), Encoders.STRING(), Encoders.LONG()));
    List<Tuple2<Integer, Tuple3<String, String, Long>>> data2 =
        Arrays.asList(tuple2(1, new Tuple3<String, String, Long>("a", "b", 3L)));
    Dataset<Tuple2<Integer, Tuple3<String, String, Long>>> ds2 =
        context.createDataset(data2, encoder2);
    Assert.assertEquals(data2, ds2.collectAsList());

    // test (int, ((string, long), string))
    Encoder<Tuple2<Integer, Tuple2<Tuple2<String, Long>, String>>> encoder3 =
        Encoders.tuple(
            Encoders.INT(),
            Encoders.tuple(Encoders.tuple(Encoders.STRING(), Encoders.LONG()), Encoders.STRING()));
    List<Tuple2<Integer, Tuple2<Tuple2<String, Long>, String>>> data3 =
        Arrays.asList(tuple2(1, tuple2(tuple2("a", 2L), "b")));
    Dataset<Tuple2<Integer, Tuple2<Tuple2<String, Long>, String>>> ds3 =
        context.createDataset(data3, encoder3);
    Assert.assertEquals(data3, ds3.collectAsList());
  }
Ejemplo n.º 14
0
  @Test
  public void testTupleEncoder() {
    Encoder<Tuple2<Integer, String>> encoder2 = Encoders.tuple(Encoders.INT(), Encoders.STRING());
    List<Tuple2<Integer, String>> data2 = Arrays.asList(tuple2(1, "a"), tuple2(2, "b"));
    Dataset<Tuple2<Integer, String>> ds2 = context.createDataset(data2, encoder2);
    Assert.assertEquals(data2, ds2.collectAsList());

    Encoder<Tuple3<Integer, Long, String>> encoder3 =
        Encoders.tuple(Encoders.INT(), Encoders.LONG(), Encoders.STRING());
    List<Tuple3<Integer, Long, String>> data3 =
        Arrays.asList(new Tuple3<Integer, Long, String>(1, 2L, "a"));
    Dataset<Tuple3<Integer, Long, String>> ds3 = context.createDataset(data3, encoder3);
    Assert.assertEquals(data3, ds3.collectAsList());

    Encoder<Tuple4<Integer, String, Long, String>> encoder4 =
        Encoders.tuple(Encoders.INT(), Encoders.STRING(), Encoders.LONG(), Encoders.STRING());
    List<Tuple4<Integer, String, Long, String>> data4 =
        Arrays.asList(new Tuple4<Integer, String, Long, String>(1, "b", 2L, "a"));
    Dataset<Tuple4<Integer, String, Long, String>> ds4 = context.createDataset(data4, encoder4);
    Assert.assertEquals(data4, ds4.collectAsList());

    Encoder<Tuple5<Integer, String, Long, String, Boolean>> encoder5 =
        Encoders.tuple(
            Encoders.INT(),
            Encoders.STRING(),
            Encoders.LONG(),
            Encoders.STRING(),
            Encoders.BOOLEAN());
    List<Tuple5<Integer, String, Long, String, Boolean>> data5 =
        Arrays.asList(new Tuple5<Integer, String, Long, String, Boolean>(1, "b", 2L, "a", true));
    Dataset<Tuple5<Integer, String, Long, String, Boolean>> ds5 =
        context.createDataset(data5, encoder5);
    Assert.assertEquals(data5, ds5.collectAsList());
  }
Ejemplo n.º 15
0
  @Test
  public void search_by_any_of_statuses() throws InterruptedException {
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setStatus(RuleStatus.BETA));
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setStatus(RuleStatus.READY));
    dbSession.commit();

    RuleQuery query =
        new RuleQuery().setStatuses(Arrays.asList(RuleStatus.DEPRECATED, RuleStatus.READY));
    Result<Rule> results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");

    // no results
    query = new RuleQuery().setStatuses(Arrays.asList(RuleStatus.DEPRECATED));
    assertThat(index.search(query, new QueryContext()).getHits()).isEmpty();

    // empty list => no filter
    query = new RuleQuery().setStatuses(Collections.<RuleStatus>emptyList());
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);

    // null list => no filter
    query = new RuleQuery().setStatuses(null);
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);
  }
Ejemplo n.º 16
0
  /** Test the static #copy() function with a JDK {@link Set} as a source */
  public void testCopyJDKSet() {
    Set<String> set = new HashSet<>();

    List<String> stopwords = Arrays.asList(TEST_STOP_WORDS);
    List<String> stopwordsUpper = new ArrayList<>();
    for (String string : stopwords) {
      stopwordsUpper.add(string.toUpperCase(Locale.ROOT));
    }
    set.addAll(Arrays.asList(TEST_STOP_WORDS));

    CharArraySet copy = CharArraySet.copy(TEST_VERSION_CURRENT, set);

    assertEquals(set.size(), copy.size());
    assertEquals(set.size(), copy.size());

    assertTrue(copy.containsAll(stopwords));
    for (String string : stopwordsUpper) {
      assertFalse(copy.contains(string));
    }

    List<String> newWords = new ArrayList<>();
    for (String string : stopwords) {
      newWords.add(string + "_1");
    }
    copy.addAll(newWords);

    assertTrue(copy.containsAll(stopwords));
    assertTrue(copy.containsAll(newWords));
    // new added terms are not in the source set
    for (String string : newWords) {
      assertFalse(set.contains(string));
    }
  }
Ejemplo n.º 17
0
  public MainPanel() {
    super(new BorderLayout());
    JPanel p = new JPanel(new GridLayout(2, 1));
    final JComboBox<String> c0 = makeComboBox(true, false);
    final JComboBox<String> c1 = makeComboBox(false, false);
    final JComboBox<String> c2 = makeComboBox(true, true);
    final JComboBox<String> c3 = makeComboBox(false, true);

    p.add(makeTitlePanel("setEditable(false)", Arrays.asList(c0, c1)));
    p.add(makeTitlePanel("setEditable(true)", Arrays.asList(c2, c3)));
    p.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    add(p, BorderLayout.NORTH);
    add(
        new JButton(
            new AbstractAction("add") {
              @Override
              public void actionPerformed(ActionEvent e) {
                String str = new Date().toString();
                for (JComboBox<String> c : Arrays.asList(c0, c1, c2, c3)) {
                  MutableComboBoxModel<String> m = (MutableComboBoxModel<String>) c.getModel();
                  m.insertElementAt(str, m.getSize());
                }
              }
            }),
        BorderLayout.SOUTH);
    setPreferredSize(new Dimension(320, 240));
  }
Ejemplo n.º 18
0
  public static Set<HttpResponse> getResult() {
    final HttpResponse result = new HttpResponse();

    result.getStatuses().addAll(Arrays.asList(200, 433));
    result.getEntityTypes().addAll(Arrays.asList("java.lang.Double"));
    result
        .getHeaders()
        .addAll(
            Arrays.asList(
                "X-Test",
                "Cache-Control",
                "Set-Cookie",
                "Expires",
                "Content-Language",
                "Content-Encoding",
                "Last-Modified",
                "Link",
                "Location",
                "ETag",
                "Vary",
                "Content-Location"));
    result.getContentTypes().add("application/json");

    return Collections.singleton(result);
  }
Ejemplo n.º 19
0
  @Test
  public void post() throws Exception {
    given(connection.getURL()).willReturn(new URL(URL));
    given(connection.getResponseCode()).willReturn(200);
    given(connection.getResponseMessage()).willReturn("OK");
    Map<String, List<String>> responseHeaderFields = new LinkedHashMap<String, List<String>>();
    responseHeaderFields.put("Set-Cookie", Arrays.asList("aaa"));
    given(connection.getHeaderFields()).willReturn(responseHeaderFields);

    Request request =
        new Request(
            "POST",
            URL,
            Arrays.asList(new Header("Hoge", "Piyo")),
            new FormUrlEncodedTypedOutput().addField("foo", "bar"));

    Response response = underTest.execute(request);

    verify(connection).setRequestMethod("POST");
    verify(connection).addRequestProperty("Hoge", "Piyo");
    verify(connection).getOutputStream();

    assertThat(response.getUrl()).isEqualTo(URL);
    assertThat(response.getStatus()).isEqualTo(200);
    assertThat(response.getReason()).isEqualTo("OK");
    assertThat(response.getHeaders()).isEqualTo(Arrays.asList(new Header("Set-Cookie", "aaa")));
    assertThat(output.toString("UTF-8")).isEqualTo("foo=bar");
  }
Ejemplo n.º 20
0
 private void processResponseOnExport(ClientResponse response, ExchangeContext context)
     throws Exception {
   context.setVariable("smevPool", false);
   String exportType = getStringFromContext(context, "exportRequestType", "");
   addAdditionalXmlSchema(response, exportType);
   ExportDataResponse exportDataResponse =
       (ExportDataResponse)
           new XmlTypes(ExportDataResponse.class).toBean(response.appData.getFirstChild());
   if (exportDataResponse.getResponseTemplate().getRequestProcessResult() != null) {
     context.setVariable("responseSuccess", false);
     String errorCode =
         exportDataResponse.getResponseTemplate().getRequestProcessResult().getErrorCode();
     processInternalErrorService(context, errorCode);
     context.setVariable("requestProcessResultErrorCode", errorCode);
     context.setVariable(
         "requestProcessResultErrorDescription",
         exportDataResponse.getResponseTemplate().getRequestProcessResult().getErrorDescription());
   } else {
     context.setVariable("responseSuccess", true);
     if ("QUITTANCE".equals(exportType)) {
       processExportQuittanceResponse(context, exportDataResponse);
     } else if (Arrays.asList("CHARGE", "CHARGESTATUS", "CHARGENOTFULLMATCHED")
         .contains(exportType)) {
       processExportChargeResponse(context, exportDataResponse);
     } else if (Arrays.asList("PAYMENT", "PAYMENTMODIFIED", "PAYMENTUNMATCHED")
         .contains(exportType)) {
       processExportPaymentResponse(context, exportDataResponse);
     } else {
       throw new IllegalArgumentException("Unknown export type " + exportType);
     }
   }
 }
Ejemplo n.º 21
0
  public static LinkedHashSet<String> findJars(LogicalPlan dag, Class<?>[] defaultClasses) {
    List<Class<?>> jarClasses = new ArrayList<Class<?>>();

    for (String className : dag.getClassNames()) {
      try {
        Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        jarClasses.add(clazz);
      } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("Failed to load class " + className, e);
      }
    }

    for (Class<?> clazz : Lists.newArrayList(jarClasses)) {
      // process class and super classes (super does not require deploy annotation)
      for (Class<?> c = clazz; c != Object.class && c != null; c = c.getSuperclass()) {
        // LOG.debug("checking " + c);
        jarClasses.add(c);
        jarClasses.addAll(Arrays.asList(c.getInterfaces()));
      }
    }

    jarClasses.addAll(Arrays.asList(defaultClasses));

    if (dag.isDebug()) {
      LOG.debug("Deploy dependencies: {}", jarClasses);
    }

    LinkedHashSet<String> localJarFiles = new LinkedHashSet<String>(); // avoid duplicates
    HashMap<String, String> sourceToJar = new HashMap<String, String>();

    for (Class<?> jarClass : jarClasses) {
      if (jarClass.getProtectionDomain().getCodeSource() == null) {
        // system class
        continue;
      }
      String sourceLocation =
          jarClass.getProtectionDomain().getCodeSource().getLocation().toString();
      String jar = sourceToJar.get(sourceLocation);
      if (jar == null) {
        // don't create jar file from folders multiple times
        jar = JarFinder.getJar(jarClass);
        sourceToJar.put(sourceLocation, jar);
        LOG.debug("added sourceLocation {} as {}", sourceLocation, jar);
      }
      if (jar == null) {
        throw new AssertionError("Cannot resolve jar file for " + jarClass);
      }
      localJarFiles.add(jar);
    }

    String libJarsPath = dag.getValue(LogicalPlan.LIBRARY_JARS);
    if (!StringUtils.isEmpty(libJarsPath)) {
      String[] libJars = StringUtils.splitByWholeSeparator(libJarsPath, LIB_JARS_SEP);
      localJarFiles.addAll(Arrays.asList(libJars));
    }

    LOG.info("Local jar file dependencies: " + localJarFiles);

    return localJarFiles;
  }
Ejemplo n.º 22
0
  private static void patchGtkDefaults(UIDefaults defaults) {
    if (!UIUtil.isUnderGTKLookAndFeel()) return;

    Map<String, Icon> map =
        ContainerUtil.newHashMap(
            Arrays.asList(
                "OptionPane.errorIcon",
                "OptionPane.informationIcon",
                "OptionPane.warningIcon",
                "OptionPane.questionIcon"),
            Arrays.asList(
                AllIcons.General.ErrorDialog,
                AllIcons.General.InformationDialog,
                AllIcons.General.WarningDialog,
                AllIcons.General.QuestionDialog));
    // GTK+ L&F keeps icons hidden in style
    SynthStyle style = SynthLookAndFeel.getStyle(new JOptionPane(""), Region.DESKTOP_ICON);
    for (String key : map.keySet()) {
      if (defaults.get(key) != null) continue;

      Object icon = style == null ? null : style.get(null, key);
      defaults.put(key, icon instanceof Icon ? icon : map.get(key));
    }

    Color fg = defaults.getColor("Label.foreground");
    Color bg = defaults.getColor("Label.background");
    if (fg != null && bg != null) {
      defaults.put("Label.disabledForeground", UIUtil.mix(fg, bg, 0.5));
    }
  }
Ejemplo n.º 23
0
  /**
   * Tests A|6, A|7, A|8 and B|7, B|8, B|9 -> we should have a subviews in MergeView consisting of
   * only 2 elements: A|5 and B|5
   */
  public void testMultipleViewsBySameMembers() throws Exception {
    View a1 =
        View.create(
            a.getAddress(),
            6,
            a.getAddress(),
            b.getAddress(),
            c.getAddress(),
            d.getAddress()); // {A,B,C,D}
    View a2 =
        View.create(a.getAddress(), 7, a.getAddress(), b.getAddress(), c.getAddress()); // {A,B,C}
    View a3 = View.create(a.getAddress(), 8, a.getAddress(), b.getAddress()); // {A,B}
    View a4 = View.create(a.getAddress(), 9, a.getAddress()); // {A}

    View b1 = View.create(b.getAddress(), 7, b.getAddress(), c.getAddress(), d.getAddress());
    View b2 = View.create(b.getAddress(), 8, b.getAddress(), c.getAddress());
    View b3 = View.create(b.getAddress(), 9, b.getAddress());

    Util.close(c, d); // not interested in those...

    // A and B cannot communicate:
    discard(true, a, b);

    // inject view A|6={A} into A and B|5={B} into B
    injectView(a4, a);
    injectView(b3, b);

    assert a.getView().equals(a4);
    assert b.getView().equals(b3);

    List<Event> merge_events = new ArrayList<>();
    for (View view : Arrays.asList(a3, a4, a2, a1)) {
      MERGE3.MergeHeader hdr = MERGE3.MergeHeader.createInfo(view.getViewId(), null, null);
      Message msg = new Message(null, a.getAddress(), null).putHeader(merge_id, hdr);
      merge_events.add(new Event(Event.MSG, msg));
    }
    for (View view : Arrays.asList(b2, b3, b1)) {
      MERGE3.MergeHeader hdr = MERGE3.MergeHeader.createInfo(view.getViewId(), null, null);
      Message msg = new Message(null, b.getAddress(), null).putHeader(merge_id, hdr);
      merge_events.add(new Event(Event.MSG, msg));
    }

    // A and B can communicate again
    discard(false, a, b);

    injectMergeEvents(merge_events, a, b);
    checkInconsistencies(a, b); // merge will happen between A and B
    Util.waitUntilAllChannelsHaveSameSize(10000, 500, a, b);
    System.out.println("A's view: " + a.getView() + "\nB's view: " + b.getView());
    assert a.getView().size() == 2;
    assert a.getView().containsMember(a.getAddress());
    assert a.getView().containsMember(b.getAddress());
    assert a.getView().equals(b.getView());
    for (View merge_view : Arrays.asList(getViewFromGMS(a), getViewFromGMS(b))) {
      System.out.println(merge_view);
      assert merge_view instanceof MergeView;
      List<View> subviews = ((MergeView) merge_view).getSubgroups();
      assert subviews.size() == 2;
    }
  }
Ejemplo n.º 24
0
  public static void testAllEqual() {
    Address[] mbrs = Util.createRandomAddresses(5);
    View[] views = {
      View.create(mbrs[0], 1, mbrs), View.create(mbrs[0], 1, mbrs), View.create(mbrs[0], 1, mbrs)
    };

    boolean same = Util.allEqual(Arrays.asList(views));
    System.out.println("views=" + Arrays.toString(views) + ", same = " + same);
    assert same;

    views =
        new View[] {
          View.create(mbrs[0], 1, mbrs),
          View.create(mbrs[0], 2, mbrs),
          View.create(mbrs[0], 1, mbrs)
        };
    same = Util.allEqual(Arrays.asList(views));
    System.out.println("views=" + Arrays.toString(views) + ", same = " + same);
    assert !same;

    views =
        new View[] {
          View.create(mbrs[1], 1, mbrs),
          View.create(mbrs[0], 1, mbrs),
          View.create(mbrs[0], 1, mbrs)
        };
    same = Util.allEqual(Arrays.asList(views));
    System.out.println("views=" + Arrays.toString(views) + ", same = " + same);
    assert !same;
  }
    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      AllowedValues a2 = (AllowedValues) o;
      if (canBeOred != a2.canBeOred) {
        return false;
      }
      Set<PsiAnnotationMemberValue> v1 =
          new THashSet<PsiAnnotationMemberValue>(Arrays.asList(values));
      Set<PsiAnnotationMemberValue> v2 =
          new THashSet<PsiAnnotationMemberValue>(Arrays.asList(a2.values));
      if (v1.size() != v2.size()) {
        return false;
      }
      for (PsiAnnotationMemberValue value : v1) {
        for (PsiAnnotationMemberValue value2 : v2) {
          if (same(value, value2, value.getManager())) {
            v2.remove(value2);
            break;
          }
        }
      }
      return v2.isEmpty();
    }
  protected Result describeMbean(
      @Nonnull MBeanServerConnection mbeanServer, @Nonnull ObjectName objectName)
      throws IntrospectionException, ReflectionException, InstanceNotFoundException, IOException {
    MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName);
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    out.println("# MBEAN");
    out.println(objectName.toString());
    out.println();
    out.println("## OPERATIONS");
    List<MBeanOperationInfo> operations = Arrays.asList(mbeanInfo.getOperations());
    Collections.sort(
        operations,
        new Comparator<MBeanOperationInfo>() {
          @Override
          public int compare(MBeanOperationInfo o1, MBeanOperationInfo o2) {
            return o1.getName().compareTo(o1.getName());
          }
        });

    for (MBeanOperationInfo opInfo : operations) {
      out.print("* " + opInfo.getName() + "(");
      MBeanParameterInfo[] signature = opInfo.getSignature();
      for (int i = 0; i < signature.length; i++) {
        MBeanParameterInfo paramInfo = signature[i];
        out.print(paramInfo.getType() + " " + paramInfo.getName());
        if (i < signature.length - 1) {
          out.print(", ");
        }
      }

      out.print("):" + opInfo.getReturnType() /* + " - " + opInfo.getDescription() */);
      out.println();
    }
    out.println();
    out.println("## ATTRIBUTES");
    List<MBeanAttributeInfo> attributes = Arrays.asList(mbeanInfo.getAttributes());
    Collections.sort(
        attributes,
        new Comparator<MBeanAttributeInfo>() {
          @Override
          public int compare(MBeanAttributeInfo o1, MBeanAttributeInfo o2) {
            return o1.getName().compareTo(o2.getName());
          }
        });
    for (MBeanAttributeInfo attrInfo : attributes) {
      out.println(
          "* "
              + attrInfo.getName()
              + ": "
              + attrInfo.getType()
              + " - "
              + (attrInfo.isReadable() ? "r" : "")
              + (attrInfo.isWritable() ? "w" : "") /* + " - " +
                    attrInfo.getDescription() */);
    }

    String description = sw.getBuffer().toString();
    return new Result(objectName, description, description);
  }
  @Test
  public void testPutMappingsWithBlocks() throws Exception {
    createIndex("test");
    ensureGreen();

    for (String block : Arrays.asList(SETTING_BLOCKS_READ, SETTING_BLOCKS_WRITE)) {
      try {
        enableIndexBlock("test", block);
        assertAcked(
            client()
                .admin()
                .indices()
                .preparePutMapping("test")
                .setType("doc")
                .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}"));
      } finally {
        disableIndexBlock("test", block);
      }
    }

    for (String block : Arrays.asList(SETTING_READ_ONLY, SETTING_BLOCKS_METADATA)) {
      try {
        enableIndexBlock("test", block);
        assertBlocked(
            client()
                .admin()
                .indices()
                .preparePutMapping("test")
                .setType("doc")
                .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}"));
      } finally {
        disableIndexBlock("test", block);
      }
    }
  }
Ejemplo n.º 28
0
  @Test
  public void search_by_any_of_severities() throws InterruptedException {
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setSeverity(Severity.BLOCKER));
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setSeverity(Severity.INFO));
    dbSession.commit();

    RuleQuery query = new RuleQuery().setSeverities(Arrays.asList(Severity.INFO, Severity.MINOR));
    Result<Rule> results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");

    // no results
    query = new RuleQuery().setSeverities(Arrays.asList(Severity.MINOR));
    assertThat(index.search(query, new QueryContext()).getHits()).isEmpty();

    // empty list => no filter
    query = new RuleQuery().setSeverities(Collections.<String>emptyList());
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);

    // null list => no filter
    query = new RuleQuery().setSeverities(null);
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);
  }
  /** Test for creating zobjects with relationships */
  @Test
  @SuppressWarnings("serial")
  public void createAndDeleteRelated() throws Exception {
    SaveResult saveResult =
        module.create(ZObjectType.Account, Collections.singletonList(testAccount())).get(0);
    assertTrue(saveResult.isSuccess());

    final String accountId = saveResult.getId();
    try {
      SaveResult result =
          module
              .create(
                  ZObjectType.Contact,
                  Collections.<Map<String, Object>>singletonList(
                      new HashMap<String, Object>() {
                        {
                          put("Country", "US");
                          put("FirstName", "John");
                          put("LastName", "Doe");
                          put("AccountId", accountId);
                        }
                      }))
              .get(0);
      assertTrue(result.isSuccess());

      DeleteResult deleteResult =
          module.delete(ZObjectType.Contact, Arrays.asList(result.getId())).get(0);
      assertTrue(deleteResult.isSuccess());
    } finally {
      module.delete(ZObjectType.Account, Arrays.asList(accountId)).get(0);
    }
  }
  /**
   * Constructor.
   *
   * @param ee comma separated list of execution environments names.
   * @throws PlatformException - If encountered during reading of profiles - If profile cannot be
   *     found or determined
   */
  ExecutionEnvironment(final String ee) throws PlatformException {
    // we make an union of the packages form each ee so let's have a unique set for it
    final Set<String> uniquePackages = new TreeSet<String>();
    final Set<String> uniqueEE = new TreeSet<String>();

    for (String segment : ee.split(",")) {
      try {
        final Properties profile = new Properties();
        profile.load(discoverExecutionEnvironmentURL(segment).openStream());

        final String systemPackagesProp =
            profile.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES, "");
        if (systemPackagesProp != null && systemPackagesProp.trim().length() > 0) {
          uniquePackages.addAll(Arrays.asList(systemPackagesProp.split(",")));
        }

        final String eeProp = profile.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT, "");
        if (eeProp != null && eeProp.trim().length() > 0) {
          uniqueEE.addAll(Arrays.asList(eeProp.split(",")));
        }
      } catch (IOException e) {
        throw new PlatformException("Could not read execution environment profile", e);
      }
    }
    m_systemPackages = join(uniquePackages, ",");
    m_executionEnvironment = join(uniqueEE, ",");
  }