Ejemplo n.º 1
0
 public void addTick(Cam c) {
   tickArr.add(new Tick(hs1.getSliderPos(), hsYPos, c, hs1.getPosInSeconds()));
   // set the older ticks to inactive
   for (int i = 0; i < tickArr.size() - 1; i++) {
     tickArr.get(i).setToInActive();
   }
   // sort the ticks in case one was placed before an existing tick
   Collections.sort(tickArr);
 }
 static {
   Map<String, CompressingStreamFactory> temp = new HashMap<>(11);
   temp.put(GZIP_ENCODING, GZIP_CSF);
   temp.put(X_GZIP_ENCODING, GZIP_CSF);
   temp.put(COMPRESS_ENCODING, ZIP_CSF);
   temp.put(X_COMPRESS_ENCODING, ZIP_CSF);
   temp.put(DEFLATE_ENCODING, DEFLATE_CSF);
   FACTORY_MAP = Collections.unmodifiableMap(temp);
 }
 static {
   List<String> temp = new ArrayList<>(6);
   temp.add(GZIP_ENCODING);
   temp.add(DEFLATE_ENCODING);
   temp.add(COMPRESS_ENCODING);
   temp.add(X_GZIP_ENCODING);
   temp.add(X_COMPRESS_ENCODING);
   temp.add(NO_ENCODING);
   SUPPORTED_ENCODINGS = Collections.unmodifiableList(temp);
 }
Ejemplo n.º 4
0
 @Override
 public Iterable<DataKey> getSubKeys() {
   final Tag tag = this.findLastTag(this.path, false);
   if (!(tag instanceof CompoundTag)) {
     return (Iterable<DataKey>) Collections.emptyList();
   }
   final List<DataKey> subKeys = (List<DataKey>) Lists.newArrayList();
   for (final String name : ((CompoundTag) tag).getValue().keySet()) {
     subKeys.add(new NBTKey(this.createRelativeKey(name)));
   }
   return subKeys;
 }
 static {
   FILE_UTILS = FileUtils.getFileUtils();
   AntClassLoader.pathMap = Collections.synchronizedMap(new HashMap<String, String>());
   AntClassLoader.subClassToLoad = null;
   CONSTRUCTOR_ARGS = new Class[] {ClassLoader.class, Project.class, Path.class, Boolean.TYPE};
   if (JavaEnvUtils.isAtLeastJavaVersion("1.5")) {
     try {
       AntClassLoader.subClassToLoad =
           Class.forName("org.apache.tools.ant.loader.AntClassLoader5");
     } catch (ClassNotFoundException ex) {
     }
   }
 }
 public static void main(String[] args) throws Exception {
   int iterations = 0;
   File zFile1 = new File(System.getProperty("test.src", "."), "pkware123456789012345.zip");
   while (iterations < 2500) {
     ZipFile zipFile = new ZipFile(zFile1);
     List entries = Collections.list(zipFile.entries());
     for (Iterator it = entries.iterator(); it.hasNext(); ) {
       ZipEntry zipEntry = (ZipEntry) it.next();
       InputStream in = zipFile.getInputStream(zipEntry);
       in.close();
     }
     iterations++;
   }
 }
Ejemplo n.º 7
0
  /**
   * @param fld Folder with files to match.
   * @param ptrn Pattern to match against file name.
   * @return Collection of matched files.
   */
  public static List<VisorLogFile> matchedFiles(File fld, final String ptrn) {
    List<VisorLogFile> files =
        fileTree(
            fld,
            MAX_FOLDER_DEPTH,
            new FileFilter() {
              @Override
              public boolean accept(File f) {
                return !f.isHidden()
                    && (f.isDirectory() || f.isFile() && f.getName().matches(ptrn));
              }
            });

    Collections.sort(files, LAST_MODIFIED);

    return files;
  }
Ejemplo n.º 8
0
  /**
   * Finds all files in folder and in it's sub-tree of specified depth.
   *
   * @param file Starting folder
   * @param maxDepth Depth of the tree. If 1 - just look in the folder, no sub-folders.
   * @param filter file filter.
   * @return List of found files.
   */
  public static List<VisorLogFile> fileTree(File file, int maxDepth, @Nullable FileFilter filter) {
    if (file.isDirectory()) {
      File[] files = (filter == null) ? file.listFiles() : file.listFiles(filter);

      if (files == null) return Collections.emptyList();

      List<VisorLogFile> res = new ArrayList<>(files.length);

      for (File f : files) {
        if (f.isFile() && f.length() > 0) res.add(new VisorLogFile(f));
        else if (maxDepth > 1) res.addAll(fileTree(f, maxDepth - 1, filter));
      }

      return res;
    }

    return F.asList(new VisorLogFile(file));
  }
Ejemplo n.º 9
0
 @Override
 public Map<String, Object> getValuesDeep() {
   final Tag tag = this.findLastTag(this.path, false);
   if (!(tag instanceof CompoundTag)) {
     return Collections.emptyMap();
   }
   final Queue<Node> node =
       new ArrayDeque<Node>(
           (Collection<? extends Node>) ImmutableList.of((Object) new Node(tag)));
   final Map<String, Object> values = (Map<String, Object>) Maps.newHashMap();
   while (!node.isEmpty()) {
     final Node root = node.poll();
     for (final Map.Entry<String, Tag> entry : root.values.entrySet()) {
       final String key = this.createRelativeKey(root.parent, entry.getKey());
       if (entry.getValue() instanceof CompoundTag) {
         node.add(new Node(key, entry.getValue()));
       } else {
         values.put(key, entry.getValue().getValue());
       }
     }
   }
   return values;
 }
Ejemplo n.º 10
0
 public java.util.List<AirspaceEntry> getEntries() {
   return Collections.unmodifiableList(this.entryList);
 }
Ejemplo n.º 11
0
  private void prepareToDraw() {

    if (forwardSlot0 != null) {
      forwardSlot0.setCgview(p);
      forwardSlot0.setFeatureThickness(featureThickness);
    }
    if (forwardSlot1 != null) {
      forwardSlot1.setCgview(p);
      forwardSlot1.setFeatureThickness(featureThickness);
    }
    if (forwardSlot2 != null) {
      forwardSlot2.setCgview(p);
      forwardSlot2.setFeatureThickness(featureThickness);
    }
    if (forwardSlot3 != null) {
      forwardSlot3.setCgview(p);
      forwardSlot3.setFeatureThickness(featureThickness);
    }
    if (forwardSlot4 != null) {
      forwardSlot4.setCgview(p);
      forwardSlot4.setFeatureThickness(featureThickness);
    }
    if (forwardSlot5 != null) {
      forwardSlot5.setCgview(p);
      forwardSlot5.setFeatureThickness(featureThickness);
    }
    if (forwardSlot6 != null) {
      forwardSlot6.setCgview(p);
      forwardSlot6.setFeatureThickness(featureThickness);
    }
    if (forwardSlot7 != null) {
      forwardSlot7.setCgview(p);
      forwardSlot7.setFeatureThickness(featureThickness);
    }

    if (reverseSlot0 != null) {
      reverseSlot0.setCgview(p);
      reverseSlot0.setFeatureThickness(featureThickness);
    }
    if (reverseSlot1 != null) {
      reverseSlot1.setCgview(p);
      reverseSlot1.setFeatureThickness(featureThickness);
    }
    if (reverseSlot2 != null) {
      reverseSlot2.setCgview(p);
      reverseSlot2.setFeatureThickness(featureThickness);
    }
    if (reverseSlot3 != null) {
      reverseSlot3.setCgview(p);
      reverseSlot3.setFeatureThickness(featureThickness);
    }
    if (reverseSlot4 != null) {
      reverseSlot4.setCgview(p);
      reverseSlot4.setFeatureThickness(featureThickness);
    }
    if (reverseSlot5 != null) {
      reverseSlot5.setCgview(p);
      reverseSlot5.setFeatureThickness(featureThickness);
    }
    if (reverseSlot6 != null) {
      reverseSlot6.setCgview(p);
      reverseSlot6.setFeatureThickness(featureThickness);
    }
    if (reverseSlot7 != null) {
      reverseSlot7.setCgview(p);
      reverseSlot7.setFeatureThickness(featureThickness);
    }

    if (restrictionSlot != null) {
      restrictionSlot.setCgview(p);
      restrictionSlot.setFeatureThickness(featureThickness);
    }

    // send settings to p
    if (showTitle) {
      p.setTitle(title);
    }
    p.setWidth(imageWidth);
    p.setHeight(imageHeight);
    p.setLabelsToKeep(MAXLABELS);
    p.setDrawTickMarks(drawTickMarks);
    p.setTitleFont(titleFont);
    p.setLabelFont(labelFont);
    p.setFeatureThickness(featureThickness);
    p.setBackboneThickness(backboneThickness);
    p.setFeatureSlotSpacing(featureSpacing);
    p.setLegendFont(legendFont);
    p.setTickLength(tickLength);
    p.setLabelLineLength(labelLineLength);
    p.setLabelPlacementQuality(labelPlacementQuality);
    p.setUseColoredLabelBackgrounds(useColoredLabelBackground);
    p.setShowBorder(showBorder);
    p.setShowShading(showShading);
    p.setShadingProportion(shadingProportion);
    p.setUseInnerLabels(useInnerLabels);
    p.setMoveInnerLabelsToOuter(moveInnerLabelsToOuter);
    p.setWarningFont(rulerFont);
    p.setRulerFont(rulerFont);

    // if not drawing labels, don't show message.
    if (!(showLabels)) {
      p.setShowWarning(false);
    }

    // set backboneRadius based on smallest image dimension
    int smallestDimension = Math.min(imageWidth, imageHeight);
    if (smallestDimension <= 750) {
      p.setBackboneRadius(0.50d * (double) smallestDimension / 2.0d);
    } else {
      p.setBackboneRadius(0.50d * 750.0d / 2.0d);
    }

    // check coloredLabels
    if (!(useColoredLabels)) {
      if (colorScheme == REGULAR) {
        p.setGlobalLabelColor((Color) MAP_ITEM_COLORS.get("titleFont"));
      } else if (colorScheme == INVERSE) {
        p.setGlobalLabelColor((Color) MAP_ITEM_COLORS_INVERSE.get("titleFont"));
      }
    }

    // set map item colors
    if (colorScheme == REGULAR) {
      p.setLongTickColor((Color) MAP_ITEM_COLORS.get("tick"));
      p.setShortTickColor((Color) MAP_ITEM_COLORS.get("partialTick"));
      p.setZeroTickColor((Color) MAP_ITEM_COLORS.get("zeroLine"));
      p.setRulerFontColor((Color) MAP_ITEM_COLORS.get("rulerFont"));
      p.setBackboneColor((Color) MAP_ITEM_COLORS.get("backbone"));
      p.setTitleFontColor((Color) MAP_ITEM_COLORS.get("titleFont"));
      p.setWarningFontColor((Color) MAP_ITEM_COLORS.get("titleFont"));
      p.setBackgroundColor((Color) MAP_ITEM_COLORS.get("background"));
    } else if (colorScheme == INVERSE) {
      p.setLongTickColor((Color) MAP_ITEM_COLORS_INVERSE.get("tick"));
      p.setShortTickColor((Color) MAP_ITEM_COLORS_INVERSE.get("partialTick"));
      p.setZeroTickColor((Color) MAP_ITEM_COLORS_INVERSE.get("zeroLine"));
      p.setRulerFontColor((Color) MAP_ITEM_COLORS_INVERSE.get("rulerFont"));
      p.setBackboneColor((Color) MAP_ITEM_COLORS_INVERSE.get("backbone"));
      p.setTitleFontColor((Color) MAP_ITEM_COLORS_INVERSE.get("titleFont"));
      p.setWarningFontColor((Color) MAP_ITEM_COLORS_INVERSE.get("titleFont"));
      p.setBackgroundColor((Color) MAP_ITEM_COLORS_INVERSE.get("background"));
    }

    // build legend
    if ((showLegend) && (DRAW_LEGEND_ITEMS.size() > 0)) {
      // create legend
      legend = new Legend(p);
      legend.setAllowLabelClash(allowLabelClashLegend);
      legend.setBackgroundOpacity(0.5f);
      legend.setFont(legendFont);
      legend.setPosition(legendPosition);
      if (colorScheme == REGULAR) {
        legend.setBackgroundColor((Color) MAP_ITEM_COLORS.get("background"));
        legend.setFontColor((Color) MAP_ITEM_COLORS.get("titleFont"));
      } else if (colorScheme == INVERSE) {
        legend.setBackgroundColor((Color) MAP_ITEM_COLORS_INVERSE.get("background"));
        legend.setFontColor((Color) MAP_ITEM_COLORS_INVERSE.get("titleFont"));
      }

      LegendItem legendItem;

      Enumeration legendEntries = DRAW_LEGEND_ITEMS.keys();
      ArrayList list = new ArrayList();
      while (legendEntries.hasMoreElements()) {
        list.add(legendEntries.nextElement());
      }
      Collections.sort(list);
      Iterator i = list.iterator();

      while (i.hasNext()) {
        String key = (String) i.next();
        legendItem = new LegendItem(legend);
        legendItem.setDrawSwatch(SWATCH_SHOW);
        legendItem.setLabel((String) LEGEND_ITEM_NAMES.get(key));
        if (colorScheme == REGULAR) {
          legendItem.setSwatchColor((Color) FEATURE_COLORS.get(key));
        } else if (colorScheme == INVERSE) {
          legendItem.setSwatchColor((Color) FEATURE_COLORS_INVERSE.get(key));
        }
      }
    }

    // set message
    if (showMessage) {
      legend = new Legend(p);
      legend.setAllowLabelClash(false);
      legend.setBackgroundOpacity(0.5f);
      legend.setFont(messageFont);
      legend.setPosition(LEGEND_LOWER_RIGHT);
      LegendItem legendItem;

      if (colorScheme == REGULAR) {
        legend.setBackgroundColor((Color) MAP_ITEM_COLORS.get("background"));
        legend.setFontColor((Color) MAP_ITEM_COLORS.get("titleFont"));
        legendItem = new LegendItem(legend);
        legendItem.setLabel(message);
        legendItem.setDrawSwatch(SWATCH_NO_SHOW);
      } else if (colorScheme == INVERSE) {
        legend.setBackgroundColor((Color) MAP_ITEM_COLORS_INVERSE.get("background"));
        legend.setFontColor((Color) MAP_ITEM_COLORS_INVERSE.get("titleFont"));
        legendItem = new LegendItem(legend);
        legendItem.setLabel(message);
        legendItem.setDrawSwatch(SWATCH_NO_SHOW);
      }
    }
  }
Ejemplo n.º 12
0
 public Iterable<ZipEntry> getEntries(final String name) {
   final List<ZipEntry> entriesOfThatName = this.nameMap.get(name);
   return (entriesOfThatName != null) ? entriesOfThatName : Collections.emptyList();
 }
Ejemplo n.º 13
0
 public Enumeration<ZipEntry> getEntriesInPhysicalOrder() {
   final ZipEntry[] allEntries = this.entries.toArray(new ZipEntry[0]);
   Arrays.sort(allEntries, this.OFFSET_COMPARATOR);
   return Collections.enumeration(Arrays.asList(allEntries));
 }
Ejemplo n.º 14
0
 public Enumeration<ZipEntry> getEntries() {
   return Collections.enumeration(this.entries);
 }
Ejemplo n.º 15
0
/**
 * Implementations of this abstract class can add compression of a particular type to a given {@link
 * OutputStream}. They each return a {@link CompressingOutputStream}, which is just a thin wrapper
 * on top of an {@link OutputStream} that adds the ability to "finish" a stream (see {@link
 * CompressingOutputStream}).
 *
 * <p>
 *
 * <p>This class contains implementations based on several popular compression algorithms, such as
 * gzip. For example, the gzip implementation can decorate an {@link OutputStream} using an instance
 * of {@link GZIPOutputStream} and in that way add gzip compression to the stream.
 *
 * @author Sean Owen
 */
abstract class CompressingStreamFactory {
  /** "No encoding" content type: "identity". */
  static final String NO_ENCODING = "identity";

  private static final Logger LOG = LoggerFactory.getLogger(CompressingStreamFactory.class);
  /** Implementation based on {@link GZIPOutputStream} and {@link GZIPInputStream}. */
  private static final CompressingStreamFactory GZIP_CSF = new GZIPCompressingStreamFactory();
  /** Implementation based on {@link ZipOutputStream} and {@link ZipInputStream}. */
  private static final CompressingStreamFactory ZIP_CSF = new ZipCompressingStreamFactory();
  /** Implementation based on {@link DeflaterOutputStream}. */
  private static final CompressingStreamFactory DEFLATE_CSF = new DeflateCompressingStreamFactory();

  private static final String GZIP_ENCODING = "gzip";
  private static final String X_GZIP_ENCODING = "x-gzip";
  private static final String DEFLATE_ENCODING = "deflate";
  private static final String COMPRESS_ENCODING = "compress";
  private static final String X_COMPRESS_ENCODING = "x-compress";
  static final List<String> ALL_COMPRESSION_ENCODINGS =
      Collections.unmodifiableList(
          Arrays.asList(
              GZIP_ENCODING,
              DEFLATE_ENCODING,
              COMPRESS_ENCODING,
              X_GZIP_ENCODING,
              X_COMPRESS_ENCODING));

  /** "Any encoding" content type: the "*" wildcard. */
  private static final String ANY_ENCODING = "*";

  /** Ordered list of preferred encodings, from most to least preferred */
  private static final List<String> SUPPORTED_ENCODINGS;
  /**
   * Cache mapping previously seen "Accept-Encoding" header Strings to an appropriate instance of
   * {@link CompressingStreamFactory}.
   */
  private static final Map<String, String> BEST_ENCODING_CACHE =
      Collections.synchronizedMap(new HashMap<String, String>(101));
  /** Maps content type String to appropriate implementation of {@link CompressingStreamFactory}. */
  private static final Map<String, CompressingStreamFactory> FACTORY_MAP;

  private static final Pattern COMMA = Pattern.compile(",");

  static {
    List<String> temp = new ArrayList<>(6);
    temp.add(GZIP_ENCODING);
    temp.add(DEFLATE_ENCODING);
    temp.add(COMPRESS_ENCODING);
    temp.add(X_GZIP_ENCODING);
    temp.add(X_COMPRESS_ENCODING);
    temp.add(NO_ENCODING);
    SUPPORTED_ENCODINGS = Collections.unmodifiableList(temp);
  }

  static {
    Map<String, CompressingStreamFactory> temp = new HashMap<>(11);
    temp.put(GZIP_ENCODING, GZIP_CSF);
    temp.put(X_GZIP_ENCODING, GZIP_CSF);
    temp.put(COMPRESS_ENCODING, ZIP_CSF);
    temp.put(X_COMPRESS_ENCODING, ZIP_CSF);
    temp.put(DEFLATE_ENCODING, DEFLATE_CSF);
    FACTORY_MAP = Collections.unmodifiableMap(temp);
  }

  private static OutputStream maybeWrapStatsOutputStream(
      OutputStream outputStream,
      CompressingFilterContext context,
      CompressingFilterStats.StatsField field) {
    assert outputStream != null;
    OutputStream result;
    if (context.isStatsEnabled()) {
      CompressingFilterStats stats = context.getStats();
      CompressingFilterStats.OutputStatsCallback callbackOutput =
          stats.getOutputStatsCallback(field);
      result = new StatsOutputStream(outputStream, callbackOutput);
    } else {
      result = outputStream;
    }
    return result;
  }

  private static InputStream maybeWrapStatsInputStream(
      InputStream inputStream,
      CompressingFilterContext context,
      CompressingFilterStats.StatsField field) {
    assert inputStream != null;
    InputStream result;
    if (context.isStatsEnabled()) {
      CompressingFilterStats stats = context.getStats();
      CompressingFilterStats.InputStatsCallback callbackInput = stats.getInputStatsCallback(field);
      result = new StatsInputStream(inputStream, callbackInput);
    } else {
      result = inputStream;
    }
    return result;
  }

  private static boolean isSupportedResponseContentEncoding(String contentEncoding) {
    return NO_ENCODING.equals(contentEncoding) || FACTORY_MAP.containsKey(contentEncoding);
  }

  static boolean isSupportedRequestContentEncoding(String contentEncoding) {
    return NO_ENCODING.equals(contentEncoding) || FACTORY_MAP.containsKey(contentEncoding);
  }

  /**
   * Returns the instance associated to the given content encoding.
   *
   * @param contentEncoding content encoding (e.g. "gzip")
   * @return instance for content encoding
   */
  static CompressingStreamFactory getFactoryForContentEncoding(String contentEncoding) {
    assert FACTORY_MAP.containsKey(contentEncoding);
    return FACTORY_MAP.get(contentEncoding);
  }

  /**
   * Determines best content encoding for the response, based on the request -- in particular, based
   * on its "Accept-Encoding" header.
   *
   * @param httpRequest request
   * @return best content encoding
   */
  static String getBestContentEncoding(HttpServletRequest httpRequest) {

    String forcedEncoding = (String) httpRequest.getAttribute(CompressingFilter.FORCE_ENCODING_KEY);
    String bestEncoding;
    if (forcedEncoding != null) {

      bestEncoding = forcedEncoding;

    } else {

      String acceptEncodingHeader =
          httpRequest.getHeader(CompressingHttpServletResponse.ACCEPT_ENCODING_HEADER);
      if (acceptEncodingHeader == null) {

        bestEncoding = NO_ENCODING;

      } else {

        bestEncoding = BEST_ENCODING_CACHE.get(acceptEncodingHeader);

        if (bestEncoding == null) {

          // No cached value; must parse header to determine best encoding
          // I don't synchronize on bestEncodingCache; it's not worth it to avoid the rare case
          // where
          // two thread get in here and both parse the header. It's only a tiny bit of extra work,
          // and
          // avoids the synchronization overhead.

          if (acceptEncodingHeader.indexOf((int) ',') >= 0) {
            // multiple encodings are accepted
            bestEncoding = selectBestEncoding(acceptEncodingHeader);
          } else {
            // one encoding is accepted
            bestEncoding = parseBestEncoding(acceptEncodingHeader);
          }

          BEST_ENCODING_CACHE.put(acceptEncodingHeader, bestEncoding);
        }
      }
    }

    // User-specified encoding might not be supported
    if (!isSupportedResponseContentEncoding(bestEncoding)) {
      bestEncoding = NO_ENCODING;
    }

    return bestEncoding;
  }

  private static String parseBestEncoding(String acceptEncodingHeader) {
    ContentEncodingQ contentEncodingQ = parseContentEncodingQ(acceptEncodingHeader);
    String contentEncoding = contentEncodingQ.getContentEncoding();
    if (contentEncodingQ.getQ() > 0.0) {
      if (ANY_ENCODING.equals(contentEncoding)) {
        return SUPPORTED_ENCODINGS.get(0);
      } else if (SUPPORTED_ENCODINGS.contains(contentEncoding)) {
        return contentEncoding;
      }
    }
    return NO_ENCODING;
  }

  @SuppressWarnings("squid:S1244")
  private static String selectBestEncoding(String acceptEncodingHeader) {
    // multiple encodings are accepted; determine best one

    Collection<String> bestEncodings = new HashSet<>(3);
    double bestQ = 0.0;
    Collection<String> unacceptableEncodings = new HashSet<>(3);
    boolean willAcceptAnything = false;

    for (String token : COMMA.split(acceptEncodingHeader)) {
      ContentEncodingQ contentEncodingQ = parseContentEncodingQ(token);
      String contentEncoding = contentEncodingQ.getContentEncoding();
      double q = contentEncodingQ.getQ();
      if (ANY_ENCODING.equals(contentEncoding)) {
        willAcceptAnything = q > 0.0;
      } else if (SUPPORTED_ENCODINGS.contains(contentEncoding)) {
        if (q > 0.0) {
          // This is a header quality comparison.
          // So it is safe to suppress warning squid:S1244
          if (q == bestQ) {
            bestEncodings.add(contentEncoding);
          } else if (q > bestQ) {
            bestQ = q;
            bestEncodings.clear();
            bestEncodings.add(contentEncoding);
          }
        } else {
          unacceptableEncodings.add(contentEncoding);
        }
      }
    }

    if (bestEncodings.isEmpty()) {
      // nothing was acceptable to us
      if (willAcceptAnything) {
        if (unacceptableEncodings.isEmpty()) {
          return SUPPORTED_ENCODINGS.get(0);
        } else {
          for (String encoding : SUPPORTED_ENCODINGS) {
            if (!unacceptableEncodings.contains(encoding)) {
              return encoding;
            }
          }
        }
      }
    } else {
      for (String encoding : SUPPORTED_ENCODINGS) {
        if (bestEncodings.contains(encoding)) {
          return encoding;
        }
      }
    }

    return NO_ENCODING;
  }

  private static ContentEncodingQ parseContentEncodingQ(String contentEncodingString) {

    double q = 1.0;

    int qvalueStartIndex = contentEncodingString.indexOf((int) ';');
    String contentEncoding;
    if (qvalueStartIndex >= 0) {
      contentEncoding = contentEncodingString.substring(0, qvalueStartIndex).trim();
      String qvalueString = contentEncodingString.substring(qvalueStartIndex + 1).trim();
      if (qvalueString.startsWith("q=")) {
        try {
          q = Double.parseDouble(qvalueString.substring(2));
        } catch (NumberFormatException ignored) {
          // That's bad -- browser sent an invalid number. All we can do is ignore it, and
          // pretend that no q value was specified, so that it effectively defaults to 1.0
          LOG.trace("Couldn't parse a Double from {}.", qvalueString.substring(2), ignored);
        }
      }
    } else {
      contentEncoding = contentEncodingString.trim();
    }

    return new ContentEncodingQ(contentEncoding, q);
  }

  abstract CompressingOutputStream getCompressingStream(
      OutputStream servletOutputStream, CompressingFilterContext context) throws IOException;

  abstract CompressingInputStream getCompressingStream(
      InputStream servletInputStream, CompressingFilterContext context) throws IOException;

  private static final class ContentEncodingQ {

    private final String contentEncoding;
    private final double q;

    private ContentEncodingQ(String contentEncoding, double q) {
      assert contentEncoding != null && contentEncoding.length() > 0;
      this.contentEncoding = contentEncoding;
      this.q = q;
    }

    String getContentEncoding() {
      return contentEncoding;
    }

    double getQ() {
      return q;
    }

    @Override
    public String toString() {
      return contentEncoding + ";q=" + q;
    }
  }

  private static class GZIPCompressingStreamFactory extends CompressingStreamFactory {
    @Override
    CompressingOutputStream getCompressingStream(
        final OutputStream outputStream, final CompressingFilterContext context)
        throws IOException {
      return new CompressingOutputStream() {
        private final DeflaterOutputStream gzipOutputStream =
            new GZIPOutputStream(
                CompressingStreamFactory.maybeWrapStatsOutputStream(
                    outputStream,
                    context,
                    CompressingFilterStats.StatsField.RESPONSE_COMPRESSED_BYTES));
        private final OutputStream statsOutputStream =
            CompressingStreamFactory.maybeWrapStatsOutputStream(
                gzipOutputStream, context, CompressingFilterStats.StatsField.RESPONSE_INPUT_BYTES);

        @Override
        public OutputStream getCompressingOutputStream() {
          return statsOutputStream;
        }

        @Override
        public void finish() throws IOException {
          gzipOutputStream.finish();
        }
      };
    }

    @Override
    CompressingInputStream getCompressingStream(
        final InputStream inputStream, final CompressingFilterContext context) {
      return new CompressingInputStream() {
        @Override
        public InputStream getCompressingInputStream() throws IOException {
          return CompressingStreamFactory.maybeWrapStatsInputStream(
              new GZIPInputStream(
                  CompressingStreamFactory.maybeWrapStatsInputStream(
                      inputStream,
                      context,
                      CompressingFilterStats.StatsField.REQUEST_COMPRESSED_BYTES)),
              context,
              CompressingFilterStats.StatsField.REQUEST_INPUT_BYTES);
        }
      };
    }
  }

  private static class ZipCompressingStreamFactory extends CompressingStreamFactory {
    @Override
    CompressingOutputStream getCompressingStream(
        final OutputStream outputStream, final CompressingFilterContext context) {
      return new CompressingOutputStream() {
        private final DeflaterOutputStream zipOutputStream =
            new ZipOutputStream(
                CompressingStreamFactory.maybeWrapStatsOutputStream(
                    outputStream,
                    context,
                    CompressingFilterStats.StatsField.RESPONSE_COMPRESSED_BYTES));
        private final OutputStream statsOutputStream =
            CompressingStreamFactory.maybeWrapStatsOutputStream(
                zipOutputStream, context, CompressingFilterStats.StatsField.RESPONSE_INPUT_BYTES);

        @Override
        public OutputStream getCompressingOutputStream() {
          return statsOutputStream;
        }

        @Override
        public void finish() throws IOException {
          zipOutputStream.finish();
        }
      };
    }

    @Override
    CompressingInputStream getCompressingStream(
        final InputStream inputStream, final CompressingFilterContext context) {
      return new CompressingInputStream() {
        @Override
        public InputStream getCompressingInputStream() {
          return CompressingStreamFactory.maybeWrapStatsInputStream(
              new ZipInputStream(
                  CompressingStreamFactory.maybeWrapStatsInputStream(
                      inputStream,
                      context,
                      CompressingFilterStats.StatsField.REQUEST_COMPRESSED_BYTES)),
              context,
              CompressingFilterStats.StatsField.REQUEST_INPUT_BYTES);
        }
      };
    }
  }

  private static class DeflateCompressingStreamFactory extends CompressingStreamFactory {
    @Override
    CompressingOutputStream getCompressingStream(
        final OutputStream outputStream, final CompressingFilterContext context) {
      return new CompressingOutputStream() {
        private final DeflaterOutputStream deflaterOutputStream =
            new DeflaterOutputStream(
                CompressingStreamFactory.maybeWrapStatsOutputStream(
                    outputStream,
                    context,
                    CompressingFilterStats.StatsField.RESPONSE_COMPRESSED_BYTES));
        private final OutputStream statsOutputStream =
            CompressingStreamFactory.maybeWrapStatsOutputStream(
                deflaterOutputStream,
                context,
                CompressingFilterStats.StatsField.RESPONSE_INPUT_BYTES);

        @Override
        public OutputStream getCompressingOutputStream() {
          return statsOutputStream;
        }

        @Override
        public void finish() throws IOException {
          deflaterOutputStream.finish();
        }
      };
    }

    @Override
    CompressingInputStream getCompressingStream(
        final InputStream inputStream, final CompressingFilterContext context) {
      return new CompressingInputStream() {
        @Override
        public InputStream getCompressingInputStream() {
          return CompressingStreamFactory.maybeWrapStatsInputStream(
              new InflaterInputStream(
                  CompressingStreamFactory.maybeWrapStatsInputStream(
                      inputStream,
                      context,
                      CompressingFilterStats.StatsField.REQUEST_COMPRESSED_BYTES)),
              context,
              CompressingFilterStats.StatsField.REQUEST_INPUT_BYTES);
        }
      };
    }
  }
}
Ejemplo n.º 16
0
  /**
   * Grabs local events and detects if events was lost since last poll.
   *
   * @param ignite Target grid.
   * @param evtOrderKey Unique key to take last order key from node local map.
   * @param evtThrottleCntrKey Unique key to take throttle count from node local map.
   * @param evtTypes Event types to collect.
   * @param evtMapper Closure to map grid events to Visor data transfer objects.
   * @return Collections of node events
   */
  public static Collection<VisorGridEvent> collectEvents(
      Ignite ignite,
      String evtOrderKey,
      String evtThrottleCntrKey,
      final int[] evtTypes,
      IgniteClosure<Event, VisorGridEvent> evtMapper) {
    assert ignite != null;
    assert evtTypes != null && evtTypes.length > 0;

    ConcurrentMap<String, Long> nl = ignite.cluster().nodeLocalMap();

    final long lastOrder = getOrElse(nl, evtOrderKey, -1L);
    final long throttle = getOrElse(nl, evtThrottleCntrKey, 0L);

    // When we first time arrive onto a node to get its local events,
    // we'll grab only last those events that not older than given period to make sure we are
    // not grabbing GBs of data accidentally.
    final long notOlderThan = System.currentTimeMillis() - EVENTS_COLLECT_TIME_WINDOW;

    // Flag for detecting gaps between events.
    final AtomicBoolean lastFound = new AtomicBoolean(lastOrder < 0);

    IgnitePredicate<Event> p =
        new IgnitePredicate<Event>() {
          /** */
          private static final long serialVersionUID = 0L;

          @Override
          public boolean apply(Event e) {
            // Detects that events were lost.
            if (!lastFound.get() && (lastOrder == e.localOrder())) lastFound.set(true);

            // Retains events by lastOrder, period and type.
            return e.localOrder() > lastOrder
                && e.timestamp() > notOlderThan
                && F.contains(evtTypes, e.type());
          }
        };

    Collection<Event> evts = ignite.events().localQuery(p);

    // Update latest order in node local, if not empty.
    if (!evts.isEmpty()) {
      Event maxEvt = Collections.max(evts, EVTS_ORDER_COMPARATOR);

      nl.put(evtOrderKey, maxEvt.localOrder());
    }

    // Update throttle counter.
    if (!lastFound.get())
      nl.put(evtThrottleCntrKey, throttle == 0 ? EVENTS_LOST_THROTTLE : throttle - 1);

    boolean lost = !lastFound.get() && throttle == 0;

    Collection<VisorGridEvent> res = new ArrayList<>(evts.size() + (lost ? 1 : 0));

    if (lost) res.add(new VisorGridEventsLost(ignite.cluster().localNode().id()));

    for (Event e : evts) {
      VisorGridEvent visorEvt = evtMapper.apply(e);

      if (visorEvt != null) res.add(visorEvt);
    }

    return res;
  }