Beispiel #1
0
  /**
   * create the info string; assumes that no values are null
   *
   * @param infoFields a map of info fields
   * @throws IOException for writer
   */
  private void writeInfoString(Map<String, String> infoFields) throws IOException {
    if (infoFields.isEmpty()) {
      mWriter.write(VCFConstants.EMPTY_INFO_FIELD);
      return;
    }

    boolean isFirst = true;
    for (Map.Entry<String, String> entry : infoFields.entrySet()) {
      if (isFirst) isFirst = false;
      else mWriter.write(VCFConstants.INFO_FIELD_SEPARATOR);

      String key = entry.getKey();
      mWriter.write(key);

      if (!entry.getValue().equals("")) {
        VCFInfoHeaderLine metaData = mHeader.getInfoHeaderLine(key);
        if (metaData == null
            || metaData.getCountType() != VCFHeaderLineCount.INTEGER
            || metaData.getCount() != 0) {
          mWriter.write("=");
          mWriter.write(entry.getValue());
        }
      }
    }
  }
Beispiel #2
0
 static void clrTest(int n, Map s) {
   String nm = "Remove Present         ";
   timer.start(nm, n);
   s.clear();
   timer.finish();
   reallyAssert(s.isEmpty());
 }
  protected Map<String, FusionSession> establishSessions(
      List<String> endpoints, String user, String password, String realm) throws Exception {

    Exception lastError = null;
    Map<String, FusionSession> map = new HashMap<String, FusionSession>();
    for (String url : endpoints) {
      try {
        map.put(url, establishSession(url, user, password, realm));
      } catch (Exception exc) {
        // just log this ... so long as there is at least one good endpoint we can use it
        lastError = exc;
        log.warn("Failed to establish session with Fusion at " + url + " due to: " + exc);
      }
    }

    if (map.isEmpty()) {
      if (lastError != null) {
        throw lastError;
      } else {
        throw new Exception("Failed to establish session with Fusion endpoint(s): " + endpoints);
      }
    }

    log.info(
        "Established sessions with "
            + map.size()
            + " of "
            + endpoints.size()
            + " Fusion endpoints for user "
            + user
            + " in realm "
            + realm);

    return map;
  }
 public Map<String, String> loadAndGetPackages() throws IOException {
   Map<String, String> pyPIPackages = getPyPIPackages();
   if (pyPIPackages.isEmpty()) {
     updatePyPICache(PyPackageService.getInstance());
     pyPIPackages = getPyPIPackages();
   }
   return pyPIPackages;
 }
 void completed(InetAddress remote, String cfname) {
   logger.debug("Repair completed for {} on {}", remote, cfname);
   RepairJob job = activeJobs.get(cfname);
   if (job.completedSynchronizationJob(remote)) {
     activeJobs.remove(cfname);
     if (activeJobs.isEmpty()) completed.signalAll();
   }
 }
Beispiel #6
0
  /** Prints the given <code>JimpleBody</code> to the specified <code>PrintWriter</code>. */
  private void printLocalsInBody(Body body, UnitPrinter up) {
    // Print out local variables
    {
      Map typeToLocals = new DeterministicHashMap(body.getLocalCount() * 2 + 1, 0.7f);

      // Collect locals
      {
        Iterator localIt = body.getLocals().iterator();

        while (localIt.hasNext()) {
          Local local = (Local) localIt.next();

          List localList;

          Type t = local.getType();

          if (typeToLocals.containsKey(t)) localList = (List) typeToLocals.get(t);
          else {
            localList = new ArrayList();
            typeToLocals.put(t, localList);
          }

          localList.add(local);
        }
      }

      // Print locals
      {
        Iterator typeIt = typeToLocals.keySet().iterator();

        while (typeIt.hasNext()) {
          Type type = (Type) typeIt.next();

          List localList = (List) typeToLocals.get(type);
          Object[] locals = localList.toArray();
          up.type(type);
          up.literal(" ");

          for (int k = 0; k < locals.length; k++) {
            if (k != 0) up.literal(", ");

            up.local((Local) locals[k]);
          }

          up.literal(";");
          up.newline();
        }
      }

      if (!typeToLocals.isEmpty()) {
        up.newline();
      }
    }
  }
 public synchronized void undeployAll(final Handler<Void> doneHandler) {
   final CountingCompletionHandler count = new CountingCompletionHandler(vertx);
   if (!deployments.isEmpty()) {
     // We do it this way since undeploy is itself recursive - we don't want
     // to attempt to undeploy the same verticle twice if it's a child of
     // another
     while (!deployments.isEmpty()) {
       String name = deployments.keySet().iterator().next();
       count.incRequired();
       undeploy(
           name,
           new SimpleHandler() {
             public void handle() {
               count.complete();
             }
           });
     }
   }
   count.setHandler(doneHandler);
 }
Beispiel #8
0
  private Point getFeedPoint(final User user) throws NimbitsException {
    final Point point;
    final Map<String, Entity> map =
        EntityServiceFactory.getInstance().getEntityMap(user, EntityType.feed, 1);

    if (map.isEmpty()) {
      point = createFeedPoint(user);
    } else {
      return (Point) map.values().iterator().next();
    }
    return point;
  }
  /** Print plugins information. */
  private void ackPluginsInfo() {
    U.quietAndInfo(log, "Configured plugins:");

    if (plugins.isEmpty()) {
      U.quietAndInfo(log, "  ^-- None");
      U.quietAndInfo(log, "");
    } else {
      for (PluginProvider plugin : plugins.values()) {
        U.quietAndInfo(log, "  ^-- " + plugin.name() + " " + plugin.version());
        U.quietAndInfo(log, "  ^-- " + plugin.copyright());
        U.quietAndInfo(log, "");
      }
    }
  }
  private static void convertProtocolToAsciidocTable(Properties props, Class<Protocol> clazz)
      throws Exception {
    boolean isUnsupported = clazz.isAnnotationPresent(Unsupported.class);
    if (isUnsupported) return;

    Map<String, String> nameToDescription = new TreeMap<>();

    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
      if (field.isAnnotationPresent(Property.class)) {
        String property = field.getName();
        Property annotation = field.getAnnotation(Property.class);
        String desc = annotation.description();
        nameToDescription.put(property, desc);
      }
    }

    // iterate methods
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
      if (method.isAnnotationPresent(Property.class)) {

        Property annotation = method.getAnnotation(Property.class);
        String desc = annotation.description();

        if (desc == null || desc.isEmpty()) desc = "n/a";

        String name = annotation.name();
        if (name.length() < 1) {
          name = Util.methodNameToAttributeName(method.getName());
        }
        nameToDescription.put(name, desc);
      }
    }

    // do we have more than one property (superclass Protocol has only one property (stats))
    if (nameToDescription.isEmpty()) return;

    List<String[]> rows = new ArrayList<>(nameToDescription.size() + 1);
    rows.add(new String[] {"Name", "Description"});
    for (Map.Entry<String, String> entry : nameToDescription.entrySet())
      rows.add(new String[] {entry.getKey(), entry.getValue()});

    String tmp =
        createAsciidocTable(
            rows,
            clazz.getSimpleName(),
            "[align=\"left\",width=\"90%\",cols=\"2,10\",options=\"header\"]");
    props.put(clazz.getSimpleName(), tmp);
  }
 static void mergeOptionalConfigs(Map<PluginId, IdeaPluginDescriptorImpl> descriptors) {
   final Map<PluginId, IdeaPluginDescriptorImpl> descriptorsWithModules =
       new HashMap<PluginId, IdeaPluginDescriptorImpl>(descriptors);
   addModulesAsDependents(descriptorsWithModules);
   for (IdeaPluginDescriptorImpl descriptor : descriptors.values()) {
     final Map<PluginId, IdeaPluginDescriptorImpl> optionalDescriptors =
         descriptor.getOptionalDescriptors();
     if (optionalDescriptors != null && !optionalDescriptors.isEmpty()) {
       for (Map.Entry<PluginId, IdeaPluginDescriptorImpl> entry : optionalDescriptors.entrySet()) {
         if (descriptorsWithModules.containsKey(entry.getKey())) {
           descriptor.mergeOptionalConfig(entry.getValue());
         }
       }
     }
   }
 }
  /**
   * Starts new grid node.
   *
   * @param gridName name of new node.
   * @param springCfg file with spring configuration to use for this node.
   * @return a grid instance local to new node {@link GridGain#start(GridConfiguration)}.
   * @throws Exception if node run failed.
   */
  protected Grid startNode(String gridName, File springCfg) throws Exception {
    assert springCfg != null;

    ListableBeanFactory springCtx =
        new FileSystemXmlApplicationContext("file:///" + springCfg.getAbsolutePath());

    Map cfgMap = springCtx.getBeansOfType(GridConfiguration.class);

    assert cfgMap != null;
    assert !cfgMap.isEmpty();

    GridConfiguration cfg = (GridConfiguration) cfgMap.values().iterator().next();

    cfg.setGridName(gridName + "-" + getNextNodeNum());

    return G.start(cfg);
  }
Beispiel #13
0
  /** Обработчик всех событий помещенных в очередь */
  void processEvents() {
    for (; ; ) {

      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        LOG.log(Level.SEVERE, x.getMessage());
        return;
      }

      Path dir = keys.get(key);
      if (dir == null) {
        LOG.log(Level.SEVERE, "Входной каталог не найден!");
        continue;
      }

      for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind kind = event.kind();

        // TODO - подумать над обработчиком события OVERFLOW
        if (kind == OVERFLOW) {
          continue;
        }

        WatchEvent<Path> ev = cast(event);
        Path name = ev.context();
        Path child = dir.resolve(name);

        // логируем событие
        if (kind == ENTRY_CREATE) {
          LOG.log(Level.FINEST, "{0}: {1}", new Object[] {event.kind().name(), child});
          Runnable worker = new WorkerThread(child);
          executor.execute(worker);
        }
      }

      boolean valid = key.reset();
      if (!valid) {
        keys.remove(key);
        if (keys.isEmpty()) {
          break;
        }
      }
    }
  }
 public void setProperty(final String path, final ItemStack stack) {
   final Map<String, Object> map = new HashMap<String, Object>();
   map.put("type", stack.getType().toString());
   map.put("amount", stack.getAmount());
   map.put("damage", stack.getDurability());
   Map<Enchantment, Integer> enchantments = stack.getEnchantments();
   if (!enchantments.isEmpty()) {
     Map<String, Integer> enchant = new HashMap<String, Integer>();
     for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
       enchant.put(entry.getKey().getName().toLowerCase(Locale.ENGLISH), entry.getValue());
     }
     map.put("enchant", enchant);
   }
   // getData().getData() is broken
   // map.put("data", stack.getDurability());
   set(path, map);
 }
  public Map<String, Object> getMapParams(Long id, Map<String, Object> mapFormatSql) {
    Template tpl = this.templateDao.load(id);
    if (tpl == null) throw new CoreException("template is not exists");

    // 取参数集合
    Set<TemplateParam> tplps = tpl.getParams();
    // 没配置模板参数处理
    if (tplps == null || tplps.isEmpty()) return null;

    Map<String, Object> formattedMap = new HashMap<String, Object>();
    Map<String, Object> tempMap;
    // 遍历模板参数集合获取格式化的替换参数
    for (TemplateParam tp : tplps) {
      tempMap = templateParamService.getMapParams(tp, mapFormatSql);
      if (tempMap != null) formattedMap.putAll(tempMap);
    }
    return formattedMap.isEmpty() ? null : formattedMap;
  }
Beispiel #16
0
 byte[] getByteBodyContents() {
   if (bytePayload != null) return bytePayload;
   String body = null;
   if (payload != null) {
     body = payload;
   } else if (files.isEmpty()) {
     body = URLUtils.formURLEncodeMap(bodyParams);
   } else {
     byte res[] = null;
     try {
       res = URLUtils.doFormDataEncode(bodyParams, files, boundary).toByteArray();
     } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
     return res;
   }
   try {
     return body.getBytes(getCharset());
   } catch (UnsupportedEncodingException uee) {
     throw new OAuthException("Unsupported Charset: " + getCharset(), uee);
   }
 }
  public boolean getBoolean() throws SQLException {
    int type = JSONTypes.jsonTypes.get(field.getType());

    switch (type) {
      case JSONTypes.JSON_BOOLEAN:
        return (boolean) jsonObject;
      case JSONTypes.JSON_NUMBER:
        Number number = (Number) jsonObject;
        return !number.equals((Number) 0);
      case JSONTypes.JSON_STRING:
        String string = (String) jsonObject;
        return !string.isEmpty();
      case JSONTypes.JSON_MAP:
      case JSONTypes.JSON_OBJECT:
        Map map = (Map) jsonObject;
        return !map.isEmpty();
      case JSONTypes.JSON_ARRAY:
        List list = (List) jsonObject;
        return !list.isEmpty();

      default:
        return false;
    }
  }
 @Override
 public boolean hasReportedProblems() {
   final GlobalInspectionContextImpl context = getContext();
   if (!isDisposed() && context.getUIOptions().SHOW_ONLY_DIFF) {
     for (CommonProblemDescriptor descriptor : getProblemToElements().keySet()) {
       if (getProblemStatus(descriptor) != FileStatus.NOT_CHANGED) {
         return true;
       }
     }
     if (myOldProblemElements != null) {
       for (RefEntity entity : myOldProblemElements.keySet()) {
         if (getElementStatus(entity) != FileStatus.NOT_CHANGED) {
           return true;
         }
       }
     }
     return false;
   }
   if (!getProblemElements().isEmpty()) return true;
   return !isDisposed()
       && context.getUIOptions().SHOW_DIFF_WITH_PREVIOUS_RUN
       && myOldProblemElements != null
       && !myOldProblemElements.isEmpty();
 }
    void completed(Differencer differencer) {
      logger.debug(
          String.format(
              "[repair #%s] Repair completed between %s and %s on %s",
              getName(), differencer.r1.endpoint, differencer.r2.endpoint, differencer.cfname));
      RepairJob job = activeJobs.get(differencer.cfname);
      if (job == null) {
        assert terminated;
        return;
      }

      if (job.completedSynchronization(differencer)) {
        activeJobs.remove(differencer.cfname);
        String remaining =
            activeJobs.size() == 0
                ? ""
                : String.format(
                    " (%d remaining column family to sync for this session)", activeJobs.size());
        logger.info(
            String.format(
                "[repair #%s] %s is fully synced%s", getName(), differencer.cfname, remaining));
        if (activeJobs.isEmpty()) completed.signalAll();
      }
    }
Beispiel #20
0
  /** Process all events for keys queued to the watcher */
  void processEvents() {
    for (; ; ) {

      // wait for key to be signalled
      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        return;
      }

      Path dir = keys.get(key);
      if (dir == null) {
        System.err.println("WatchKey not recognized!!");
        continue;
      }

      for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind kind = event.kind();

        // TBD - provide example of how OVERFLOW event is handled
        if (kind == OVERFLOW) {
          continue;
        }

        // Context for directory entry event is the file name of entry
        WatchEvent<Path> ev = cast(event);
        Path name = ev.context();
        Path child = dir.resolve(name);

        // print out event
        System.out.format("%s: %s\n", event.kind().name(), child);
        // Printing manager
        if (event.kind().name().equals("ENTRY_MODIFY")
            && (child.endsWith("baseFerremundoPointer.csv")
                || child.endsWith("baseFerremundoPointer2.csv"))) {
          File file = new File(child.toString());
          file.renameTo(new File("/home/dios/FERREMUNDO/BD/baseFerremundoPointer_.csv"));
          InvoicePrintingManager manager = new InvoicePrintingManager();
          manager.manage();
        }
        // if directory is created, and watching recursively, then
        // register it and its sub-directories
        if (recursive && (kind == ENTRY_CREATE)) {
          try {
            if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
              registerAll(child);
            }
          } catch (IOException x) {
            // ignore to keep sample readbale
          }
        }
      }

      // reset key and remove from set if directory no longer accessible
      boolean valid = key.reset();
      if (!valid) {
        keys.remove(key);

        // all directories are inaccessible
        if (keys.isEmpty()) {
          break;
        }
      }
    }
  }
Beispiel #21
0
  static void twoMapTest2(Map s, Object[] key, Object[] absent) {
    int size = key.length;

    Map s2 = newMap();
    putAllTest("Add    Absent          ", size, s, s2);
    putAllTest("Modify Present         ", size, s, s2);

    Object lastkey = kitTest(s2, size);
    Object hold = s2.get(lastkey);
    int sum = 0;

    timer.start("Traverse entry         ", size * 12); // 12 until finish

    int sh1 = s.hashCode() - s2.hashCode();
    reallyAssert(sh1 == 0);

    boolean eq1 = s2.equals(s);
    boolean eq2 = s.equals(s2);
    reallyAssert(eq1 && eq2);

    Set es2 = s2.entrySet();
    for (Iterator it = s.entrySet().iterator(); it.hasNext(); ) {
      Object entry = it.next();
      if (es2.contains(entry)) ++sum;
    }
    reallyAssert(sum == size);

    s2.put(lastkey, MISSING);

    int sh2 = s.hashCode() - s2.hashCode();
    reallyAssert(sh2 != 0);

    eq1 = s2.equals(s);
    eq2 = s.equals(s2);
    reallyAssert(!eq1 && !eq2);

    sum = 0;
    for (Iterator it = s.entrySet().iterator(); it.hasNext(); ) {
      Map.Entry e = (Map.Entry) it.next();
      e.setValue(absent[sum++]);
    }
    reallyAssert(sum == size);
    for (Iterator it = s2.entrySet().iterator(); it.hasNext(); ) {
      Map.Entry e = (Map.Entry) it.next();
      e.setValue(s.get(e.getKey()));
    }

    timer.finish();

    int rmiss = 0;
    timer.start("Remove Present         ", size * 2);
    Iterator s2i = s2.entrySet().iterator();
    Set es = s.entrySet();
    while (s2i.hasNext()) {
      if (!es.remove(s2i.next())) ++rmiss;
    }
    timer.finish();
    reallyAssert(rmiss == 0);

    clrTest(size, s2);
    reallyAssert(s2.isEmpty() && s.isEmpty());
  }
 public boolean isEmpty() {
   return tags.isEmpty();
 }
Beispiel #23
0
  /**
   * Merge other Tdb into this one. Makes copies of otherTdb's non-duplicate TdbPublisher, TdbTitle,
   * and TdbAu objects and their non-duplicate children. The object themselves are not merged.
   *
   * @param otherTdb the other Tdb
   * @throws TdbException if Tdb is sealed
   */
  public void copyFrom(Tdb otherTdb) throws TdbException {
    // ignore inappropriate Tdb values
    if ((otherTdb == null) || (otherTdb == this)) {
      return;
    }

    if (isSealed()) {
      throw new TdbException("Cannot add otherTdb AUs to sealed Tdb");
    }

    // merge non-duplicate publishers of otherTdb
    boolean tdbIsNew = tdbPublisherMap.isEmpty();
    for (TdbPublisher otherPublisher : otherTdb.getAllTdbPublishers().values()) {
      String pubName = otherPublisher.getName();
      TdbPublisher thisPublisher;
      boolean publisherIsNew = true;
      if (tdbIsNew) {
        // no need to check for existing publisher if TDB is new
        thisPublisher = new TdbPublisher(pubName);
        tdbPublisherMap.put(pubName, thisPublisher);
      } else {
        thisPublisher = tdbPublisherMap.get(pubName);
        publisherIsNew = (thisPublisher == null);
        if (publisherIsNew) {
          // copy publisher if not present in this Tdb
          thisPublisher = new TdbPublisher(pubName);
          tdbPublisherMap.put(pubName, thisPublisher);
        }
      }

      // merge non-duplicate titles of otherPublisher into thisPublisher
      for (TdbTitle otherTitle : otherPublisher.getTdbTitles()) {
        String otherId = otherTitle.getId();
        TdbTitle thisTitle;
        boolean titleIsNew = true;
        if (publisherIsNew) {
          // no need to check for existing title if publisher is new
          thisTitle = otherTitle.copyForTdbPublisher(thisPublisher);
          thisPublisher.addTdbTitle(thisTitle);
        } else {
          thisTitle = thisPublisher.getTdbTitleById(otherId);
          titleIsNew = (thisTitle == null);
          if (titleIsNew) {
            // copy title if not present in this publisher
            thisTitle = otherTitle.copyForTdbPublisher(thisPublisher);
            thisPublisher.addTdbTitle(thisTitle);
          } else if (!thisTitle.getName().equals(otherTitle.getName())) {
            // error because it could lead to a missing title -- one probably has a typo
            // (what about checking other title elements too?)
            logger.error(
                "Ignorning duplicate title entry: \""
                    + otherTitle.getName()
                    + "\" with the same ID as \""
                    + thisTitle.getName()
                    + "\"");
          }
        }

        // merge non-duplicate TdbAus of otherTitle into thisTitle
        for (TdbAu otherAu : otherTitle.getTdbAus()) {
          // no need to check for existing au if title is new
          String pluginId = otherAu.getPluginId();
          if (titleIsNew || !getTdbAuIds(pluginId).contains(otherAu.getId())) {
            // always succeeds we've already checked for duplicate
            TdbAu thisAu = otherAu.copyForTdbTitle(thisTitle);
            addTdbAuForPlugin(thisAu);
          } else {
            TdbAu thisAu = findExistingTdbAu(otherAu);
            if (!thisAu.getTdbTitle().getName().equals(otherAu.getTdbTitle().getName())) {
              if (!thisAu.getName().equals(otherAu.getName())) {
                logger.error(
                    "Ignorning duplicate au entry: \""
                        + otherAu.getName()
                        + "\" for title \""
                        + otherAu.getTdbTitle().getName()
                        + "\" with same definion as existing au entry: \""
                        + thisAu.getName()
                        + "\" for title \""
                        + thisAu.getTdbTitle().getName()
                        + "\"");
              } else {
                logger.error(
                    "Ignorning duplicate au entry: \""
                        + otherAu.getName()
                        + "\" for title \""
                        + otherAu.getTdbTitle().getName()
                        + "\" with same definion as existing one for title \""
                        + thisAu.getTdbTitle().getName()
                        + "\"");
              }
            } else if (!thisAu.getName().equals(otherAu.getName())) {
              // error because it could lead to a missing AU -- one probably has a typo
              logger.error(
                  "Ignorning duplicate au entry: \""
                      + otherAu.getName()
                      + "\" with the same definition as \""
                      + thisAu.getName()
                      + "\" for title \""
                      + otherAu.getTdbTitle().getName());
            } else {
              logger.warning(
                  "Ignoring duplicate au entry: \""
                      + otherAu.getName()
                      + "\" for title \""
                      + otherAu.getTdbTitle().getName());
            }
          }
        }
      }
    }
  }
Beispiel #24
0
  private void writeAdditionalUninstallData(UninstallData udata, JarOutputStream outJar)
      throws IOException {
    Map<String, Object> additionalData = udata.getAdditionalData();
    if (additionalData != null && !additionalData.isEmpty()) {
      Set<String> exist = new HashSet<String>();
      for (String key : additionalData.keySet()) {
        Object contents = additionalData.get(key);
        if ("__uninstallLibs__".equals(key)) {
          for (Object o : ((List) contents)) {
            String nativeLibName = (String) ((List) o).get(0);
            byte[] buffer = new byte[5120];
            long bytesCopied = 0;
            int bytesInBuffer;
            outJar.putNextEntry(new JarEntry("/com/izforge/izpack/bin/native/" + nativeLibName));
            InputStream in =
                getClass().getResourceAsStream("/com/izforge/izpack/bin/native/" + nativeLibName);
            while ((bytesInBuffer = in.read(buffer)) != -1) {
              outJar.write(buffer, 0, bytesInBuffer);
              bytesCopied += bytesInBuffer;
            }
            outJar.closeEntry();
          }
        } else if ("uninstallerListeners".equals(key) || "uninstallerJars".equals(key)) {
          // It is a ArrayList of ArrayLists which contains the full
          // package paths of all needed class files.
          // First we create a new ArrayList which contains only
          // the full paths for the uninstall listener self; thats
          // the first entry of each sub ArrayList.
          ArrayList<String> subContents = new ArrayList<String>();

          // Secound put the class into uninstaller.jar
          for (Object o : ((List) contents)) {
            byte[] buffer = new byte[5120];
            long bytesCopied = 0;
            int bytesInBuffer;
            CustomData customData = (CustomData) o;
            // First element of the list contains the listener
            // class path;
            // remind it for later.
            if (customData.listenerName != null) {
              subContents.add(customData.listenerName);
            }
            for (String content : customData.contents) {
              if (exist.contains(content)) {
                continue;
              }
              exist.add(content);
              try {
                outJar.putNextEntry(new JarEntry(content));
              } catch (JarException je) { // Ignore, or ignore not ?? May be it is a
                // exception because
                // a doubled entry was tried, then we should
                // ignore ...
                Debug.trace("JarException in writing custom data: " + je.getMessage());
                continue;
              }
              InputStream in = getClass().getResourceAsStream("/" + content);
              if (in != null) {
                while ((bytesInBuffer = in.read(buffer)) != -1) {
                  outJar.write(buffer, 0, bytesInBuffer);
                  bytesCopied += bytesInBuffer;
                }
              } else {
                Debug.trace("custom data not found: " + content);
              }
              outJar.closeEntry();
            }
          }
          // Third we write the list into the
          // uninstaller.jar
          outJar.putNextEntry(new JarEntry(key));
          ObjectOutputStream objOut = new ObjectOutputStream(outJar);
          objOut.writeObject(subContents);
          objOut.flush();
          outJar.closeEntry();

        } else {
          outJar.putNextEntry(new JarEntry(key));
          if (contents instanceof ByteArrayOutputStream) {
            ((ByteArrayOutputStream) contents).writeTo(outJar);
          } else {
            ObjectOutputStream objOut = new ObjectOutputStream(outJar);
            objOut.writeObject(contents);
            objOut.flush();
          }
          outJar.closeEntry();
        }
      }
    }
  }
  @SuppressWarnings({"unchecked", "rawtypes"})
  private void startTag() {
    if (!finalPass) return;

    tagIndex++;

    String text;
    StringBuilder buf = new StringBuilder(scan.getToken());
    String ns = scan.getNamespace();

    boolean emptyTag = false;

    state = scan.nextToken();
    while (state != HTML && state != GEND_TAG && state != GEND_EMPTY_TAG && state != EOF) {
      if (state == GTAG_EXPR) {
        buf.append("${");
        buf.append(scan.getToken().trim());
        buf.append("}");
      } else {
        buf.append(scan.getToken());
      }
      state = scan.nextToken();
    }
    if (state == GEND_EMPTY_TAG) {
      emptyTag = true;
    }

    doNextScan = false;

    text = buf.toString();

    String tagName;
    Map attrs = new LinkedHashMap();

    Matcher m = Pattern.compile("\\s").matcher(text);

    if (m.find()) { // ignores carriage returns and new lines
      tagName = text.substring(0, m.start());
      if (state != EOF) {
        String attrTokens = text.substring(m.start(), text.length());
        populateMapWithAttributes(attrs, attrTokens);
      }
    } else {
      tagName = text;
    }

    if (state == EOF) {
      throw new GrailsTagException(
          "Unexpected end of file encountered parsing Tag ["
              + tagName
              + "] for "
              + className
              + ". Are you missing a closing brace '}'?",
          pageName,
          getCurrentOutputLineNumber());
    }

    flushTagBuffering();

    TagMeta tm = new TagMeta();
    tm.name = tagName;
    tm.namespace = ns;
    tm.hasAttributes = !attrs.isEmpty();
    tm.lineNumber = getCurrentOutputLineNumber();
    tm.emptyTag = emptyTag;
    tm.tagIndex = tagIndex;
    tagMetaStack.push(tm);

    if (GroovyPage.DEFAULT_NAMESPACE.equals(ns) && tagRegistry.isSyntaxTag(tagName)) {
      if (tagContext == null) {
        tagContext = new HashMap<Object, Object>();
        tagContext.put(GroovyPage.OUT, out);
        tagContext.put(GroovyPageParser.class, this);
      }
      GroovySyntaxTag tag = (GroovySyntaxTag) tagRegistry.newTag(tagName);
      tag.init(tagContext);
      tag.setAttributes(attrs);

      if (tag.isKeepPrecedingWhiteSpace() && currentlyBufferingWhitespace) {
        flushBufferedWhiteSpace();
      } else if (!tag.isAllowPrecedingContent() && previousContentWasNonWhitespace) {
        throw new GrailsTagException(
            "Tag ["
                + tag.getName()
                + "] cannot have non-whitespace characters directly preceding it.",
            pageName,
            getCurrentOutputLineNumber());
      } else {
        // If tag does not specify buffering of WS, we swallow it here
        clearBufferedWhiteSpace();
      }

      tag.doStartTag();

      tm.instance = tag;
    } else {
      // Custom taglibs have to always flush the whitespace, there's no
      // "allowPrecedingWhitespace" property on tags yet
      flushBufferedWhiteSpace();

      if (attrs.size() > 0) {
        FastStringWriter buffer = new FastStringWriter();
        buffer.print("[");
        for (Iterator<?> i = attrs.keySet().iterator(); i.hasNext(); ) {
          String name = (String) i.next();
          String cleanedName = name;
          if (name.startsWith("\"") && name.endsWith("\"")) {
            cleanedName = "'" + name.substring(1, name.length() - 1) + "'";
          }
          buffer.print(cleanedName);
          buffer.print(':');

          buffer.print(getExpressionText(attrs.get(name).toString()));
          if (i.hasNext()) {
            buffer.print(',');
          } else {
            buffer.print("]");
          }
        }
        attrsVarsMapDefinition.put(tagIndex, buffer.toString());
        buffer.close();
      }

      if (!emptyTag) {
        tm.bufferMode = true;
      }
    }
  }
  public void processOperation(
      String resourcePath,
      String httpMethod,
      Operation operation,
      Map<String, List<CodegenOperation>> operations,
      Path path) {
    if (operation != null) {
      if (System.getProperty("debugOperations") != null) {
        LOGGER.info(
            "processOperation: resourcePath= "
                + resourcePath
                + "\t;"
                + httpMethod
                + " "
                + operation
                + "\n");
      }
      List<String> tags = operation.getTags();
      if (tags == null) {
        tags = new ArrayList<String>();
        tags.add("default");
      }

      /*
       build up a set of parameter "ids" defined at the operation level
       per the swagger 2.0 spec "A unique parameter is defined by a combination of a name and location"
        i'm assuming "location" == "in"
      */
      Set<String> operationParameters = new HashSet<String>();
      if (operation.getParameters() != null) {
        for (Parameter parameter : operation.getParameters()) {
          operationParameters.add(generateParameterId(parameter));
        }
      }

      // need to propagate path level down to the operation
      if (path.getParameters() != null) {
        for (Parameter parameter : path.getParameters()) {
          // skip propagation if a parameter with the same name is already defined at the operation
          // level
          if (!operationParameters.contains(generateParameterId(parameter))) {
            operation.addParameter(parameter);
          }
        }
      }

      for (String tag : tags) {
        CodegenOperation co = null;
        try {
          co =
              config.fromOperation(
                  resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger);
          co.tags = new ArrayList<String>();
          co.tags.add(sanitizeTag(tag));
          config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations);

          List<Map<String, List<String>>> securities = operation.getSecurity();
          if (securities == null && swagger.getSecurity() != null) {
            securities = new ArrayList<Map<String, List<String>>>();
            for (SecurityRequirement sr : swagger.getSecurity()) {
              securities.add(sr.getRequirements());
            }
          }
          if (securities == null || securities.isEmpty()) {
            continue;
          }
          Map<String, SecuritySchemeDefinition> authMethods =
              new HashMap<String, SecuritySchemeDefinition>();
          // NOTE: Use only the first security requirement for now.
          // See the "security" field of "Swagger Object":
          //
          // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object
          //  "there is a logical OR between the security requirements"
          if (securities.size() > 1) {
            LOGGER.warn("More than 1 security requirements are found, using only the first one");
          }
          Map<String, List<String>> security = securities.get(0);
          for (String securityName : security.keySet()) {
            SecuritySchemeDefinition securityDefinition = fromSecurity(securityName);
            if (securityDefinition != null) {
              if (securityDefinition instanceof OAuth2Definition) {
                OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition;
                OAuth2Definition oauth2Operation = new OAuth2Definition();
                oauth2Operation.setType(oauth2Definition.getType());
                oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl());
                oauth2Operation.setFlow(oauth2Definition.getFlow());
                oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl());
                oauth2Operation.setScopes(new HashMap<String, String>());
                for (String scope : security.get(securityName)) {
                  if (oauth2Definition.getScopes().containsKey(scope)) {
                    oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope));
                  }
                }
                authMethods.put(securityName, oauth2Operation);
              } else {
                authMethods.put(securityName, securityDefinition);
              }
            }
          }
          if (!authMethods.isEmpty()) {
            co.authMethods = config.fromSecurity(authMethods);
            co.hasAuthMethods = true;
          }
        } catch (Exception ex) {
          String msg =
              "Could not process operation:\n" //
                  + "  Tag: "
                  + tag
                  + "\n" //
                  + "  Operation: "
                  + operation.getOperationId()
                  + "\n" //
                  + "  Resource: "
                  + httpMethod
                  + " "
                  + resourcePath
                  + "\n" //
                  + "  Definitions: "
                  + swagger.getDefinitions()
                  + "\n" //
                  + "  Exception: "
                  + ex.getMessage();
          throw new RuntimeException(msg, ex);
        }
      }
    }
  }
  public static boolean doPrepare(
      final Module module, final List<String> errorMessages, final List<String> successMessages) {
    final String pluginName = module.getName();
    final String defaultPath =
        new File(module.getModuleFilePath()).getParent() + File.separator + pluginName;
    final HashSet<Module> modules = new HashSet<Module>();
    PluginBuildUtil.getDependencies(module, modules);
    modules.add(module);
    final Set<Library> libs = new HashSet<Library>();
    for (Module dep : modules) {
      PluginBuildUtil.getLibraries(dep, libs);
    }

    final Map<Module, String> jpsModules = collectJpsPluginModules(module);
    modules.removeAll(jpsModules.keySet());

    final boolean isZip = !libs.isEmpty() || !jpsModules.isEmpty();
    final String oldPath = defaultPath + (isZip ? JAR_EXTENSION : ZIP_EXTENSION);
    final File oldFile = new File(oldPath);
    if (oldFile.exists()) {
      if (Messages.showYesNoDialog(
              module.getProject(),
              DevKitBundle.message("suggest.to.delete", oldPath),
              DevKitBundle.message("info.message"),
              Messages.getInformationIcon())
          == Messages.YES) {
        FileUtil.delete(oldFile);
      }
    }

    final String dstPath = defaultPath + (isZip ? ZIP_EXTENSION : JAR_EXTENSION);
    final File dstFile = new File(dstPath);
    return clearReadOnly(module.getProject(), dstFile)
        && ProgressManager.getInstance()
            .runProcessWithProgressSynchronously(
                new Runnable() {
                  public void run() {

                    final ProgressIndicator progressIndicator =
                        ProgressManager.getInstance().getProgressIndicator();
                    if (progressIndicator != null) {
                      progressIndicator.setText(
                          DevKitBundle.message("prepare.for.deployment.common"));
                      progressIndicator.setIndeterminate(true);
                    }
                    try {
                      File jarFile = preparePluginsJar(module, modules);
                      if (isZip) {
                        processLibrariesAndJpsPlugins(
                            jarFile, dstFile, pluginName, libs, jpsModules, progressIndicator);
                      } else {
                        FileUtil.copy(jarFile, dstFile);
                      }
                      LocalFileSystem.getInstance()
                          .refreshIoFiles(Collections.singleton(dstFile), true, false, null);
                      successMessages.add(
                          DevKitBundle.message(
                              "saved.message", isZip ? 1 : 2, pluginName, dstPath));
                    } catch (final IOException e) {
                      errorMessages.add(e.getMessage() + "\n(" + dstPath + ")");
                    }
                  }
                },
                DevKitBundle.message("prepare.for.deployment", pluginName),
                true,
                module.getProject());
  }
 public boolean emptySource() {
   return mySources.isEmpty();
 }
Beispiel #29
0
  // void processEvents() {
  public void run() {
    System.out.println("WatchDir Thread INFO: priority=" + Thread.currentThread().getPriority());
    for (; ; ) {
      // wait for key to be signalled
      System.out.println("WatchDir INFO: restarting loop...acquiring new key");
      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        return;
      }

      Path dir = keys.get(key);
      if (dir == null) {
        System.err.println("WatchKey not recognized!!");
        continue;
      }

      for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind kind = event.kind();
        // TBD - provide example of how OVERFLOW event is handled
        if (kind == OVERFLOW) {
          System.out.println("Encountered OVERFLOW Event - " + event);
          continue;
        }

        // Context for directory entry event is the file name of entry
        WatchEvent<Path> ev = cast(event);
        Path name = ev.context();
        Path child = dir.resolve(name);

        // print out event
        System.out.format("[WatchDir] %s: %s\n", event.kind().name(), child);

        // if directory is created, and watching recursively, then
        // register it and its sub-directories
        if (recursive && (kind == ENTRY_CREATE)) {
          try {
            if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
              registerAll(child);
            }
          } catch (IOException x) {
            // ignore to keep sample readbale
          }
        }

        long t = System.currentTimeMillis();
        if (!Folder.dontWatch.contains(Folder.getInternalPath(child))) {
          Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
          System.out.println(
              "WatchDir#"
                  + key
                  + " INFO: path="
                  + child
                  + ", internal="
                  + Folder.getInternalPath(child)
                  + " is NOT in don't watch list. Forwarding it to other peers. @"
                  + Main.timeToString(t)); // DEBUG
          forwardToItopic(kind, child);
        } else {
          Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
          System.out.println(
              "WatchDir#"
                  + key
                  + " INFO: path="
                  + child
                  + ", internal="
                  + Folder.getInternalPath(child)
                  + " IS in the don't watch list. NOT forwarding. @"
                  + Main.timeToString(t)); // DEBUG
          // try{
          //     Thread.sleep(minDelayBtwnWatchEvents);
          // } catch(InterruptedException ex) {
          //     System.err.println("Exception:"+ex+" while trying to sleep WatchDir thread");
          //     ex.printStackTrace();
          // }
        }
      }

      // reset key and remove from set if directory no longer accessible
      boolean valid = key.reset();
      if (!valid) {
        keys.remove(key);

        // all directories are inaccessible
        if (keys.isEmpty()) {
          break;
        }
      }
    }
  }
Beispiel #30
0
 /** @return true if ISOMsg has at least one field */
 public boolean hasFields() {
   return !fields.isEmpty();
 }