示例#1
1
  protected Header readHeaderFromBuffer(ByteBuffer buffer) throws WWRuntimeException {
    // Read file code - first byte
    int fileCode = buffer.get();
    if (fileCode > 5) {
      String message = Logging.getMessage("SHP.NotADBaseFile", file.getPath());
      Logging.logger().log(java.util.logging.Level.SEVERE, message);
      throw new WWRuntimeException(message);
    }

    // Last update date
    int yy = 0xFF & buffer.get(); // unsigned
    int mm = buffer.get();
    int dd = buffer.get();

    // Number of records
    int numRecords = buffer.getInt();

    // Header struct length
    int headerLength = buffer.getShort();

    // Record length
    int recordLength = buffer.getShort();

    // Assemble header
    Header header = new Header();
    header.fileCode = fileCode;
    Calendar cal = Calendar.getInstance();
    cal.set(1900 + yy, mm - 1, dd);
    header.lastModificationDate = cal.getTime();
    header.numberOfRecords = numRecords;
    header.headerLength = headerLength;
    header.recordLength = recordLength;

    return header;
  }
  private String getNotModified(String dataId, CacheData cacheData, HttpMethod httpMethod) {
    Header md5Header = httpMethod.getResponseHeader(Constants.CONTENT_MD5);
    if (null == md5Header) {
      throw new RuntimeException("RP_NO_CHANGE response not contain MD5");
    }
    String md5 = md5Header.getValue();
    if (!cacheData.getMd5().equals(md5)) {
      String lastMd5 = cacheData.getMd5();
      cacheData.setMd5(Constants.NULL);
      cacheData.setLastModifiedHeader(Constants.NULL);

      throw new RuntimeException(
          "MD5 verify error,DataID:["
              + dataId
              + "]MD5 last:["
              + lastMd5
              + "]MD5 current:["
              + md5
              + "]");
    }

    cacheData.setMd5(md5);
    changeSpacingInterval(httpMethod);
    if (log.isInfoEnabled()) {
      log.info("DataId: " + dataId + ",not changed");
    }
    return null;
  }
示例#3
0
 Message(DNSInput in) throws IOException {
   this(new Header(in));
   boolean isUpdate = (header.getOpcode() == Opcode.UPDATE);
   boolean truncated = header.getFlag(Flags.TC);
   try {
     for (int i = 0; i < 4; i++) {
       int count = header.getCount(i);
       if (count > 0) sections[i] = new ArrayList(count);
       for (int j = 0; j < count; j++) {
         int pos = in.current();
         Record rec = Record.fromWire(in, i, isUpdate);
         sections[i].add(rec);
         if (i == Section.ADDITIONAL) {
           if (rec.getType() == Type.TSIG) tsigstart = pos;
           if (rec.getType() == Type.SIG) {
             SIGRecord sig = (SIGRecord) rec;
             if (sig.getTypeCovered() == 0) sig0start = pos;
           }
         }
       }
     }
   } catch (WireParseException e) {
     if (!truncated) throw e;
   }
   size = in.current();
 }
示例#4
0
 /** Converts the Message to a String. */
 public String toString() {
   StringBuffer sb = new StringBuffer();
   OPTRecord opt = getOPT();
   if (opt != null) sb.append(header.toStringWithRcode(getRcode()) + "\n");
   else sb.append(header + "\n");
   if (isSigned()) {
     sb.append(";; TSIG ");
     if (isVerified()) sb.append("ok");
     else sb.append("invalid");
     sb.append('\n');
   }
   if (opt != null) {
     sb.append(";; OPT PSEUDOSECTION:\n");
     sb.append(";  EDNS: version: ");
     sb.append(opt.getVersion());
     sb.append(", flags:");
     if ((opt.getFlags() & ExtendedFlags.DO) != 0) {
       sb.append(" do");
     }
     sb.append("; udp: ");
     sb.append(opt.getPayloadSize());
     sb.append("\n");
   }
   for (int i = 0; i < 4; i++) {
     if (header.getOpcode() != Opcode.UPDATE) sb.append(";; " + Section.longString(i) + ":\n");
     else sb.append(";; " + Section.updString(i) + ":\n");
     sb.append(sectionToString(i) + "\n");
   }
   sb.append(";; Message size: " + numBytes() + " bytes");
   return sb.toString();
 }
示例#5
0
 /**
  * Adds the specified tuple to the page.
  *
  * @throws DbException if the page is full (no empty slots) or tupledesc is mismatch.
  * @param t The tuple to add.
  */
 public void addTuple(Tuple t) throws DbException {
   int index = header.findFirstEmptySlot();
   if (index == -1) {
     throw new DbException("No empty slot for new tuple");
   } else {
     header.setSlotVal(index, true);
     tuples[index] = t;
   }
 }
示例#6
0
  /**
   * Generates a byte array representing the contents of this page. Used to serialize this page to
   * disk.
   *
   * <p>The invariant here is that it should be possible to pass the byte array generated by
   * getPageData to the HeapPage constructor and have it produce an identical HeapPage object.
   *
   * @see #HeapPage
   * @return A byte array correspond to the bytes of this page.
   */
  public byte[] getPageData() {
    // int len = header.length*4 + BufferPool.PAGE_SIZE;
    int len = BufferPool.PAGE_SIZE;
    ByteArrayOutputStream baos = new ByteArrayOutputStream(len);
    DataOutputStream dos = new DataOutputStream(baos);

    // create the header of the page
    try {
      dos.write(header.getHeader());
    } catch (IOException e) {
      // this really shouldn't happen
      e.printStackTrace();
    }

    // create the tuples
    for (int i = 0; i < numSlots; i++) {

      // empty slot
      if (!getSlot(i)) {
        for (int j = 0; j < td.getSize(); j++) {
          try {
            dos.writeByte(0);
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        continue;
      }

      // non-empty slot
      for (int j = 0; j < td.numFields(); j++) {
        Field f = tuples[i].getField(j);
        try {
          f.serialize(dos);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    // padding
    int zerolen = BufferPool.PAGE_SIZE - numSlots * td.getSize() - header.length();
    byte[] zeroes = new byte[zerolen];
    try {
      dos.write(zeroes, 0, zerolen);
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      dos.flush();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return baos.toByteArray();
  }
示例#7
0
  protected Header readHeaderFromStream(InputStream is) throws IOException {
    ReadableByteChannel channel = Channels.newChannel(is);
    // Read header fixed portion
    ByteBuffer headerBuffer = ShapefileUtils.readByteChannelToBuffer(channel, FIXED_HEADER_LENGTH);
    Header header = this.readHeaderFromBuffer(headerBuffer);
    // Read fields description header
    int fieldsHeaderLength = header.headerLength - FIXED_HEADER_LENGTH;
    header.fieldsHeaderBuffer = ShapefileUtils.readByteChannelToBuffer(channel, fieldsHeaderLength);

    return header;
  }
示例#8
0
  private static Header parseHeader(Node parent) throws XmlParserException {
    Header header = new Header();

    NodeList nodes = parent.getChildNodes();
    for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) {
      Node node = nodes.item(nodeid);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;

      Element element = (Element) node;
      try {
        if (element.getTagName().equals("nrpeaks"))
          header.setNrPeaks(Integer.parseInt(element.getTextContent()));
        else if (element.getTagName().equals("date")) header.setDate(element.getTextContent());
        else if (element.getTagName().equals("owner")) header.setOwner(element.getTextContent());
        else if (element.getTagName().equals("description"))
          header.setDescription(element.getTextContent());
        else if (element.getTagName().equals("sets")) header.addSetInfos(parseSets(element));
        else if (element.getTagName().equals("measurements"))
          header.addMeasurementInfos(parseMeasurements(element));
        else if (element.getTagName().equals("annotations")) {
          Vector<Annotation> annotations = parseAnnotations(element);
          if (annotations != null)
            for (Annotation annotation : annotations) header.addAnnotation(annotation);
        }
      } catch (Exception e) {
        throw new XmlParserException(
            "Invalid value in header (" + element.getTagName() + "): '" + e.getMessage() + "'.");
      }
    }

    return header;
  }
示例#9
0
 public void process(final HttpResponse response, final HttpContext context)
     throws HttpException, IOException {
   HttpEntity entity = response.getEntity();
   if (entity != null) {
     Header ceheader = entity.getContentEncoding();
     if (ceheader != null) {
       HeaderElement[] codecs = ceheader.getElements();
       for (HeaderElement h : codecs) {
         if (h.getName().equalsIgnoreCase("deflate")) {
           response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
           return;
         }
       }
     }
   }
 }
示例#10
0
 /**
  * Returns the TSIG record from the ADDITIONAL section, if one is present.
  *
  * @see TSIGRecord
  * @see TSIG
  * @see Section
  */
 public TSIGRecord getTSIG() {
   int count = header.getCount(Section.ADDITIONAL);
   if (count == 0) return null;
   List l = sections[Section.ADDITIONAL];
   Record rec = (Record) l.get(count - 1);
   if (rec.type != Type.TSIG) return null;
   return (TSIGRecord) rec;
 }
  private String getSuccess(
      String dataId, String group, CacheData cacheData, HttpMethod httpMethod) {
    String configInfo = Constants.NULL;
    configInfo = getContent(httpMethod);
    if (null == configInfo) {
      throw new RuntimeException("RP_OK configInfo is null");
    }

    Header md5Header = httpMethod.getResponseHeader(Constants.CONTENT_MD5);
    if (null == md5Header) {
      throw new RuntimeException("RP_OK not contain MD5, " + configInfo);
    }
    String md5 = md5Header.getValue();
    if (!checkContent(configInfo, md5)) {
      throw new RuntimeException(
          "MD5 verify error,DataID:["
              + dataId
              + "]ConfigInfo:["
              + configInfo
              + "]MD5:["
              + md5
              + "]");
    }

    Header lastModifiedHeader = httpMethod.getResponseHeader(Constants.LAST_MODIFIED);
    if (null == lastModifiedHeader) {
      throw new RuntimeException("RP_OK result not contain lastModifiedHeader");
    }
    String lastModified = lastModifiedHeader.getValue();

    cacheData.setMd5(md5);
    cacheData.setLastModifiedHeader(lastModified);

    changeSpacingInterval(httpMethod);

    String key = makeCacheKey(dataId, group);
    contentCache.put(key, configInfo);

    StringBuilder buf = new StringBuilder();
    buf.append("dataId=").append(dataId);
    buf.append(" ,group=").append(group);
    buf.append(" ,content=").append(configInfo);
    dataLog.info(buf.toString());

    return configInfo;
  }
示例#12
0
  public void serialize(Header t, DataOutput dos) throws IOException {
    dos.writeUTF(t.getMessageId());
    CompactEndPointSerializationHelper.serialize(t.getFrom(), dos);
    dos.writeUTF(t.getMessageType());
    dos.writeUTF(t.getVerb());

    /* Serialize the message header */
    int size = t.details_.size();
    dos.writeInt(size);
    Set<String> keys = t.details_.keySet();

    for (String key : keys) {
      dos.writeUTF(key);
      byte[] value = t.details_.get(key);
      dos.writeInt(value.length);
      dos.write(value);
    }
  }
示例#13
0
 /**
  * Creates a copy of this Message. This is done by the Resolver before adding TSIG and OPT
  * records, for example.
  *
  * @see Resolver
  * @see TSIGRecord
  * @see OPTRecord
  */
 public Object clone() {
   Message m = new Message();
   for (int i = 0; i < sections.length; i++) {
     if (sections[i] != null) m.sections[i] = new LinkedList(sections[i]);
   }
   m.header = (Header) header.clone();
   m.size = size;
   return m;
 }
示例#14
0
 /** Converts the Message to a String. */
 public String toString() {
   StringBuffer sb = new StringBuffer();
   OPTRecord opt = getOPT();
   if (opt != null) sb.append(header.toStringWithRcode(getRcode()) + "\n");
   else sb.append(header + "\n");
   if (isSigned()) {
     sb.append(";; TSIG ");
     if (isVerified()) sb.append("ok");
     else sb.append("invalid");
     sb.append('\n');
   }
   for (int i = 0; i < 4; i++) {
     if (header.getOpcode() != Opcode.UPDATE) sb.append(";; " + Section.longString(i) + ":\n");
     else sb.append(";; " + Section.updString(i) + ":\n");
     sb.append(sectionToString(i) + "\n");
   }
   sb.append(";; Message size: " + numBytes() + " bytes");
   return sb.toString();
 }
示例#15
0
 void toWire(DNSOutput out) {
   header.toWire(out);
   Compression c = new Compression();
   for (int i = 0; i < 4; i++) {
     if (sections[i] == null) continue;
     for (int j = 0; j < sections[i].size(); j++) {
       Record rec = (Record) sections[i].get(j);
       rec.toWire(out, i, c);
     }
   }
 }
示例#16
0
  /* Returns true if the message could be rendered. */
  private boolean toWire(DNSOutput out, int maxLength) {
    if (maxLength < Header.LENGTH) return false;

    Header newheader = null;

    int tempMaxLength = maxLength;
    if (tsigkey != null) tempMaxLength -= tsigkey.recordLength();

    OPTRecord opt = getOPT();
    byte[] optBytes = null;
    if (opt != null) {
      optBytes = opt.toWire(Section.ADDITIONAL);
      tempMaxLength -= optBytes.length;
    }

    int startpos = out.current();
    header.toWire(out);
    Compression c = new Compression();
    int flags = header.getFlagsByte();
    int additionalCount = 0;
    for (int i = 0; i < 4; i++) {
      int skipped;
      if (sections[i] == null) continue;
      skipped = sectionToWire(out, i, c, tempMaxLength);
      if (skipped != 0 && i != Section.ADDITIONAL) {
        flags = Header.setFlag(flags, Flags.TC, true);
        out.writeU16At(header.getCount(i) - skipped, startpos + 4 + 2 * i);
        for (int j = i + 1; j < Section.ADDITIONAL; j++) out.writeU16At(0, startpos + 4 + 2 * j);
        break;
      }
      if (i == Section.ADDITIONAL) additionalCount = header.getCount(i) - skipped;
    }

    if (optBytes != null) {
      out.writeByteArray(optBytes);
      additionalCount++;
    }

    if (flags != header.getFlagsByte()) out.writeU16At(flags, startpos + 2);

    if (additionalCount != header.getCount(Section.ADDITIONAL))
      out.writeU16At(additionalCount, startpos + 10);

    if (tsigkey != null) {
      TSIGRecord tsigrec = tsigkey.generate(this, out.toByteArray(), tsigerror, querytsig);

      tsigrec.toWire(out, Section.ADDITIONAL, c);
      out.writeU16At(additionalCount + 1, startpos + 10);
    }

    return true;
  }
  /*
   * import sheet scope content from POI Sheet.
   */
  protected SSheet importSheet(Sheet poiSheet, int poiSheetIndex) {
    SSheet sheet = book.createSheet(poiSheet.getSheetName());
    sheet.setDefaultRowHeight(UnitUtil.twipToPx(poiSheet.getDefaultRowHeight()));
    // ZSS-952
    importSheetDefaultColumnWidth(poiSheet, sheet);
    // reference FreezeInfoLoaderImpl.getRowFreeze()
    sheet.getViewInfo().setNumOfRowFreeze(BookHelper.getRowFreeze(poiSheet));
    sheet.getViewInfo().setNumOfColumnFreeze(BookHelper.getColumnFreeze(poiSheet));
    sheet
        .getViewInfo()
        .setDisplayGridlines(
            poiSheet
                .isDisplayGridlines()); // Note isDisplayGridlines() and isPrintGridlines() are
                                        // different
    sheet.getViewInfo().setColumnBreaks(poiSheet.getColumnBreaks());
    sheet.getViewInfo().setRowBreaks(poiSheet.getRowBreaks());

    SPrintSetup sps = sheet.getPrintSetup();

    SHeader header = sheet.getViewInfo().getHeader();
    if (header != null) {
      header.setCenterText(poiSheet.getHeader().getCenter());
      header.setLeftText(poiSheet.getHeader().getLeft());
      header.setRightText(poiSheet.getHeader().getRight());
      sps.setHeader(header);
    }

    SFooter footer = sheet.getViewInfo().getFooter();
    if (footer != null) {
      footer.setCenterText(poiSheet.getFooter().getCenter());
      footer.setLeftText(poiSheet.getFooter().getLeft());
      footer.setRightText(poiSheet.getFooter().getRight());
      sps.setFooter(footer);
    }

    if (poiSheet.isDiffOddEven()) {
      Header poiEvenHeader = poiSheet.getEvenHeader();
      if (poiEvenHeader != null) {
        SHeader evenHeader = new HeaderFooterImpl();
        evenHeader.setCenterText(poiEvenHeader.getCenter());
        evenHeader.setLeftText(poiEvenHeader.getLeft());
        evenHeader.setRightText(poiEvenHeader.getRight());
        sps.setEvenHeader(evenHeader);
      }
      Footer poiEvenFooter = poiSheet.getEvenFooter();
      if (poiEvenFooter != null) {
        SFooter evenFooter = new HeaderFooterImpl();
        evenFooter.setCenterText(poiEvenFooter.getCenter());
        evenFooter.setLeftText(poiEvenFooter.getLeft());
        evenFooter.setRightText(poiEvenFooter.getRight());
        sps.setEvenFooter(evenFooter);
      }
    }

    if (poiSheet.isDiffFirst()) {
      Header poiFirstHeader = poiSheet.getFirstHeader();
      if (poiFirstHeader != null) {
        SHeader firstHeader = new HeaderFooterImpl();
        firstHeader.setCenterText(poiFirstHeader.getCenter());
        firstHeader.setLeftText(poiFirstHeader.getLeft());
        firstHeader.setRightText(poiFirstHeader.getRight());
        sps.setFirstHeader(firstHeader);
      }
      Footer poiFirstFooter = poiSheet.getFirstFooter();
      if (poiFirstFooter != null) {
        SFooter firstFooter = new HeaderFooterImpl();
        firstFooter.setCenterText(poiFirstFooter.getCenter());
        firstFooter.setLeftText(poiFirstFooter.getLeft());
        firstFooter.setRightText(poiFirstFooter.getRight());
        sps.setFirstFooter(firstFooter);
      }
    }

    PrintSetup poips = poiSheet.getPrintSetup();

    sps.setBottomMargin(poiSheet.getMargin(Sheet.BottomMargin));
    sps.setTopMargin(poiSheet.getMargin(Sheet.TopMargin));
    sps.setLeftMargin(poiSheet.getMargin(Sheet.LeftMargin));
    sps.setRightMargin(poiSheet.getMargin(Sheet.RightMargin));
    sps.setHeaderMargin(poiSheet.getMargin(Sheet.HeaderMargin));
    sps.setFooterMargin(poiSheet.getMargin(Sheet.FooterMargin));

    sps.setAlignWithMargins(poiSheet.isAlignMargins());
    sps.setErrorPrintMode(poips.getErrorsMode());
    sps.setFitHeight(poips.getFitHeight());
    sps.setFitWidth(poips.getFitWidth());
    sps.setHCenter(poiSheet.getHorizontallyCenter());
    sps.setLandscape(poips.getLandscape());
    sps.setLeftToRight(poips.getLeftToRight());
    sps.setPageStart(poips.getUsePage() ? poips.getPageStart() : 0);
    sps.setPaperSize(PoiEnumConversion.toPaperSize(poips.getPaperSize()));
    sps.setCommentsMode(poips.getCommentsMode());
    sps.setPrintGridlines(poiSheet.isPrintGridlines());
    sps.setPrintHeadings(poiSheet.isPrintHeadings());

    sps.setScale(poips.getScale());
    sps.setScaleWithDoc(poiSheet.isScaleWithDoc());
    sps.setDifferentOddEvenPage(poiSheet.isDiffOddEven());
    sps.setDifferentFirstPage(poiSheet.isDiffFirst());
    sps.setVCenter(poiSheet.getVerticallyCenter());

    Workbook poiBook = poiSheet.getWorkbook();
    String area = poiBook.getPrintArea(poiSheetIndex);
    if (area != null) {
      sps.setPrintArea(area);
    }

    CellRangeAddress rowrng = poiSheet.getRepeatingRows();
    if (rowrng != null) {
      sps.setRepeatingRowsTitle(rowrng.getFirstRow(), rowrng.getLastRow());
    }

    CellRangeAddress colrng = poiSheet.getRepeatingColumns();
    if (colrng != null) {
      sps.setRepeatingColumnsTitle(colrng.getFirstColumn(), colrng.getLastColumn());
    }

    sheet.setPassword(poiSheet.getProtect() ? "" : null);

    // import hashed password directly
    importPassword(poiSheet, sheet);

    // ZSS-832
    // import sheet visible
    if (poiBook.isSheetHidden(poiSheetIndex)) {
      sheet.setSheetVisible(SheetVisible.HIDDEN);
    } else if (poiBook.isSheetVeryHidden(poiSheetIndex)) {
      sheet.setSheetVisible(SheetVisible.VERY_HIDDEN);
    } else {
      sheet.setSheetVisible(SheetVisible.VISIBLE);
    }

    // ZSS-1130
    // import conditionalFormatting
    importConditionalFormatting(sheet, poiSheet);
    return sheet;
  }
示例#18
0
  /* Returns true if the message could be rendered. */
  private boolean toWire(DNSOutput out, int maxLength) {
    if (maxLength < Header.LENGTH) return false;

    Header newheader = null;

    int tempMaxLength = maxLength;
    if (tsigkey != null) tempMaxLength -= tsigkey.recordLength();

    int startpos = out.current();
    header.toWire(out);
    Compression c = new Compression();
    for (int i = 0; i < 4; i++) {
      int skipped;
      if (sections[i] == null) continue;
      skipped = sectionToWire(out, i, c, tempMaxLength);
      if (skipped != 0) {
        if (i != Section.ADDITIONAL) {
          if (newheader == null) newheader = (Header) header.clone();
          newheader.setFlag(Flags.TC);
          int count = newheader.getCount(i);
          newheader.setCount(i, count - skipped);
          for (int j = i + 1; j < 4; j++) newheader.setCount(j, 0);

          out.save();
          out.jump(startpos);
          newheader.toWire(out);
          out.restore();
        }
        break;
      }
    }

    if (tsigkey != null) {
      TSIGRecord tsigrec = tsigkey.generate(this, out.toByteArray(), tsigerror, querytsig);

      if (newheader == null) newheader = (Header) header.clone();
      tsigrec.toWire(out, Section.ADDITIONAL, c);
      newheader.incCount(Section.ADDITIONAL);

      out.save();
      out.jump(startpos);
      newheader.toWire(out);
      out.restore();
    }

    return true;
  }
示例#19
0
 /** Returns the message's rcode (error code). This incorporates the EDNS extended rcode. */
 public int getRcode() {
   int rcode = header.getRcode();
   OPTRecord opt = getOPT();
   if (opt != null) rcode += (opt.getExtendedRcode() << 4);
   return rcode;
 }
示例#20
0
 /**
  * Removes all records from a section of the Message, and adjusts the header.
  *
  * @see Record
  * @see Section
  */
 public void removeAllRecords(int section) {
   sections[section] = null;
   header.setCount(section, 0);
 }
  @Override
  protected Product readProductNodesImpl() throws IOException {
    final String s = getInput().toString();

    final File file0 = new File(s);
    final File dir = file0.getParentFile();

    final S2FilenameInfo fni0 = S2FilenameInfo.create(file0.getName());
    if (fni0 == null) {
      throw new IOException();
    }
    Header metadataHeader = null;
    final Map<Integer, BandInfo> fileMap = new HashMap<Integer, BandInfo>();
    if (dir != null) {
      File[] files =
          dir.listFiles(
              new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                  return name.endsWith(Sentinel2ProductReaderPlugIn.JP2_EXT);
                }
              });
      if (files != null) {
        for (File file : files) {
          int bandIndex = fni0.getBand(file.getName());
          if (bandIndex >= 0 && bandIndex < WAVEBAND_INFOS.length) {
            final S2WavebandInfo wavebandInfo = WAVEBAND_INFOS[bandIndex];
            BandInfo bandInfo =
                new BandInfo(
                    file, bandIndex, wavebandInfo, imageLayouts[wavebandInfo.resolution.id]);
            fileMap.put(bandIndex, bandInfo);
          }
        }
      }
      File[] metadataFiles =
          dir.listFiles(
              new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                  return name.startsWith("MTD_") && name.endsWith(".xml");
                }
              });
      if (metadataFiles != null && metadataFiles.length > 0) {
        File metadataFile = metadataFiles[0];
        try {
          metadataHeader = Header.parseHeader(metadataFile);
        } catch (JDOMException e) {
          BeamLogManager.getSystemLogger()
              .warning("Failed to parse metadata file: " + metadataFile);
        }
      } else {
        BeamLogManager.getSystemLogger().warning("No metadata file found");
      }
    }

    final ArrayList<Integer> bandIndexes = new ArrayList<Integer>(fileMap.keySet());
    Collections.sort(bandIndexes);

    if (bandIndexes.isEmpty()) {
      throw new IOException("No valid bands found.");
    }

    String prodType = "S2_MSI_" + fni0.procLevel;
    final Product product =
        new Product(
            String.format("%s_%s_%s", prodType, fni0.orbitNo, fni0.tileId),
            prodType,
            imageLayouts[S2Resolution.R10M.id].width,
            imageLayouts[S2Resolution.R10M.id].height);

    try {
      product.setStartTime(ProductData.UTC.parse(fni0.start, "yyyyMMddHHmmss"));
    } catch (ParseException e) {
      // warn
    }

    try {
      product.setEndTime(ProductData.UTC.parse(fni0.stop, "yyyyMMddHHmmss"));
    } catch (ParseException e) {
      // warn
    }

    if (metadataHeader != null) {
      SceneDescription sceneDescription = SceneDescription.create(metadataHeader);
      int tileIndex = sceneDescription.getTileIndex(fni0.tileId);
      Envelope2D tileEnvelope = sceneDescription.getTileEnvelope(tileIndex);
      Header.Tile tile = metadataHeader.getTileList().get(tileIndex);

      try {
        product.setGeoCoding(
            new CrsGeoCoding(
                tileEnvelope.getCoordinateReferenceSystem(),
                imageLayouts[S2Resolution.R10M.id].width,
                imageLayouts[S2Resolution.R10M.id].height,
                tile.tileGeometry10M.upperLeftX,
                tile.tileGeometry10M.upperLeftY,
                tile.tileGeometry10M.xDim,
                -tile.tileGeometry10M.yDim,
                0.0,
                0.0));
      } catch (FactoryException e) {
        // todo - handle e
      } catch (TransformException e) {
        // todo - handle e
      }
    }

    for (Integer bandIndex : bandIndexes) {
      final BandInfo bandInfo = fileMap.get(bandIndex);
      final Band band = product.addBand(bandInfo.wavebandInfo.bandName, ProductData.TYPE_UINT16);
      band.setSpectralWavelength((float) bandInfo.wavebandInfo.centralWavelength);
      band.setSpectralBandwidth((float) bandInfo.wavebandInfo.bandWidth);
      band.setSpectralBandIndex(bandIndex);
      band.setSourceImage(new DefaultMultiLevelImage(new Jp2MultiLevelSource(bandInfo)));
    }

    product.setNumResolutionLevels(imageLayouts[0].numResolutions);

    return product;
  }
示例#22
0
 /**
  * Removes a record from a section of the Message, and adjusts the header.
  *
  * @see Record
  * @see Section
  */
 public boolean removeRecord(Record r, int section) {
   if (sections[section] != null && sections[section].remove(r)) {
     header.decCount(section);
     return true;
   } else return false;
 }
示例#23
0
 /**
  * Adds a record to a section of the Message, and adjusts the header.
  *
  * @see Record
  * @see Section
  */
 public void addRecord(Record r, int section) {
   if (sections[section] == null) sections[section] = new LinkedList();
   header.incCount(section);
   sections[section].add(r);
 }
示例#24
0
 /** Returns the number of empty slots on this page. */
 public int getNumEmptySlots() {
   return header.findSlots(false).size();
 }
示例#25
0
 /** Returns true if associated slot on this page is filled. */
 public boolean getSlot(int i) {
   return header.getSlotVal(i);
 }
示例#26
0
 /** Abstraction to fill a slot on this page. */
 public void setSlot(int i, boolean value) {
   header.setSlotVal(i, value);
 }