Пример #1
0
 private void addLoginParams(Request request, LoginInfo loginInfo) {
   MultiMap<String> params = new MultiMap<>();
   if (loginInfo != null && loginInfo.rememberAccount) {
     params.put(PARAM_USER_ID, loginInfo.userId);
   }
   request.setParameters(params);
 }
Пример #2
0
 public String formatOpts(Collection pLongNames) {
   StringBuffer result = new StringBuffer();
   Map longnametoshortnamemap = CollectionUtils.inverseMap(mShortNameToLongNameMap);
   Iterator longnames = pLongNames.iterator();
   while (longnames.hasNext()) {
     String longname = (String) longnames.next();
     result.append("  -" + longname);
     String shortname = (String) longnametoshortnamemap.get(longname);
     if (shortname != null) {
       result.append(" (-" + shortname + ")");
     }
     String possibleValsString = "";
     if (mPossibleValues.keySet().contains(longname)) {
       possibleValsString = " " + mPossibleValues.get(longname);
     }
     result.append(possibleValsString);
     String defaultVal = (String) mDefaultValues.get(longname);
     if (defaultVal != null) {
       result.append(", default=" + defaultVal);
     }
     if (longnames.hasNext()) {
       result.append("\n");
     }
   }
   return result.toString();
 }
  private static void removeFromMap(
      LookupElement key,
      MultiMap<LookupElement, LookupElement> mainMap,
      MultiMap<LookupElement, LookupElement> inverseMap) {
    Collection<LookupElement> removed = mainMap.remove(key);
    if (removed == null) return;

    for (LookupElement reference : ContainerUtil.newArrayList(removed)) {
      inverseMap.remove(reference, key);
    }
  }
 private void calculateToLift(LookupElement element) {
   for (String string : CompletionUtil.iterateLookupStrings(element)) {
     for (int len = 1; len < string.length(); len++) {
       String prefix = string.substring(0, len);
       for (LookupElement shorterElement : myElements.get(prefix)) {
         if (myCondition.shouldLift(shorterElement, element)) {
           myToLift.putValue(element, shorterElement);
           myReversedToLift.putValue(shorterElement, element);
         }
       }
     }
   }
 }
  @Override
  public void removeElement(@NotNull LookupElement element, @NotNull ProcessingContext context) {
    for (String s : CompletionUtil.iterateLookupStrings(element)) {
      myElements.remove(s, element);
      if (myElements.get(s).isEmpty()) {
        mySortedStrings.remove(s);
      }
    }

    removeFromMap(element, myToLift, myReversedToLift);
    removeFromMap(element, myReversedToLift, myToLift);

    super.removeElement(element, context);
  }
 @Test
 public void testHazelcastInstances() {
   assertNotNull(map1);
   assertNotNull(map2);
   assertNotNull(multiMap);
   assertNotNull(queue);
   assertNotNull(topic);
   assertNotNull(set);
   assertNotNull(list);
   assertNotNull(executorService);
   assertNotNull(idGenerator);
   assertNotNull(atomicLong);
   assertNotNull(atomicReference);
   assertNotNull(countDownLatch);
   assertNotNull(semaphore);
   assertNotNull(lock);
   assertEquals("map1", map1.getName());
   assertEquals("map2", map2.getName());
   assertEquals("testMultimap", multiMap.getName());
   assertEquals("testQ", queue.getName());
   assertEquals("testTopic", topic.getName());
   assertEquals("set", set.getName());
   assertEquals("list", list.getName());
   assertEquals("idGenerator", idGenerator.getName());
   assertEquals("atomicLong", atomicLong.getName());
   assertEquals("atomicReference", atomicReference.getName());
   assertEquals("countDownLatch", countDownLatch.getName());
   assertEquals("semaphore", semaphore.getName());
 }
  @Override
  public void addElement(@NotNull LookupElement added, @NotNull ProcessingContext context) {
    myCount++;

    for (String string : CompletionUtil.iterateLookupStrings(added)) {
      if (string.length() == 0) continue;

      myElements.putValue(string, added);
      mySortedStrings.add(string);
      final NavigableSet<String> after = mySortedStrings.tailSet(string, false);
      for (String s : after) {
        if (!s.startsWith(string)) {
          break;
        }
        for (LookupElement longer : myElements.get(s)) {
          updateLongerItem(added, longer);
        }
      }
    }
    super.addElement(added, context);

    calculateToLift(added);
  }
 @Test
 public void testIssue508And513() throws Exception {
   HazelcastClient client = getHazelcastClient();
   IMap<String, HashSet<byte[]>> callEventsMap = client.getMap("CALL_EVENTS");
   IMap<String, Long> metaDataMap = client.getMap("CALL_META_DATA");
   IMap<String, byte[]> callStartMap = client.getMap("CALL_START_EVENTS");
   MultiMap<String, String> calls = client.getMultiMap("CALLS");
   calls.lock("1");
   calls.unlock("1");
   byte[] bytes = new byte[10];
   HashSet<byte[]> hashSet = new HashSet<byte[]>();
   hashSet.add(bytes);
   String callId = "1";
   callEventsMap.put(callId, hashSet);
   callStartMap.put(callId, bytes);
   metaDataMap.put(callId, 10L);
   Transaction txn = client.getTransaction();
   txn.begin();
   try {
     // remove the data
     callEventsMap.remove(callId);
     // remove meta data
     metaDataMap.remove(callId);
     // remove call start
     callStartMap.remove(callId);
     calls.put(callId, callId);
     txn.commit();
   } catch (Exception e) {
     fail();
   }
   assertNull(callEventsMap.get(callId));
   assertNull(metaDataMap.get(callId));
   assertNull(callStartMap.get(callId));
   assertEquals(0, callEventsMap.size());
   assertEquals(0, metaDataMap.size());
   assertEquals(0, callStartMap.size());
 }
Пример #9
0
 @TestOnly
 public boolean setSelectedTemplate(String group, String name) {
   ListModel model = myProjectTypeList.getModel();
   for (int i = 0; i < model.getSize(); i++) {
     TemplatesGroup templatesGroup = (TemplatesGroup) model.getElementAt(i);
     if (group.equals(templatesGroup.getName())) {
       myProjectTypeList.setSelectedIndex(i);
       if (name == null) return getSelectedGroup().getName().equals(group);
       Collection<ProjectTemplate> templates = myTemplatesMap.get(templatesGroup);
       setTemplatesList(templatesGroup, templates, false);
       return myTemplatesList.setSelectedTemplate(name);
     }
   }
   return false;
 }
Пример #10
0
 private MultiMap<String, ProjectTemplate> loadLocalTemplates() {
   ConcurrentMultiMap<String, ProjectTemplate> map =
       new ConcurrentMultiMap<String, ProjectTemplate>();
   ProjectTemplateEP[] extensions = ProjectTemplateEP.EP_NAME.getExtensions();
   for (ProjectTemplateEP ep : extensions) {
     ClassLoader classLoader = ep.getLoaderForClass();
     URL url = classLoader.getResource(ep.templatePath);
     if (url != null) {
       LocalArchivedTemplate template = new LocalArchivedTemplate(url, classLoader);
       if (ep.category) {
         TemplateBasedCategory category = new TemplateBasedCategory(template, ep.projectType);
         myTemplatesMap.putValue(new TemplatesGroup(category), template);
       } else {
         map.putValue(ep.projectType, template);
       }
     }
   }
   return map;
 }
Пример #11
0
 public Collection<ProjectTemplate> getAvailableTemplates() {
   if (myCurrentCard != FRAMEWORKS_CARD) {
     return Collections.emptyList();
   } else {
     Collection<ProjectTemplate> templates = myTemplatesMap.get(getSelectedGroup());
     List<FrameworkSupportNode> nodes = myFrameworksPanel.getSelectedNodes();
     if (nodes.isEmpty()) return templates;
     final List<String> selectedFrameworks = ContainerUtil.map(nodes, NODE_STRING_FUNCTION);
     return ContainerUtil.filter(
         templates,
         new Condition<ProjectTemplate>() {
           @Override
           public boolean value(ProjectTemplate template) {
             if (!(template instanceof ArchivedProjectTemplate)) return true;
             List<String> frameworks = ((ArchivedProjectTemplate) template).getFrameworks();
             return frameworks.containsAll(selectedFrameworks);
           }
         });
   }
 }
Пример #12
0
  public void addDef(OptDef pDef) {

    mArgDefs.add(pDef);

    if (mShortNameToLongNameMap.containsKey(pDef.shortname)) {
      throw new RuntimeException("Duplicate short name: " + pDef.shortname);
    }

    mValidOptionNames.add(pDef.longname);

    if (pDef.shortname != null) {
      mValidOptionNames.add(pDef.shortname);
      mShortNameToLongNameMap.put(pDef.shortname, pDef.longname);
    } else {
      mOptionsWithoutShortName.add(pDef.longname);
    }

    if (pDef.hasvalue) {
      mNamesOfOptionsRequiringValue.add(pDef.longname);
    }

    if (pDef.defaultvalue != null) {
      // a little sanity check, if you permit...
      if (!(pDef.hasvalue)) {
        throw new RuntimeException(
            "Illegal situation: parameter "
                + pDef.longname
                + " has no value, "
                + "but still has default value "
                + pDef.defaultvalue);
      }
      mDefaultValues.put(pDef.longname, pDef.defaultvalue);
    }

    if (pDef.possiblevalues != null) {
      // for an "enum" type parameter
      mPossibleValues.putMultiple(pDef.longname, pDef.possiblevalues);
    }
  }
Пример #13
0
 public Set getOptions(String pKey) {
   return mPossibleValues.get(pKey);
 }
Пример #14
0
 private void showTemplates(TemplatesGroup group) {
   Collection<ProjectTemplate> templates = myTemplatesMap.get(group);
   setTemplatesList(group, templates, false);
   showCard(TEMPLATES_CARD);
 }
Пример #15
0
  private List<TemplatesGroup> fillTemplatesMap(WizardContext context) {

    List<ModuleBuilder> builders = ModuleBuilder.getAllBuilders();
    if (context.isCreatingNewProject()) {
      builders.add(new EmptyModuleBuilder());
    }
    Map<String, TemplatesGroup> groupMap = new HashMap<String, TemplatesGroup>();
    for (ModuleBuilder builder : builders) {
      BuilderBasedTemplate template = new BuilderBasedTemplate(builder);
      if (builder.isTemplate()) {
        TemplatesGroup group = groupMap.get(builder.getGroupName());
        if (group == null) {
          group = new TemplatesGroup(builder);
        }
        myTemplatesMap.putValue(group, template);
      } else {
        TemplatesGroup group = new TemplatesGroup(builder);
        groupMap.put(group.getName(), group);
        myTemplatesMap.put(group, new ArrayList<ProjectTemplate>());
      }
    }

    MultiMap<TemplatesGroup, ProjectTemplate> map = CreateFromTemplateMode.getTemplatesMap(context);
    myTemplatesMap.putAllValues(map);

    for (ProjectCategory category : ProjectCategory.EXTENSION_POINT_NAME.getExtensions()) {
      TemplatesGroup group = new TemplatesGroup(category);
      myTemplatesMap.remove(group);
      myTemplatesMap.put(group, new ArrayList<ProjectTemplate>());
    }

    if (context.isCreatingNewProject()) {
      MultiMap<String, ProjectTemplate> localTemplates = loadLocalTemplates();
      for (TemplatesGroup group : myTemplatesMap.keySet()) {
        myTemplatesMap.putValues(group, localTemplates.get(group.getId()));
      }
    }

    // remove Static Web group in IDEA Community if no specific templates found (IDEA-120593)
    if (PlatformUtils.isIdeaCommunity()) {
      for (TemplatesGroup group : myTemplatesMap.keySet()) {
        if (WebModuleTypeBase.WEB_MODULE.equals(group.getId())
            && myTemplatesMap.get(group).isEmpty()) {
          myTemplatesMap.remove(group);
          break;
        }
      }
    }

    List<TemplatesGroup> groups = new ArrayList<TemplatesGroup>(myTemplatesMap.keySet());

    // sorting by module type popularity
    final MultiMap<ModuleType, TemplatesGroup> moduleTypes =
        new MultiMap<ModuleType, TemplatesGroup>();
    for (TemplatesGroup group : groups) {
      ModuleType type = getModuleType(group);
      moduleTypes.putValue(type, group);
    }
    Collections.sort(
        groups,
        new Comparator<TemplatesGroup>() {
          @Override
          public int compare(TemplatesGroup o1, TemplatesGroup o2) {
            int i = o2.getWeight() - o1.getWeight();
            if (i != 0) return i;
            int i1 =
                moduleTypes.get(getModuleType(o2)).size()
                    - moduleTypes.get(getModuleType(o1)).size();
            if (i1 != 0) return i1;
            return o1.compareTo(o2);
          }
        });

    Set<String> groupNames =
        ContainerUtil.map2Set(
            groups,
            new Function<TemplatesGroup, String>() {
              @Override
              public String fun(TemplatesGroup group) {
                return group.getParentGroup();
              }
            });

    // move subgroups
    MultiMap<String, TemplatesGroup> subGroups = new MultiMap<String, TemplatesGroup>();
    for (ListIterator<TemplatesGroup> iterator = groups.listIterator(); iterator.hasNext(); ) {
      TemplatesGroup group = iterator.next();
      String parentGroup = group.getParentGroup();
      if (parentGroup != null
          && groupNames.contains(parentGroup)
          && !group.getName().equals(parentGroup)
          && groupMap.containsKey(parentGroup)) {
        subGroups.putValue(parentGroup, group);
        iterator.remove();
      }
    }
    for (ListIterator<TemplatesGroup> iterator = groups.listIterator(); iterator.hasNext(); ) {
      TemplatesGroup group = iterator.next();
      for (TemplatesGroup subGroup : subGroups.get(group.getName())) {
        iterator.add(subGroup);
      }
    }
    return groups;
  }
Пример #16
0
  public ProjectTypeStep(
      WizardContext context, NewProjectWizard wizard, ModulesProvider modulesProvider) {
    myContext = context;
    myWizard = wizard;

    myTemplatesMap = new ConcurrentMultiMap<TemplatesGroup, ProjectTemplate>();
    final List<TemplatesGroup> groups = fillTemplatesMap(context);

    myProjectTypeList.setModel(new CollectionListModel<TemplatesGroup>(groups));
    myProjectTypeList.setSelectionModel(new SingleSelectionModel());
    myProjectTypeList.addListSelectionListener(
        new ListSelectionListener() {
          @Override
          public void valueChanged(ListSelectionEvent e) {
            updateSelection();
          }
        });
    myProjectTypeList.setCellRenderer(
        new GroupedItemsListRenderer(
            new ListItemDescriptorAdapter<TemplatesGroup>() {
              @Nullable
              @Override
              public String getTextFor(TemplatesGroup value) {
                return value.getName();
              }

              @Nullable
              @Override
              public String getTooltipFor(TemplatesGroup value) {
                return value.getDescription();
              }

              @Nullable
              @Override
              public Icon getIconFor(TemplatesGroup value) {
                return value.getIcon();
              }

              @Override
              public boolean hasSeparatorAboveOf(TemplatesGroup value) {
                int index = groups.indexOf(value);
                if (index < 1) return false;
                TemplatesGroup upper = groups.get(index - 1);
                if (upper.getParentGroup() == null && value.getParentGroup() == null) return true;
                return !Comparing.equal(upper.getParentGroup(), value.getParentGroup())
                    && !Comparing.equal(upper.getName(), value.getParentGroup());
              }
            }) {
          @Override
          protected JComponent createItemComponent() {
            JComponent component = super.createItemComponent();
            myTextLabel.setBorder(IdeBorderFactory.createEmptyBorder(3));
            return component;
          }
        });

    new ListSpeedSearch(myProjectTypeList) {
      @Override
      protected String getElementText(Object element) {
        return ((TemplatesGroup) element).getName();
      }
    };

    myModulesProvider = modulesProvider;
    Project project = context.getProject();
    final LibrariesContainer container =
        LibrariesContainerFactory.createContainer(context, modulesProvider);
    FrameworkSupportModelBase model =
        new FrameworkSupportModelBase(project, null, container) {
          @NotNull
          @Override
          public String getBaseDirectoryForLibrariesPath() {
            ModuleBuilder builder = getSelectedBuilder();
            return StringUtil.notNullize(builder.getContentEntryPath());
          }

          @Override
          public ModuleBuilder getModuleBuilder() {
            return getSelectedBuilder();
          }
        };
    myFrameworksPanel =
        new AddSupportForFrameworksPanel(
            Collections.<FrameworkSupportInModuleProvider>emptyList(), model, true, myHeaderPanel);
    Disposer.register(this, myFrameworksPanel);
    myFrameworksPanelPlaceholder.add(myFrameworksPanel.getMainPanel());

    myConfigurationUpdater =
        new ModuleBuilder.ModuleConfigurationUpdater() {
          @Override
          public void update(@NotNull Module module, @NotNull ModifiableRootModel rootModel) {
            if (isFrameworksMode()) {
              myFrameworksPanel.addSupport(module, rootModel);
            }
          }
        };

    myProjectTypeList
        .getSelectionModel()
        .addListSelectionListener(
            new ListSelectionListener() {
              @Override
              public void valueChanged(ListSelectionEvent e) {
                projectTypeChanged();
              }
            });

    myTemplatesList.addListSelectionListener(
        new ListSelectionListener() {
          @Override
          public void valueChanged(ListSelectionEvent e) {
            updateSelection();
          }
        });

    for (TemplatesGroup templatesGroup : myTemplatesMap.keySet()) {
      ModuleBuilder builder = templatesGroup.getModuleBuilder();
      if (builder != null) {
        myWizard.getSequence().addStepsForBuilder(builder, context, modulesProvider);
      }
      for (ProjectTemplate template : myTemplatesMap.get(templatesGroup)) {
        myWizard
            .getSequence()
            .addStepsForBuilder(myBuilders.get(template), context, modulesProvider);
      }
    }

    final String groupId = PropertiesComponent.getInstance().getValue(PROJECT_WIZARD_GROUP);
    if (groupId != null) {
      TemplatesGroup group =
          ContainerUtil.find(
              groups,
              new Condition<TemplatesGroup>() {
                @Override
                public boolean value(TemplatesGroup group) {
                  return groupId.equals(group.getId());
                }
              });
      if (group != null) {
        myProjectTypeList.setSelectedValue(group, true);
      }
    }
    if (myProjectTypeList.getSelectedValue() == null) {
      myProjectTypeList.setSelectedIndex(0);
    }
    myTemplatesList.restoreSelection();
  }
Пример #17
0
  /**
   * Arranges (re-orders) given entries according to the given rules.
   *
   * @param entries entries to arrange
   * @param rules rules to use for arrangement
   * @param rulesByPriority rules sorted by priority ('public static' rule will have higher priority
   *     than 'public')
   * @param <E> arrangement entry type
   * @return arranged list of the given rules
   */
  @SuppressWarnings("AssignmentToForLoopParameter")
  @NotNull
  public static <E extends ArrangementEntry> List<E> arrange(
      @NotNull Collection<E> entries,
      @NotNull List<? extends ArrangementMatchRule> rules,
      @NotNull List<? extends ArrangementMatchRule> rulesByPriority) {
    List<E> arranged = ContainerUtilRt.newArrayList();
    Set<E> unprocessed = ContainerUtilRt.newLinkedHashSet();
    List<Pair<Set<ArrangementEntry>, E>> dependent = ContainerUtilRt.newArrayList();
    for (E entry : entries) {
      List<? extends ArrangementEntry> dependencies = entry.getDependencies();
      if (dependencies == null) {
        unprocessed.add(entry);
      } else {
        if (dependencies.size() == 1 && dependencies.get(0) == entry.getParent()) {
          // Handle a situation when the entry is configured to be at the first parent's children.
          arranged.add(entry);
        } else {
          Set<ArrangementEntry> first = new HashSet<ArrangementEntry>(dependencies);
          dependent.add(Pair.create(first, entry));
        }
      }
    }

    Set<E> matched = new HashSet<E>();

    MultiMap<ArrangementMatchRule, E> elementsByRule = new MultiMap<ArrangementMatchRule, E>();
    for (ArrangementMatchRule rule : rulesByPriority) {
      matched.clear();
      for (E entry : unprocessed) {
        if (entry.canBeMatched() && rule.getMatcher().isMatched(entry)) {
          elementsByRule.putValue(rule, entry);
          matched.add(entry);
        }
      }
      unprocessed.removeAll(matched);
    }

    for (ArrangementMatchRule rule : rules) {
      if (elementsByRule.containsKey(rule)) {
        final Collection<E> arrangedEntries = elementsByRule.get(rule);

        // Sort by name if necessary.
        if (StdArrangementTokens.Order.BY_NAME.equals(rule.getOrderType())) {
          sortByName((List<E>) arrangedEntries);
        }
        arranged.addAll(arrangedEntries);
      }
    }
    arranged.addAll(unprocessed);

    for (int i = 0; i < arranged.size() && !dependent.isEmpty(); i++) {
      E e = arranged.get(i);
      for (Iterator<Pair<Set<ArrangementEntry>, E>> iterator = dependent.iterator();
          iterator.hasNext(); ) {
        Pair<Set<ArrangementEntry>, E> pair = iterator.next();
        pair.first.remove(e);
        if (pair.first.isEmpty()) {
          iterator.remove();
          arranged.add(i + 1, pair.second);
        }
      }
    }

    return arranged;
  }
 private void updateLongerItem(LookupElement shorter, LookupElement longer) {
   if (myCondition.shouldLift(shorter, longer)) {
     myToLift.putValue(longer, shorter);
     myReversedToLift.putValue(shorter, longer);
   }
 }
Пример #19
0
  public void request(
      final String method,
      final String url,
      final MultiMap headers,
      final Buffer body,
      final Handler<Response> handler) {
    try {
      final URI uri = new URI(url);
      final boolean urlEncoded =
          "application/x-www-form-urlencoded".equalsIgnoreCase(headers.get("content-type"));

      final Response response = new Response(vertx, handler);

      // start yoke
      fakeServer
          .requestHandler()
          .handle(
              new HttpServerRequest() {

                MultiMap params = null;
                MultiMap attributes = null;

                @Override
                public HttpVersion version() {
                  return HttpVersion.HTTP_1_1;
                }

                @Override
                public String method() {
                  return method.toUpperCase();
                }

                @Override
                public String uri() {
                  return uri.getPath() + "?" + uri.getQuery() + "#" + uri.getFragment();
                }

                @Override
                public String path() {
                  return uri.getPath();
                }

                @Override
                public String query() {
                  return uri.getQuery();
                }

                @Override
                public HttpServerResponse response() {
                  return response;
                }

                @Override
                public MultiMap headers() {
                  return headers;
                }

                @Override
                public MultiMap params() {
                  if (params == null) {
                    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri());
                    Map<String, List<String>> prms = queryStringDecoder.parameters();
                    params = new CaseInsensitiveMultiMap();

                    if (!prms.isEmpty()) {
                      for (Map.Entry<String, List<String>> entry : prms.entrySet()) {
                        params.add(entry.getKey(), entry.getValue());
                      }
                    }
                  }
                  return params;
                }

                @Override
                public InetSocketAddress remoteAddress() {
                  return new InetSocketAddress("127.0.0.1", 80);
                }

                @Override
                public X509Certificate[] peerCertificateChain() throws SSLPeerUnverifiedException {
                  return null;
                }

                @Override
                public URI absoluteURI() {
                  return uri;
                }

                @Override
                public HttpServerRequest bodyHandler(Handler<Buffer> bodyHandler) {
                  bodyHandler.handle(body);
                  return this;
                }

                @Override
                public HttpServerRequest dataHandler(Handler<Buffer> handler) {
                  handler.handle(body);
                  return this;
                }

                @Override
                public HttpServerRequest pause() {
                  throw new UnsupportedOperationException("This mock does not support pause");
                }

                @Override
                public HttpServerRequest resume() {
                  throw new UnsupportedOperationException("This mock does not support resume");
                }

                @Override
                public HttpServerRequest endHandler(Handler<Void> endHandler) {
                  endHandler.handle(null);
                  return this;
                }

                @Override
                public NetSocket netSocket() {
                  throw new UnsupportedOperationException("This mock does not support netSocket");
                }

                @Override
                public HttpServerRequest expectMultiPart(boolean expect) {
                  // NOOP
                  return this;
                }

                @Override
                public HttpServerRequest uploadHandler(
                    Handler<HttpServerFileUpload> uploadHandler) {
                  throw new UnsupportedOperationException(
                      "This mock does not support uploadHandler");
                }

                @Override
                public MultiMap formAttributes() {
                  if (attributes == null) {
                    attributes = new CaseInsensitiveMultiMap();
                    if (urlEncoded) {
                      QueryStringDecoder queryStringDecoder =
                          new QueryStringDecoder(body.toString(), false);

                      Map<String, List<String>> prms = queryStringDecoder.parameters();

                      if (!prms.isEmpty()) {
                        for (Map.Entry<String, List<String>> entry : prms.entrySet()) {
                          attributes.add(entry.getKey(), entry.getValue());
                        }
                      }
                    }
                  }
                  return attributes;
                }

                @Override
                public HttpServerRequest exceptionHandler(Handler<Throwable> handler) {
                  throw new UnsupportedOperationException(
                      "This mock does not support exceptionHandler");
                }
              });
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
  }
Пример #20
0
 public boolean isEnum(String pKey) {
   return mPossibleValues.containsKey(pKey);
 }
Пример #21
0
  /**
   * Normally sets the path and a few attributes that the JSPs are likely to need. Also verifies the
   * login information. If necessary, just redirects to the login page.
   *
   * @param target
   * @param request
   * @param httpServletResponse
   * @param secured
   * @return true if the request is already handled so the .jsp shouldn't get called
   * @throws Exception
   */
  private boolean prepareForJspGet(
      String target, Request request, HttpServletResponse httpServletResponse, boolean secured)
      throws Exception {

    LoginInfo.SessionInfo sessionInfo = UserHelpers.getSessionInfo(request);

    LOG.info(
        String.format(
            "hndl - %s ; %s; %s ; %s",
            target,
            request.getPathInfo(),
            request.getMethod(),
            secured ? "secured" : "not secured"));

    String path = request.getUri().getDecodedPath();

    boolean redirectToLogin = path.equals(PATH_LOGOUT);
    LoginInfo loginInfo = null;
    if (sessionInfo.isNull()) {
      redirectToLogin = true;
      LOG.info("Null session info. Logging in again.");
    } else {
      loginInfo =
          loginInfoDb.get(
              sessionInfo.browserId,
              sessionInfo.sessionId); // ttt2 use a cache, to avoid going to DB
      if (loginInfo == null || loginInfo.expiresOn < System.currentTimeMillis()) {
        LOG.info("Session has expired. Logging in again. Info: " + loginInfo);
        redirectToLogin = true;
      }
    }

    if (!path.equals(PATH_LOGIN) && !path.equals(PATH_SIGNUP) && !path.equals(PATH_ERROR)) {

      if (redirectToLogin) {
        // ttt2 perhaps store URI, to return to it after login
        logOut(sessionInfo.browserId);
        addLoginParams(request, loginInfo);
        httpServletResponse.sendRedirect(PATH_LOGIN);
        return true;
      }

      User user = userDb.get(loginInfo.userId);
      if (user == null) {
        WebUtils.redirectToError("Unknown user", request, httpServletResponse);
        return true;
      }
      if (!user.active) {
        WebUtils.redirectToError("Account is not active", request, httpServletResponse);
        return true;
      }
      request.setAttribute(VAR_FEED_DB, feedDb);
      request.setAttribute(VAR_USER_DB, userDb);
      request.setAttribute(VAR_ARTICLE_DB, articleDb);
      request.setAttribute(VAR_READ_ARTICLES_COLL_DB, readArticlesCollDb);

      request.setAttribute(VAR_USER, user);
      request.setAttribute(VAR_LOGIN_INFO, loginInfo);

      MultiMap<String> params = new MultiMap<>();
      params.put(PARAM_PATH, path);
      request.setParameters(params);
    }

    if (path.equals(PATH_LOGIN)) {
      addLoginParams(request, loginInfo);
    }
    return false;
  }
 public <Kk extends K, Vv extends V> void putAllValues(@NotNull MultiMap<Kk, Vv> from) {
   for (Map.Entry<Kk, Collection<Vv>> entry : from.entrySet()) {
     putValues(entry.getKey(), entry.getValue());
   }
 }