Ejemplo n.º 1
0
 public void writeTo(
     T obj,
     Class<?> cls,
     Type genericType,
     Annotation[] anns,
     MediaType m,
     MultivaluedMap<String, Object> headers,
     OutputStream os)
     throws IOException {
   try {
     String encoding = HttpUtils.getSetEncoding(m, headers, null);
     if (InjectionUtils.isSupportedCollectionOrArray(cls)) {
       marshalCollection(cls, obj, genericType, encoding, os, m, anns);
     } else {
       Object actualObject = checkAdapter(obj, cls, anns, true);
       Class<?> actualClass =
           obj != actualObject || cls.isInterface() ? actualObject.getClass() : cls;
       marshal(actualObject, actualClass, genericType, encoding, os, m, anns);
     }
   } catch (JAXBException e) {
     handleJAXBException(e, false);
   } catch (WebApplicationException e) {
     throw e;
   } catch (Exception e) {
     LOG.warning(ExceptionUtils.getStackTrace(e));
     throw ExceptionUtils.toInternalServerErrorException(e, null);
   }
 }
Ejemplo n.º 2
0
    @Override
    public void fileCleanStatusChanged(FileChangeEvent evt) {
      Object source = evt.getSource();
      if (source instanceof InitTableModel) {
        if (LOG.isLoggable(Level.FINE)) {
          LOG.fine("ActorTableModel " + evt.isClean());
        }
        tableIsClean = evt.isClean();
      } else if (source instanceof GroupTree) {
        if (LOG.isLoggable(Level.FINE)) {
          LOG.fine("GroupTree " + evt.isClean());
        }
        treeIsClean = evt.isClean();
      } else {
        if (LOG.isLoggable(Level.WARNING)) {
          LOG.warning("UNKNOWN " + evt.isClean());
        }
      }

      if (tableIsClean && treeIsClean) {
        if (saveAsFile != null) {
          setTitle("Groups Manager - " + saveAsFile.getName());
        } else {
          setTitle("Groups Manager");
        }
      } else {
        if (saveAsFile != null) {
          setTitle("Groups Manager - " + saveAsFile.getName() + "*");
        } else {
          setTitle("Groups Manager *");
        }
      }
    }
  @Override
  public void init(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, null, null);

    while (parser.nextTag() == XmlPullParser.START_TAG) {
      String name = parser.getName();

      if (name.equals("recipients")) {
        RecipientsImpl recipientsImpl = new RecipientsImpl();
        recipientsImpl.init(parser);
        setRecipients(recipientsImpl);
      } else if (name.equals("item-content")) {
        ItemContentImpl itemContentImpl = new ItemContentImpl();
        itemContentImpl.init(parser);
        setItemContent(itemContentImpl);
      } else if (name.equals("subject")) {
        setSubject(XppUtils.getElementValueFromNode(parser));
      } else if (name.equals("body")) {
        setBody(XppUtils.getElementValueFromNode(parser));
      } else {
        // Consume something we don't understand.
        LOG.warning("Found tag that we don't recognize: " + name);
        XppUtils.skipSubTree(parser);
      }
    }
  }
  @Override
  public void init(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, null, null);

    while (parser.nextTag() == XmlPullParser.START_TAG) {
      String name = parser.getName();

      if (name.equals("id")) {
        setId(XppUtils.getElementValueFromNode(parser));
      } else if (name.equals("recommendation-type")) {
        RecommendationTypeImpl recommendationType = new RecommendationTypeImpl();
        recommendationType.init(parser);
        setRecommendationType(recommendationType);
      } else if (name.equals("recommendation-snippet")) {
        setRecommendationSnippet(XppUtils.getElementValueFromNode(parser));
      } else if (name.equals("recommendation-text")) {
        setRecommendationText(XppUtils.getElementValueFromNode(parser));
      } else if (name.equals("web-url")) {
        setWebUrl(XppUtils.getElementValueFromNode(parser));
      } else if (name.equals("recommendee")) {
        RecommendeeImpl recommendee = new RecommendeeImpl();
        recommendee.init(parser);
        setRecommendee(recommendee);
      } else if (name.equals("recommender")) {
        RecommenderImpl recommender = new RecommenderImpl();
        recommender.init(parser);
        setRecommender(recommender);
      } else {
        // Consume something we don't understand.
        LOG.warning("Found tag that we don't recognize: " + name);
        XppUtils.skipSubTree(parser);
      }
    }
  }
  /** @param folder */
  public static void saveTriggers(File folder) {
    if (list.isEmpty()) {
      LOG.warning(
          "There are no triggers to persist, "
              + folder.getAbsolutePath()
              + " will not be altered.");
      return;
    }

    if (!folder.isDirectory()) {
      LOG.warning(folder.getAbsoluteFile() + " is not a valid trigger folder. Skipped");
      return;
    }

    XStream xstream = FreedomXStream.getXstream();
    deleteTriggerFiles(folder);

    try {
      LOG.config("Saving triggers to file in " + folder.getAbsolutePath());

      for (Trigger trigger : list) {
        if (trigger.isToPersist()) {
          String uuid = trigger.getUUID();

          if ((uuid == null) || uuid.isEmpty()) {
            trigger.setUUID(UUID.randomUUID().toString());
          }

          String fileName = trigger.getUUID() + ".xtrg";
          FileWriter fstream = new FileWriter(folder + "/" + fileName);
          BufferedWriter out = new BufferedWriter(fstream);
          out.write(xstream.toXML(trigger)); // persist only the data not the logic
          // Close the output stream

          out.close();
          fstream.close();
        }
      }
    } catch (Exception e) {
      LOG.info(e.getLocalizedMessage());
      LOG.severe(Freedomotic.getStackTraceInfo(e));
    }
  }
Ejemplo n.º 6
0
 private static void registerPythonOp(Path moduleRoot, String pythonClassName) {
   int lastDotPos = pythonClassName.lastIndexOf('.');
   String modulePath = "";
   String className = "";
   if (lastDotPos > 0) {
     modulePath = pythonClassName.substring(0, lastDotPos);
     className = pythonClassName.substring(lastDotPos + 1);
     if (!registerModule(moduleRoot, modulePath, className)) {
       LOG.warning(
           String.format(
               "Python module not installed: invalid entry in %s: %s",
               moduleRoot, pythonClassName));
     }
   }
   if (modulePath.isEmpty() || className.isEmpty()) {
     LOG.warning(
         String.format("Invalid Python module entry in %s: %s", moduleRoot, pythonClassName));
   }
 }
Ejemplo n.º 7
0
    /**
     * Append the range [off,off+len) from the provided sample data to the line. If the requested
     * playback time does not match the line end time, samples are skipped or silence is inserted as
     * necessary. If the data is marked as being just a filler, some warnings are suppressed.
     *
     * @param samples sample data
     * @param off sample data offset
     * @param len sample data length
     * @param time playback time
     * @param warnNonContinous warn about non-continous samples
     */
    private void appendFrames(final byte[] samples, int off, final int len, long lineTime) {
      assert off % bytesPerFrame == 0;
      assert len % bytesPerFrame == 0;

      while (true) {
        /* Fetch line end time only once per iteration */
        final long endLineTime = getNextLineTime();

        final long timingErrorFrames = lineTime - endLineTime;
        final double timingErrorSeconds = timingErrorFrames / sampleRate;

        if (Math.abs(timingErrorSeconds) <= TIMING_PRECISION) {
          /* Samples to append scheduled exactly at line end. Just append them and be done */
          appendFrames(samples, off, len);
          break;
        } else if (timingErrorFrames > 0) {
          /* Samples to append scheduled after the line end. Fill the gap with silence */
          LOG.warning(
              "Audio output non-continous (gap of "
                  + timingErrorFrames
                  + " frames), filling with silence");

          appendSilence((int) (lineTime - endLineTime));
        } else if (timingErrorFrames < 0) {
          /* Samples to append scheduled before the line end. Remove the overlapping
           * part and retry
           */
          LOG.warning(
              "Audio output non-continous (overlap of "
                  + (-timingErrorFrames)
                  + "), skipping overlapping frames");

          off += (endLineTime - lineTime) * bytesPerFrame;
          lineTime += endLineTime - lineTime;
        } else {
          /* Strange universe... */
          assert false;
        }
      }
    }
Ejemplo n.º 8
0
 /* (non-Javadoc)
  * @see br.gov.dataprev.painelserver.recebidos.MensagemRecebida#processa()
  */
 @Override
 protected void processa() {
   if (_versaoProtocolo != PacketHandler.VERSAO_PROTOCOLO) {
     LOG.warning(
         "Versão de protocolo diferente: Origem: "
             + this.getHostRemotoStr()
             + " Protocolo: "
             + _versaoProtocolo
             + ". Versão suportada pelo controlador: "
             + PacketHandler.VERSAO_PROTOCOLO);
   } else {
     GerenciadorPaineis.getInstance().cadastrarPainel(_idUnidade, this.getHostRemoto(), _servicos);
   }
 }
Ejemplo n.º 9
0
  private static boolean registerModule(
      Path pythonModuleRoot, String pythonModuleName, final String pythonClassName) {

    String pythonModuleRelPath = pythonModuleName.replace('.', '/');

    Path pythonModuleFile = pythonModuleRoot.resolve(pythonModuleRelPath + ".py");
    if (!Files.exists(pythonModuleFile)) {
      LOG.severe(String.format("Missing Python module '%s'", pythonModuleFile.toUri()));
      return false;
    }

    Path pythonInfoXmlFile = pythonModuleRoot.resolve(pythonModuleRelPath + "-info.xml");
    if (!Files.exists(pythonInfoXmlFile)) {
      LOG.warning(
          String.format(
              "Missing operator metadata file '%s'. Using defaults.", pythonInfoXmlFile.toUri()));
    }

    DefaultOperatorDescriptor operatorDescriptor =
        createOperatorDescriptor(pythonInfoXmlFile, pythonModuleName);
    File pythonModuleRootFile = FileUtils.toFile(pythonModuleRoot);

    PyOperatorSpi operatorSpi =
        new PyOperatorSpi(operatorDescriptor) {

          @Override
          public Operator createOperator() throws OperatorException {
            PyOperator pyOperator = (PyOperator) super.createOperator();

            pyOperator.setParameterDefaultValues();
            pyOperator.setPythonModulePath(pythonModuleRootFile.getPath());
            pyOperator.setPythonModuleName(pythonModuleName);
            pyOperator.setPythonClassName(pythonClassName);
            return pyOperator;
          }
        };

    String operatorName =
        operatorDescriptor.getAlias() != null
            ? operatorDescriptor.getAlias()
            : operatorDescriptor.getName();
    GPF.getDefaultInstance().getOperatorSpiRegistry().addOperatorSpi(operatorName, operatorSpi);
    LOG.info(
        String.format(
            "Python operator '%s' registered (Python module: '%s', class: '%s', root: '%s')",
            operatorName, pythonModuleName, pythonClassName, pythonModuleRootFile));
    return true;
  }
Ejemplo n.º 10
0
  @Override
  public void close() {
    commitLock.lock();
    try {

      if (closed) {
        return;
      }

      if (hasUncommitedData()) {
        LOG.warning("Closing storage with uncommited data, this data will be discarded.");
      }

      headVol.putData(0, headVolBackup, 0, headVolBackup.length);

      if (!readonly) {
        replaySoft();
        wal.destroyWalFiles();
      }
      wal.close();

      vol.close();
      vol = null;

      headVol.close();
      headVol = null;
      headVolBackup = null;

      uncommittedStackPages.clear();

      if (caches != null) {
        for (Cache c : caches) {
          c.close();
        }
        Arrays.fill(caches, null);
      }
      if (fileLockHeartbeat != null) {
        fileLockHeartbeat.unlock();
        fileLockHeartbeat = null;
      }
      closed = true;
    } finally {
      commitLock.unlock();
    }
  }
Ejemplo n.º 11
0
  @Override
  public void init(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, null, null);

    while (parser.nextTag() == XmlPullParser.START_TAG) {
      String name = parser.getName();

      if (name.equals("invitation-request")) {
        InvitationRequestImpl requestImpl = new InvitationRequestImpl();
        requestImpl.init(parser);
        setInvitationRequest(requestImpl);
      } else {
        // Consume something we don't understand.
        LOG.warning("Found tag that we don't recognize: " + name);
        XppUtils.skipSubTree(parser);
      }
    }
  }
Ejemplo n.º 12
0
 @Override
 public void init(XmlPullParser parser) throws IOException, XmlPullParserException {
   parser.require(XmlPullParser.START_TAG, null, null);
   setCount(XppUtils.getAttributeValueAsLongFromNode(parser, "count"));
   setStart(XppUtils.getAttributeValueAsLongFromNode(parser, "start"));
   setTotal(XppUtils.getAttributeValueAsLongFromNode(parser, "total"));
   while (parser.nextTag() == XmlPullParser.START_TAG) {
     String name = parser.getName();
     if (name.equals("product")) {
       ProductImpl node = new ProductImpl();
       node.init(parser);
       getProductList().add(node);
     } else {
       // Consume something we don't understand.
       LOG.warning("Found tag that we don't recognize: " + name);
       XppUtils.skipSubTree(parser);
     }
   }
 }
  @Override
  public void init(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, null, null);

    while (parser.nextTag() == XmlPullParser.START_TAG) {
      String name = parser.getName();
      if (name.equals("url")) {
        setUrl(XppUtils.getElementValueFromNode(parser));
      } else if (name.equals("headers")) {
        HeadersImpl headerImpl = new HeadersImpl();
        headerImpl.init(parser);
        setHeaders(headerImpl);
      } else {
        // Consume something we don't understand.
        LOG.warning("Found tag that we don't recognize: " + name);
        XppUtils.skipSubTree(parser);
      }
    }
  }
Ejemplo n.º 14
0
  @Override
  public void init(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, null, null);

    while (parser.nextTag() == XmlPullParser.START_TAG) {
      String name = parser.getName();

      if (name.equals("year")) {
        setYear(XppUtils.getElementValueAsLongFromNode(parser));
      } else if (name.equals("month")) {
        setMonth(XppUtils.getElementValueAsLongFromNode(parser));
      } else if (name.equals("day")) {
        setDay(XppUtils.getElementValueAsLongFromNode(parser));
      } else {
        // Consume something we don't understand.
        LOG.warning("Found tag that we don't recognize: " + name);
        XppUtils.skipSubTree(parser);
      }
    }
  }
  @Override
  public void download(Calendar date) throws IOException {
    Calendar endDate = (Calendar) date.clone();
    endDate.add(Calendar.DATE, 2);

    String scrapeUrl =
        baseUrl
            + "/feeds/posts/default?alt=atom&max-results=1&published-min="
            + iso8601String(date)
            + "&published-max="
            + iso8601String(endDate);
    String scrapedPage = downloadUrlToString(scrapeUrl);

    Matcher matcher = PUZZLE_PATTERN.matcher(scrapedPage);
    if (!matcher.find()) {
      LOG.warning("Failed to find puzzle URL in page: " + scrapeUrl);
      throw new IOException("Failed to scrape puzzle URL");
    }

    String url = matcher.group(1).replaceAll("&amp;amp;", "&");
    super.download(date, url);
  }
Ejemplo n.º 16
0
  @Override
  public void init(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, null, null);

    while (parser.nextTag() == XmlPullParser.START_TAG) {
      String name = parser.getName();

      if (name.equals("id")) {
        setId(XppUtils.getElementValueFromNode(parser));
      } else if (name.equals("name")) {
        setName(XppUtils.getElementValueFromNode(parser));
      } else if (name.equals("person")) {
        PersonImpl author = new PersonImpl();
        author.init(parser);
        setPerson(author);
      } else {
        // Consume something we don't understand.
        LOG.warning("Found tag that we don't recognize: " + name);
        XppUtils.skipSubTree(parser);
      }
    }
  }
  @Override
  public void init(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, null, null);

    while (parser.nextTag() == XmlPullParser.START_TAG) {
      String name = parser.getName();

      if (name.equals("authorization")) {
        AuthorizationImpl authImpl = new AuthorizationImpl();
        authImpl.init(parser);
        setAuthorization(authImpl);
      } else if (name.equals("connect-type")) {
        String connectTypeStr = XppUtils.getElementValueFromNode(parser);
        if (connectTypeStr != null) {
          setConnectType(InviteConnectType.fromValue(connectTypeStr));
        }
      } else {
        // Consume something we don't understand.
        LOG.warning("Found tag that we don't recognize: " + name);
        XppUtils.skipSubTree(parser);
      }
    }
  }
Ejemplo n.º 18
0
 @Override
 public void compact() {
   LOG.warning(
       "Compaction not yet implemented with StoreWAL, disable transactions to compact this store");
 }
Ejemplo n.º 19
0
    /** Enqueuer thread main method */
    @Override
    public void run() {
      try {
        /* Mute line initially to prevent clicks */
        setVolume(Float.NEGATIVE_INFINITY);

        /* Start the line */
        // m_line.start();
        // start the audio track
        audioTrack.play();

        LOG.info("Audio Track started !!!");

        boolean lineMuted = true;
        boolean didWarnGap = false;
        while (!closing) {
          if (!frameQueue.isEmpty()) {
            /* Queue filled */

            /* If the gap between the next packet and the end of line is
             * negligible (less than one packet), we write it to the line.
             * Otherwise, we fill the line buffer with silence and hope for
             * further packets to appear in the queue
             */
            final long entryFrameTime = frameQueue.firstKey();
            final long entryLineTime = convertFrameToLineTime(entryFrameTime);
            final long gapFrames = entryLineTime - getNextLineTime();

            // LOG.info("** gapFrames: " + gapFrames + " packetSizeFrames: " +  packetSizeFrames);

            if (gapFrames < -packetSizeFrames) {
              /* Too late for playback */
              LOG.warning(
                  "Audio data was scheduled for playback "
                      + (-gapFrames)
                      + " frames ago, skipping");
              frameQueue.remove(entryFrameTime);
              continue;
            } else if (gapFrames < packetSizeFrames) {
              /* Negligible gap between packet and line end. Prepare packet for playback */
              didWarnGap = false;

              /* Unmute line in case it was muted previously */
              if (lineMuted) {
                LOG.info("Audio data available, un-muting line");

                lineMuted = false;
                applyVolume();
              } else if (getVolume() != getRequestedVolume()) {
                applyVolume();
              }

              /* Get sample data and do sanity checks */
              final byte[] nextPlaybackSamples = frameQueue.remove(entryFrameTime);
              int nextPlaybackSamplesLength = nextPlaybackSamples.length;
              if (nextPlaybackSamplesLength % bytesPerFrame != 0) {
                LOG.severe(
                    "Audio data contains non-integral number of frames, ignore last "
                        + (nextPlaybackSamplesLength % bytesPerFrame)
                        + " bytes");
                nextPlaybackSamplesLength -= nextPlaybackSamplesLength % bytesPerFrame;
              }

              /* Append packet to line */
              LOG.finest(
                  "Audio data containing "
                      + nextPlaybackSamplesLength / bytesPerFrame
                      + " frames for playback time "
                      + entryFrameTime
                      + " found in queue, appending to the output line");

              appendFrames(nextPlaybackSamples, 0, nextPlaybackSamplesLength, entryLineTime);

              continue;
            } else {
              /* Gap between packet and line end. Warn */
              if (!didWarnGap) {
                didWarnGap = true;
                LOG.warning(
                    "Audio data missing for frame time "
                        + getNextLineTime()
                        + " (currently "
                        + gapFrames
                        + " frames), writing "
                        + packetSizeFrames
                        + " frames of silence");
              }
            }
          } else {
            /* Queue empty */

            if (!lineMuted) {
              lineMuted = true;
              setVolume(Float.NEGATIVE_INFINITY);
              LOG.fine(
                  "Audio data ended at frame time "
                      + getNextLineTime()
                      + ", writing "
                      + packetSizeFrames
                      + " frames of silence and muted line");
            }
          }

          appendSilence(packetSizeFrames);
        }

        // TODO: I don't think we need the appendSilence anymore when using Android API, but will
        // evaluate that later during tests
        /* Before we exit, we fill the line's buffer with silence. This should prevent
         * noise from being output while the line is being stopped
         */
        // appendSilence(m_line.available() / m_bytesPerFrame);
      } catch (final Throwable e) {
        LOG.log(Level.SEVERE, "Audio output thread died unexpectedly", e);
      } finally {
        setVolume(Float.NEGATIVE_INFINITY);
        audioTrack.stop();
        audioTrack.release();
        // m_line.stop();
        // m_line.close();
      }
    }
Ejemplo n.º 20
0
  private void paint(Shuttle shuttle) throws InvalidXMLException {
    Element e = shuttle.node;
    String shapeName = e.getLocalName();

    if (!SVG.NS.equals(e.getNamespaceURI())) {

      for (Node c = e.getFirstChild(); c != null; c = c.getNextSibling()) {
        if (c.getNodeType() != Node.ELEMENT_NODE) continue;
        Shuttle cp = new Shuttle(shuttle, Element.class.cast(c));
        paint(cp);
      }
    } else if (shapeName == null) {
      LOG.warning("shapeName is null");
    } else if (shapeName.equals("g")) {

      for (Node c = e.getFirstChild(); c != null; c = c.getNextSibling()) {
        if (c.getNodeType() != Node.ELEMENT_NODE) continue;
        Shuttle cp = new Shuttle(shuttle, Element.class.cast(c));
        paint(cp);
      }
    } else if (shapeName.equals("path")) {
      Attr d = e.getAttributeNode("d");
      if (d != null) {
        shuttle.shape = SVGUtils.pathToShape(d.getValue());
        drawShape(shuttle);
      }
    } else if (shapeName.equals("polyline")) {
      Attr points = e.getAttributeNode("points");
      if (points != null) {
        shuttle.shape = SVGUtils.polylineToShape(points.getValue());
        drawShape(shuttle);
      }
    } else if (shapeName.equals("polygon")) {
      Attr points = e.getAttributeNode("points");
      if (points != null) {
        shuttle.shape = SVGUtils.polygonToShape(points.getValue());
        drawShape(shuttle);
      }
    } else if (shapeName.equals("rect")) {

      Attr x = e.getAttributeNode("x");
      Attr y = e.getAttributeNode("y");
      Attr w = e.getAttributeNode("width");
      Attr h = e.getAttributeNode("height");
      if (x != null && y != null && w != null && h != null) {
        shuttle.shape =
            new Rectangle2D.Double(
                Double.parseDouble(x.getValue()),
                Double.parseDouble(y.getValue()),
                Double.parseDouble(w.getValue()),
                Double.parseDouble(h.getValue()));
        drawShape(shuttle);
      }
    } else if (shapeName.equals("line")) {
      Attr x1 = e.getAttributeNode("x1");
      Attr y1 = e.getAttributeNode("y1");
      Attr x2 = e.getAttributeNode("x2");
      Attr y2 = e.getAttributeNode("y2");
      if (x1 != null && y1 != null && x2 != null && y2 != null) {
        shuttle.shape =
            new Line2D.Double(
                Double.parseDouble(x1.getValue()),
                Double.parseDouble(y1.getValue()),
                Double.parseDouble(x2.getValue()),
                Double.parseDouble(y2.getValue()));
        drawShape(shuttle);
      }
    } else if (shapeName.equals("circle")) {
      Attr cx = e.getAttributeNode("cx");
      Attr cy = e.getAttributeNode("cy");
      Attr r = e.getAttributeNode("r");
      if (cx != null && cy != null && r != null) {
        double radius = Double.parseDouble(r.getValue());
        shuttle.shape =
            new Ellipse2D.Double(
                Double.parseDouble(cx.getValue()) - radius,
                Double.parseDouble(cy.getValue()) - radius,
                radius * 2,
                radius * 2);
        drawShape(shuttle);
      }
    } else if (shapeName.equals("ellipse")) {
      Attr cx = e.getAttributeNode("cx");
      Attr cy = e.getAttributeNode("cy");
      Attr rx = e.getAttributeNode("rx");
      Attr ry = e.getAttributeNode("ry");
      if (cx != null && cy != null && rx != null && ry != null) {
        double radiusx = Double.parseDouble(rx.getValue());
        double radiusy = Double.parseDouble(ry.getValue());
        shuttle.shape =
            new Ellipse2D.Double(
                Double.parseDouble(cx.getValue()) - radiusx,
                Double.parseDouble(cy.getValue()) - radiusy,
                radiusx * 2,
                radiusy * 2);
        drawShape(shuttle);
      }
    } else if (StringUtils.isIn(shapeName, "title", "defs", "desc", "metadata")) {
      // ignore
    } else if (shapeName.equals("text")) {
      Attr x = e.getAttributeNode("x");
      Attr y = e.getAttributeNode("y");
      if (x != null && y != null) {

        Font f = new Font(shuttle.fontFamily, Font.PLAIN, (int) shuttle.fontSize);

        FontRenderContext frc = shuttle.g.getFontRenderContext();
        TextLayout tl = new TextLayout(e.getTextContent(), f, frc);
        shuttle.shape = tl.getOutline(null);
        shuttle.shape =
            AffineTransform.getTranslateInstance(
                    Double.parseDouble(x.getValue()), Double.parseDouble(y.getValue()))
                .createTransformedShape(shuttle.shape);

        drawShape(shuttle);
      }
    } else if (shapeName.equals("svg")) {

      for (Node c = e.getFirstChild(); c != null; c = c.getNextSibling()) {
        if (c.getNodeType() != Node.ELEMENT_NODE) continue;
        Shuttle cp = new Shuttle(shuttle, Element.class.cast(c));
        paint(cp);
      }
    } else {
      LOG.warning("cannot display <" + e.getLocalName() + ">");
    }
  }
Ejemplo n.º 21
0
  protected void initOpen() {
    checkFeaturesBitmap(vol.getLong(HEAD_FEATURES));

    // replay log
    long pos = headerSize;
    final long volumeSize = vol.length();
    long lastValidPos = pos;
    long highestRecid2 = RECID_LAST_RESERVED;
    LongLongMap commitData = tx ? new LongLongMap() : null;

    try {

      while (true) {
        lastValidPos = pos;
        if (pos >= volumeSize) break;
        final long instPos = pos;
        final int inst = vol.getUnsignedByte(pos++);

        if (inst == I_INSERT || inst == I_UPDATE) {

          long recid = vol.getPackedLong(pos);
          pos += recid >>> 60;
          recid = longParityGet(recid & DataIO.PACK_LONG_RESULT_MASK);

          highestRecid2 = Math.max(highestRecid2, recid);

          commitData.put(recid, instPos);

          // skip rest of the record
          long size = vol.getPackedLong(pos);
          long dataLen = longParityGet(size & DataIO.PACK_LONG_RESULT_MASK) - 1;
          dataLen = Math.max(0, dataLen);
          pos = pos + (size >>> 60) + dataLen;
        } else if (inst == I_DELETE) {
          long recid = vol.getPackedLong(pos);
          pos += recid >>> 60;
          recid = longParityGet(recid & DataIO.PACK_LONG_RESULT_MASK);

          highestRecid2 = Math.max(highestRecid2, recid);

          commitData.put(recid, -1);
        } else if (inst == I_DELETE) {
          long recid = vol.getPackedLong(pos);
          pos += recid >>> 60;
          recid = longParityGet(recid & DataIO.PACK_LONG_RESULT_MASK);
          highestRecid2 = Math.max(highestRecid2, recid);
          commitData.put(recid, -2);

        } else if (inst == I_SKIP_SINGLE_BYTE) {
          // do nothing, just skip single byte
        } else if (inst == I_SKIP_MULTI_BYTE) {
          // read size and skip it
          // skip rest of the record
          long size = vol.getPackedLong(pos);
          pos += (size >>> 60) + longParityGet(size & DataIO.PACK_LONG_RESULT_MASK);
        } else if (inst == I_TX_VALID) {
          if (tx) {
            // apply changes from commitData to indexTable
            for (int i = 0; i < commitData.table.length; i += 2) {
              long recidOffset = commitData.table[i] * 8;
              if (recidOffset == 0) continue;
              indexTable.ensureAvailable(recidOffset + 8);
              indexTable.putLong(recidOffset, commitData.table[i + 1]);
            }
            commitData.clear();
          }
        } else if (inst == I_TX_ROLLBACK) {
          if (tx) {
            commitData.clear();
          }
        } else if (inst == 0) {
          // rollback last changes if that is necessary
          if (tx) {
            // rollback changes in index table since last valid tx
            commitData.clear();
          }

          break;
        } else {
          // TODO log here?
          LOG.warning("Unknown instruction " + inst);
          break;
        }
      }
    } catch (RuntimeException e) {
      // log replay finished
      // TODO log here?
      LOG.log(Level.WARNING, "Log replay finished", e);
      if (tx) {
        // rollback changes in index table since last valid tx
        commitData.clear();
      }
    }
    eof = lastValidPos;

    highestRecid.set(highestRecid2);
  }
Ejemplo n.º 22
0
    /**
     * Append the range [off, off+len) from the provided sample data to the line.
     *
     * @param samples sample data
     * @param off sample data offset
     * @param len sample data length
     */
    private void appendFrames(final byte[] samples, int off, int len) {
      assert off % bytesPerFrame == 0;
      assert len % bytesPerFrame == 0;

      /* Make sure that [off, off+len) does not exceed sample's bounds */
      off = Math.min(off, (samples != null) ? samples.length : 0);

      len = Math.min(len, (samples != null) ? samples.length - off : 0);

      if (len <= 0) {
        return;
      }

      /* Convert samples if necessary */
      final byte[] samplesConverted = Arrays.copyOfRange(samples, off, off + len);

      if (convertUnsignedToSigned) {
        /* The line expects signed PCM samples, so we must
         * convert the unsigned PCM samples to signed.
         * Note that this only affects the high bytes!
         */
        for (int i = 0; i < samplesConverted.length; i += 2) {
          samplesConverted[i] = (byte) ((samplesConverted[i] & 0xff) - 0x80);
        }
      }

      /* Write samples to line */
      // final int bytesWritten = m_line.write(samplesConverted, 0, samplesConverted.length);
      final int bytesWritten = audioTrack.write(samplesConverted, 0, samplesConverted.length);

      if (bytesWritten == AudioTrack.ERROR_INVALID_OPERATION) {
        LOG.severe("Audio Track not initialized properly");
        throw new RuntimeException(
            "Audio Track not initialized properly: AudioTrack status: ERROR_INVALID_OPERATION");
      } else if (bytesWritten == AudioTrack.ERROR_BAD_VALUE) {
        LOG.severe("Wrong parameters sent to Audio Track!");
        throw new RuntimeException(
            "Wrong parameters sent to Audio Track! AudioTrack status: ERROR_BAD_VALUE");
      } else if (bytesWritten != len) {
        LOG.warning(
            "Audio output line accepted only "
                + bytesWritten
                + " bytes of sample data while trying to write "
                + samples.length
                + " bytes");
      } else {
        LOG.info(bytesWritten + " bytes written to the audio output line");
      }

      /* Update state */
      synchronized (AudioOutputQueue.this) {
        framesWrittenToLine += (bytesWritten / bytesPerFrame);

        for (int b = 0; b < bytesPerFrame; ++b) {
          lineLastFrame[b] = samples[off + len - (bytesPerFrame - b)];
        }

        if (LOG.isLoggable(Level.FINE)) {
          LOG.finest(
              "Audio output line end is now at "
                  + getNextLineTime()
                  + " after writing "
                  + len / bytesPerFrame
                  + " frames");
        }
      }
    }
  /** @param folder */
  public static synchronized void loadTriggers(File folder) {
    XStream xstream = FreedomXStream.getXstream();

    // This filter only returns object files
    FileFilter objectFileFileter =
        new FileFilter() {
          public boolean accept(File file) {
            if (file.isFile() && file.getName().endsWith(".xtrg")) {
              return true;
            } else {
              return false;
            }
          }
        };

    File[] files = folder.listFiles(objectFileFileter);

    try {
      StringBuilder summary = new StringBuilder();
      // print an header for the index.txt file
      summary.append("#Filename \t\t #TriggerName \t\t\t #ListenedChannel").append("\n");

      if (files != null) {
        for (File file : files) {
          Trigger trigger = null;
          try {
            // validate the object against a predefined DTD
            String xml =
                DOMValidateDTD.validate(
                    file, Info.getApplicationPath() + "/config/validator/trigger.dtd");
            trigger = (Trigger) xstream.fromXML(xml);
          } catch (Exception e) {
            LOG.log(
                Level.SEVERE,
                "Trigger file {0} is not well formatted: {1}",
                new Object[] {file.getPath(), e.getLocalizedMessage()});
            continue;
          }

          // addAndRegister trigger to the list if it is not a duplicate
          if (!list.contains(trigger)) {
            if (trigger.isHardwareLevel()) {
              trigger.setPersistence(false); // it has not to me stored in root/data folder
              addAndRegister(trigger); // in the list and start listening
            } else {
              if (folder.getAbsolutePath().startsWith(Info.getPluginsPath())) {
                trigger.setPersistence(false);
              } else {
                trigger.setPersistence(true); // not hardware trigger and not plugin related
              }

              list.add(
                  trigger); // only in the list not registred. I will be registred only if used in
                            // mapping
            }
          } else {
            LOG.warning("Trigger '" + trigger.getName() + "' is already in the list");
          }

          summary
              .append(trigger.getUUID())
              .append("\t\t")
              .append(trigger.getName())
              .append("\t\t\t")
              .append(trigger.getChannel())
              .append("\n");
        }

        // writing a summary .txt file with the list of commands in this folder
        FileWriter fstream = new FileWriter(folder + "/index.txt");
        BufferedWriter indexfile = new BufferedWriter(fstream);
        indexfile.write(summary.toString());
        // Close the output stream
        indexfile.close();
      } else {
        LOG.config("No triggers to load from this folder " + folder.toString());
      }
    } catch (Exception e) {
      LOG.severe("Exception while loading this trigger.\n" + Freedomotic.getStackTraceInfo(e));
    }
  }
Ejemplo n.º 24
0
  public T readFrom(
      Class<T> type,
      Type genericType,
      Annotation[] anns,
      MediaType mt,
      MultivaluedMap<String, String> headers,
      InputStream is)
      throws IOException {
    if (isPayloadEmpty(headers)) {
      if (AnnotationUtils.getAnnotation(anns, Nullable.class) != null) {
        return null;
      } else {
        reportEmptyContentLength();
      }
    }

    XMLStreamReader reader = null;
    Unmarshaller unmarshaller = null;
    try {

      boolean isCollection = InjectionUtils.isSupportedCollectionOrArray(type);
      Class<?> theGenericType = isCollection ? InjectionUtils.getActualType(genericType) : type;
      Class<?> theType = getActualType(theGenericType, genericType, anns);

      unmarshaller = createUnmarshaller(theType, genericType, isCollection);
      addAttachmentUnmarshaller(unmarshaller);
      Object response = null;
      if (JAXBElement.class.isAssignableFrom(type)
          || !isCollection
              && (unmarshalAsJaxbElement
                  || jaxbElementClassMap != null
                      && jaxbElementClassMap.containsKey(theType.getName()))) {
        reader = getStreamReader(is, type, mt);
        reader = TransformUtils.createNewReaderIfNeeded(reader, is);
        if (JAXBElement.class.isAssignableFrom(type) && type == theType) {
          response = unmarshaller.unmarshal(reader);
        } else {
          response = unmarshaller.unmarshal(reader, theType);
        }
      } else {
        response = doUnmarshal(unmarshaller, type, is, anns, mt);
      }
      if (response instanceof JAXBElement && !JAXBElement.class.isAssignableFrom(type)) {
        response = ((JAXBElement<?>) response).getValue();
      }
      if (isCollection) {
        response =
            ((CollectionWrapper) response)
                .getCollectionOrArray(
                    unmarshaller,
                    theType,
                    type,
                    genericType,
                    org.apache.cxf.jaxrs.utils.JAXBUtils.getAdapter(theGenericType, anns));
      } else {
        response = checkAdapter(response, type, anns, false);
      }
      return type.cast(response);

    } catch (JAXBException e) {
      handleJAXBException(e, true);
    } catch (DepthExceededStaxException e) {
      throw ExceptionUtils.toWebApplicationException(null, JAXRSUtils.toResponse(413));
    } catch (WebApplicationException e) {
      throw e;
    } catch (Exception e) {
      LOG.warning(ExceptionUtils.getStackTrace(e));
      throw ExceptionUtils.toBadRequestException(e, null);
    } finally {
      try {
        StaxUtils.close(reader);
      } catch (XMLStreamException e) {
        // Ignore
      }
      JAXBUtils.closeUnmarshaller(unmarshaller);
    }
    // unreachable
    return null;
  }
Ejemplo n.º 25
0
  private void update(boolean force) {
    final Wrappers._boolean _force = new Wrappers._boolean(force);
    myQueue.assertSoftlyIsCommandThread();
    if (!(myDifference.isEnabled())) {
      return;
    }

    IFile modelFile = myModelDescriptor.getSource().getFile();
    if (!(modelFile.exists())) {
      return;
    }
    VirtualFile modelVFile = VirtualFileUtils.getVirtualFile(modelFile);
    if (modelVFile == null
        || ProjectLevelVcsManager.getInstance(myProject).getVcsFor(modelVFile) == null) {
      return;
    }
    FileStatus status = FileStatusManager.getInstance(myProject).getStatus(modelVFile);
    if (ConflictsUtil.isModelOrModuleConflicting(myModelDescriptor, myProject)) {
      status = FileStatus.MERGED_WITH_CONFLICTS;
    }

    if (myDifference.getChangeSet() != null) {
      ModelAccess.instance()
          .runReadAction(
              new Runnable() {
                public void run() {
                  if (myDifference.getChangeSet().getNewModel() != myModelDescriptor.getSModel()) {
                    _force.value = true;
                  }
                }
              });
    }

    if (myStatusOnLastUpdate == status && !(_force.value)) {
      return;
    }
    myDifference.removeChangeSet();
    myStatusOnLastUpdate = status;
    if (FileStatus.NOT_CHANGED == status && !(_force.value)) {
      return;
    }
    final Wrappers._T<SModel> baseVersionModel = new Wrappers._T<SModel>(null);
    if (BaseVersionUtil.isAddedFileStatus(status)
        || ConflictsUtil.isModelOrModuleConflicting(myModelDescriptor, myProject)) {
      baseVersionModel.value =
          new jetbrains.mps.smodel.SModel(myModelDescriptor.getSModelReference());
    } else {
      String content = BaseVersionUtil.getBaseVersionContent(modelVFile, myProject);
      if (content == null && status != FileStatus.NOT_CHANGED) {
        LOG.error("Base version content is null while file status is " + status);
      }
      if (content == null) {
        return;
      }
      try {
        baseVersionModel.value = ModelPersistence.readModel(content, false);
      } catch (ModelReadException e) {
        LOG.warning("", e);
        return;
      }
    }
    ModelAccess.instance()
        .runReadAction(
            new Runnable() {
              public void run() {
                synchronized (ChangesTracking.this) {
                  if (!(myDisposed)) {
                    ChangeSet changeSet =
                        ChangeSetBuilder.buildChangeSet(
                            baseVersionModel.value, myModelDescriptor.getSModel(), true);
                    myDifference.setChangeSet((ChangeSetImpl) changeSet);
                    buildCaches();
                  }
                }
              }
            });
  }