コード例 #1
0
ファイル: MQTTHandler.java プロジェクト: fluppie/knx2mqtt
 private void doPublish(
     String name,
     Object val,
     String src,
     String dpt,
     String textual,
     long updateTime,
     long lastChange) {
   JsonObject jso = new JsonObject();
   jso.add("ts", updateTime).add("lc", lastChange).add("knx_src_addr", src).add("knx_dpt", dpt);
   if (textual != null) jso.add("knx_textual", textual);
   if (val instanceof Integer) jso.add("val", ((Integer) val).intValue());
   else if (val instanceof Number) jso.add("val", ((Number) val).doubleValue());
   else jso.add("val", val.toString());
   String txtmsg = jso.toString();
   MqttMessage msg = new MqttMessage(jso.toString().getBytes(StandardCharsets.UTF_8));
   msg.setQos(0);
   msg.setRetained(true);
   try {
     String fullTopic = topicPrefix + "status/" + name;
     mqttc.publish(fullTopic, msg);
     L.finer("Published " + txtmsg + " to " + fullTopic);
   } catch (MqttException e) {
     L.log(Level.WARNING, "Error when publishing message " + txtmsg, e);
   }
 }
コード例 #2
0
ファイル: ChatImpl.java プロジェクト: kronar/Skype4J
 @Override
 public ChatMessage sendMessage(Message message) throws ConnectionException {
   checkLoaded();
   try {
     long ms = System.currentTimeMillis();
     JsonObject obj = new JsonObject();
     obj.add("content", message.write());
     obj.add("messagetype", "RichText");
     obj.add("contenttype", "text");
     obj.add("clientmessageid", String.valueOf(ms));
     ConnectionBuilder builder = new ConnectionBuilder();
     builder.setUrl(getClient().withCloud(SEND_MESSAGE_URL, getIdentity()));
     builder.setMethod("POST", true);
     builder.addHeader("RegistrationToken", getClient().getRegistrationToken());
     builder.addHeader("Content-Type", "application/json");
     builder.setData(obj.toString());
     HttpURLConnection con = builder.build();
     if (con.getResponseCode() == 201) {
       return ChatMessageImpl.createMessage(
           this, getUser(getClient().getUsername()), null, String.valueOf(ms), ms, message);
     } else {
       throw getClient().generateException(con);
     }
   } catch (IOException e) {
     throw new ConnectionException("While sending a message", e);
   }
 }
コード例 #3
0
  @Override
  public void generateBuildScript(Configuration cfg, Context ctx) {
    try {
      final InputStream input =
          this.getClass().getClassLoader().getResourceAsStream("javascript/lib/package.json");
      final List<String> packLines = IOUtils.readLines(input);
      String pack = "";
      for (String line : packLines) {
        pack += line + "\n";
      }
      input.close();
      pack = pack.replace("<NAME>", cfg.getName());

      final JsonObject json = JsonObject.readFrom(pack);
      final JsonValue deps = json.get("dependencies");
      for (Thing t : cfg.allThings()) {
        for (String dep : t.annotation("js_dep")) {
          deps.asObject().add(dep.split(":")[0].trim(), dep.split(":")[1].trim());
        }
      }

      for (Thing t : cfg.allThings()) {
        if (t.getStreams().size() > 0) {
          deps.asObject().add("rx", "^2.5.3");
          deps.asObject().add("events", "^1.0.2");
          break;
        }
      }

      final File f = new File(ctx.getOutputDirectory() + "/" + cfg.getName() + "/package.json");
      f.setWritable(true);
      final PrintWriter w = new PrintWriter(new FileWriter(f));
      w.println(json.toString());
      w.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #4
0
  private static void processArchive(
      final Path path, final Set<Archive> output, final SettingsModelFactory settingsFactory)
      throws IOException, StarDBException {

    Archive originalArchive = new Archive(path);

    if (!originalArchive.extract()) {
      throw new IOException("Could not extract archive.");
    }

    Set<ArchiveFile> usedPaks = new HashSet<>();

    for (ArchiveFile file : originalArchive.getFiles()) {

      if (FileHelper.getExtension(file.getPath()).equals("modinfo")) {

        JsonObject o = JsonObject.readFrom(new String(file.getData()));

        String preformattedPath = o.get("path").asString().replaceAll("\"", "");

        if (preformattedPath.startsWith("./")) {
          preformattedPath = preformattedPath.replace("./", "");
        }

        if (preformattedPath.startsWith(".")) {
          preformattedPath = preformattedPath.replace(".", "");
        }

        if (preformattedPath.startsWith("/")) {
          preformattedPath = preformattedPath.replace("/", "");
        }

        Path modinfoPath = file.getPath();

        if (modinfoPath.getNameCount() > 2) {
          modinfoPath = modinfoPath.subpath(0, modinfoPath.getNameCount() - 1);
        } else if (modinfoPath.getNameCount() > 1) {
          modinfoPath = modinfoPath.getName(0);
        } else {
          modinfoPath = Paths.get("");
        }

        Archive outputArchive =
            new Archive(
                settingsFactory
                    .getInstance()
                    .getPropertyPath("modsdir")
                    .resolve(Paths.get(o.get("name").asString() + ".zip")));

        if (file.getPath().getNameCount() == 1) {
          outputArchive.addFile(new ArchiveFile(file.getData(), file.getPath(), false));
          log.debug(
              "'{}' -> '{}' relativized to '{}'", modinfoPath, file.getPath(), file.getPath());
        } else {
          outputArchive.addFile(
              new ArchiveFile(
                  file.getData(), modinfoPath.relativize(file.getPath()).normalize(), false));
          log.debug(
              "'{}' -> '{}' relativized to '{}'",
              modinfoPath,
              file.getPath(),
              modinfoPath.relativize(file.getPath()).normalize());
        }

        Path assetsPath = modinfoPath.resolve(Paths.get(preformattedPath));

        log.debug("Assets path for modinfo '{}': {}", file.getPath(), assetsPath);

        if (originalArchive.getFile(assetsPath) != null
            && !assetsPath.toString().isEmpty()
            && !originalArchive.getFile(assetsPath).isFolder()) {

          if (FileHelper.identifyType(originalArchive.getFile(assetsPath).getData())
              .equals("pak")) {

            log.debug("Assets for mod '{}' identified as .pak file: {}", modinfoPath, assetsPath);

            usedPaks.add(originalArchive.getFile(assetsPath));

            ArchiveFile modinfo = outputArchive.getFile(".modinfo");
            JsonObject o2 = JsonObject.readFrom(new String(modinfo.getData()));
            o2.set("path", "assets");

            modinfo.setData(o2.toString().getBytes());

            // TODO Update StarDB to let me pass in a byte array instead of needing to open a file

            Path tempPath = Paths.get("tempPak" + System.nanoTime());

            SeekableByteChannel tempPakFile =
                Files.newByteChannel(tempPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
            tempPakFile.write(ByteBuffer.wrap(originalArchive.getFile(assetsPath).getData()));
            tempPakFile.close();

            AssetDatabase database = AssetDatabase.open(tempPath);

            for (String assetFile : database.getFileList()) {
              outputArchive.addFile(
                  new ArchiveFile(
                      database.getAsset(assetFile), Paths.get("assets/" + assetFile), false));
              log.trace("Asset extracted: {} | {}", assetFile, Paths.get("assets/" + assetFile));
            }

            Files.deleteIfExists(tempPath);
          }

        } else {

          ArchiveFile modinfo = outputArchive.getFile(".modinfo");
          JsonObject o2 = JsonObject.readFrom(new String(modinfo.getData()));
          o2.set("path", "assets");

          modinfo.setData(o2.toString().getBytes());

          log.debug("Assets for mod '{}' is a standard assets folder: {}", modinfoPath, assetsPath);

          for (ArchiveFile f2 : originalArchive.getFiles()) {

            if ((assetsPath.toString().isEmpty() || f2.getPath().startsWith(assetsPath))
                && !f2.isFolder()
                && !f2.getPath().toString().endsWith(".modinfo")) {

              if (modinfoPath.toString().isEmpty()) {

                if (f2.getPath().getNameCount() == 1) {

                  if (!f2.getPath().startsWith(assetsPath)) {
                    outputArchive.addFile(
                        new ArchiveFile(
                            f2.getData(),
                            Paths.get("assets/").resolve(f2.getPath()).normalize(),
                            false));
                    log.trace(
                        "'{}' -> '{}' relativized to '{}'",
                        modinfoPath,
                        f2.getPath(),
                        Paths.get("assets/").resolve(f2.getPath()).normalize());
                  } else {
                    outputArchive.addFile(new ArchiveFile(f2.getData(), f2.getPath(), false));
                    log.trace(
                        "'{}' -> '{}' relativized to '{}'",
                        modinfoPath,
                        f2.getPath(),
                        f2.getPath());
                  }

                } else {

                  if (!f2.getPath().startsWith(assetsPath)) {
                    outputArchive.addFile(
                        new ArchiveFile(
                            f2.getData(),
                            Paths.get("assets/").resolve(f2.getPath()).normalize(),
                            false));
                    log.trace(
                        "'{}' -> '{}' relativized to '{}'",
                        modinfoPath,
                        f2.getPath(),
                        Paths.get("assets/").resolve(f2.getPath()).normalize());
                  } else {
                    outputArchive.addFile(new ArchiveFile(f2.getData(), f2.getPath(), false));
                    log.trace(
                        "'{}' -> '{}' relativized to '{}'",
                        modinfoPath,
                        f2.getPath(),
                        f2.getPath());
                  }
                }

              } else {

                if (f2.getPath().getNameCount() == 1) {

                  if (!modinfoPath.relativize(f2.getPath()).startsWith("assets")) {
                    outputArchive.addFile(
                        new ArchiveFile(
                            f2.getData(), Paths.get("assets/").resolve(f2.getPath()), false));
                    log.trace(
                        "'{}' -> '{}' relativized to '{}'",
                        modinfoPath,
                        f2.getPath(),
                        Paths.get("assets/").resolve(f2.getPath()));
                  } else {
                    outputArchive.addFile(new ArchiveFile(f2.getData(), f2.getPath(), false));
                    log.trace(
                        "'{}' -> '{}' relativized to '{}'",
                        modinfoPath,
                        f2.getPath(),
                        f2.getPath());
                  }

                } else {

                  if (!modinfoPath.relativize(f2.getPath()).startsWith("assets")) {
                    outputArchive.addFile(
                        new ArchiveFile(
                            f2.getData(),
                            Paths.get("assets/")
                                .resolve(modinfoPath.relativize(f2.getPath()).normalize()),
                            false));
                    log.trace(
                        "'{}' -> '{}' relativized to '{}'",
                        modinfoPath,
                        f2.getPath(),
                        Paths.get("assets/")
                            .resolve(modinfoPath.relativize(f2.getPath()).normalize()));
                  } else {
                    outputArchive.addFile(
                        new ArchiveFile(
                            f2.getData(), modinfoPath.relativize(f2.getPath()).normalize(), false));
                    log.trace(
                        "'{}' -> '{}' relativized to '{}'",
                        modinfoPath,
                        f2.getPath(),
                        modinfoPath.relativize(f2.getPath()).normalize());
                  }
                }
              }
            }
          }
        }

        outputArchive.writeToFile(
            settingsFactory
                .getInstance()
                .getPropertyPath("modsdir")
                .resolve(Paths.get(o.get("name").asString() + ".zip"))
                .toFile()); // TODO

        output.add(outputArchive);
      }
    }

    for (ArchiveFile file : originalArchive.getFiles()) {

      if (!usedPaks.contains(file)
          && !file.isFolder()
          && FileHelper.identifyType(file.getData()).equals("pak")) {

        log.debug("Additional .pak identified: {}", file.getPath());

        Path tempPath = Paths.get("tempPak" + System.nanoTime());

        SeekableByteChannel tempPakFile =
            Files.newByteChannel(tempPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        tempPakFile.write(ByteBuffer.wrap(file.getData()));
        tempPakFile.close();

        AssetDatabase database = AssetDatabase.open(tempPath);
        log.debug(database.getFileList());

        if (database.getAsset("/pak.modinfo") != null) {
          log.debug("{} has a .modinfo file, parsing into mod.", file.getPath());
          processPakFile(tempPath, output, settingsFactory);
        } else {
          log.debug("{} does not contain a .modinfo file, skipping.", file.getPath());
        }

        Files.deleteIfExists(tempPath);
      }
    }
  }
コード例 #5
0
  private static void processPakFile(
      final Path path, final Set<Archive> output, final SettingsModelFactory settingsFactory)
      throws IOException, StarDBException {

    SettingsModelInterface settings = settingsFactory.getInstance();

    AssetDatabase database = AssetDatabase.open(path);
    log.debug(database.getFileList());

    byte[] modinfoFile = database.getAsset("/pak.modinfo");
    String[] modinfoContents = new String(modinfoFile).split("\n");

    String modName = "";
    String assetsPath = "";

    // TODO Use actual JSON parser
    for (String line : modinfoContents) {
      if (line.contains("\"name\"")) {
        modName = line.trim().split(":")[1];
        modName = modName.substring(modName.indexOf("\"") + 1, modName.lastIndexOf("\""));
      }
      if (line.contains("\"path\"")) {
        assetsPath = line.trim().split(":")[1];
        assetsPath =
            assetsPath.substring(assetsPath.indexOf("\"") + 1, assetsPath.lastIndexOf("\""));
      }
    }

    if (assetsPath.startsWith(".")) {
      assetsPath = assetsPath.replace(".", "");
    }

    if (assetsPath.startsWith("/")) {
      assetsPath = assetsPath.replace("/", "");
    }

    if (assetsPath.startsWith("./")) {
      assetsPath = assetsPath.replace("./", "");
    }

    Archive modArchive = new Archive(settings.getPropertyPath("modsdir").resolve(modName + ".zip"));

    modArchive.addFile(new ArchiveFile(modinfoFile, Paths.get(modName + ".modinfo"), false));

    ArchiveFile modinfo = modArchive.getFile(".modinfo");
    JsonObject o2 = JsonObject.readFrom(new String(modinfo.getData()));
    o2.set("path", "assets");

    modinfo.setData(o2.toString().getBytes());

    assetsPath = "/" + assetsPath + "/";
    log.debug("Assets path is '{}'", assetsPath);

    for (String file : database.getFileList()) {

      log.trace("{} is in {}", file, path);

      if (file.endsWith(".modinfo") || file.endsWith("desktop.ini") || file.endsWith("thumbs.db")) {
        continue;
      }

      if (assetsPath.isEmpty() || !file.startsWith(assetsPath)) {
        modArchive.addFile(
            new ArchiveFile(
                database.getAsset(file), Paths.get("assets/" + file.substring(1)), false));
      } else {
        log.debug("{} --- {}", assetsPath, file.substring(assetsPath.length()));
        modArchive.addFile(
            new ArchiveFile(
                database.getAsset(file),
                Paths.get("assets/" + file.substring(assetsPath.length())),
                false));
      }
    }

    Files.deleteIfExists(
        settings
            .getPropertyPath("modsdir")
            .resolve(path.subpath(path.getNameCount() - 1, path.getNameCount())));

    modArchive.writeToFile();

    output.add(modArchive);
  }