Esempio n. 1
0
 private void fixConfigSchema() {
   File configFile;
   File ctpDir = new File(directory, "CTP");
   if (ctpDir.exists()) configFile = new File(ctpDir, "config.xml");
   else configFile = new File(directory, "config.xml");
   if (configFile.exists()) {
     try {
       Document doc = getDocument(configFile);
       Element root = doc.getDocumentElement();
       Element server = getFirstNamedChild(root, "Server");
       moveAttributes(server, sslAttrs, "SSL");
       moveAttributes(server, proxyAttrs, "ProxyServer");
       moveAttributes(server, ldapAttrs, "LDAP");
       if (programName.equals("ISN")) fixRSNAROOT(server);
       if (isMIRC(root)) fixFileServiceAnonymizerID(root);
       setFileText(configFile, toString(doc));
     } catch (Exception ex) {
       cp.appendln(Color.red, "\nUnable to convert the config file schema.");
       cp.appendln(Color.black, "");
     }
   } else {
     cp.appendln(Color.red, "\nUnable to find the config file to check the schema.");
     cp.appendln(Color.black, "");
   }
 }
Esempio n. 2
0
 public static void main(String[] args) {
   Personne[] tab = {
     new Personne("thibault", "Rougier", 2001),
     new Personne("thomas", "Niesseron", 1987),
     new Personne("thifaine", "Mitenne", 1959),
     new Personne("maxime", "Forest", 1995),
     new Personne("jules", "Forest", 1995)
   };
   System.out.println("--- Nes apres 1985 : ");
   Stream.of(tab)
       .filter(pp -> pp.getAnnee() > 1985)
       .forEach(pp -> System.out.print(pp.getPrenom() + ", "));
   System.out.println("\n--- Nes avant 2000 :");
   long nombre =
       Stream.of(tab)
           .filter(pp -> pp.getAnnee() < 2000)
           .sorted(Comparator.comparing(Personne::getNom))
           .peek(pp -> System.out.print(pp.getNom() + " "))
           .count();
   System.out.println("\n       Ils sont " + nombre);
   System.out.println("--- Tous tries sur nom + prenom : ");
   Stream.of(tab)
       .sorted(Comparator.comparing(pp -> pp.getNom() + pp.getPrenom()))
       .forEach(pp -> System.out.print("(" + pp.getNom() + ", " + pp.getPrenom() + ") "));
 }
Esempio n. 3
0
  /** Initializes the SDK and the controller. */
  public boolean initializeTwitch() {
    if (m_SdkInitialized) {
      return false;
    }

    String dllPath = m_DllPath;
    if (dllPath == "") {
      dllPath = "./";
    }

    m_Stream.setStreamCallbacks(this);

    ErrorCode err = m_Stream.initialize(m_ClientId, VideoEncoder.TTV_VID_ENC_DEFAULT, dllPath);
    if (!checkError(err)) {
      m_Stream.setStreamCallbacks(null);
      return false;
    }

    err = m_Stream.setTraceLevel(MessageLevel.TTV_ML_ERROR);
    if (!checkError(err)) {
      m_Stream.setStreamCallbacks(null);
      return false;
    }

    if (ErrorCode.succeeded(err)) {
      m_SdkInitialized = true;
      setBroadcastState(BroadcastState.Initialized);
      return true;
    }

    return false;
  }
Esempio n. 4
0
 private Hashtable<String, String> getJarManifestAttributes(String path) {
   Hashtable<String, String> h = new Hashtable<String, String>();
   JarInputStream jis = null;
   try {
     cp.appendln(Color.black, "Looking for " + path);
     InputStream is = getClass().getResourceAsStream(path);
     if (is == null) {
       if (!path.endsWith("/MIRC.jar")) {
         cp.appendln(Color.red, "...could not find it.");
       } else {
         cp.appendln(
             Color.black,
             "...could not find it. [OK, this is a " + programName + " installation]");
       }
       return null;
     }
     jis = new JarInputStream(is);
     Manifest manifest = jis.getManifest();
     h = getManifestAttributes(manifest);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   if (jis != null) {
     try {
       jis.close();
     } catch (Exception ignore) {
     }
   }
   return h;
 }
Esempio n. 5
0
  public boolean shutdown(int port, boolean ssl) {
    try {
      String protocol = "http" + (ssl ? "s" : "");
      URL url = new URL(protocol, "127.0.0.1", port, "shutdown");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("servicemanager", "shutdown");
      conn.connect();

      StringBuffer sb = new StringBuffer();
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      int n;
      char[] cbuf = new char[1024];
      while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n);
      br.close();
      String message = sb.toString().replace("<br>", "\n");
      if (message.contains("Goodbye")) {
        cp.appendln("Shutting down the server:");
        String[] lines = message.split("\n");
        for (String line : lines) {
          cp.append("...");
          cp.appendln(line);
        }
        return true;
      }
    } catch (Exception ex) {
    }
    cp.appendln("Unable to shutdown CTP");
    return false;
  }
Esempio n. 6
0
 @SuppressWarnings("unchecked")
 @Override
 default Tuple2<Seq<T>, Seq<T>> span(Predicate<? super T> predicate) {
   Objects.requireNonNull(predicate, "predicate is null");
   if (isEmpty()) {
     return Tuple.of(Stream.empty(), Stream.empty());
   } else {
     return (Tuple2<Seq<T>, Seq<T>>) traverse().span(predicate);
   }
 }
Esempio n. 7
0
 static <T> Stream<T> levelOrder(Tree<T> tree) {
   Stream<T> result = Stream.empty();
   final java.util.Queue<Tree<T>> queue = new java.util.LinkedList<>();
   queue.add(tree);
   while (!queue.isEmpty()) {
     final Tree<T> next = queue.remove();
     result = result.prepend(next.getValue());
     queue.addAll(next.getChildren().toJavaList());
   }
   return result.reverse();
 }
Esempio n. 8
0
 static <T> Stream<T> inOrder(Tree<T> tree) {
   if (tree.isLeaf()) {
     return Stream.of(tree.getValue());
   } else {
     final List<Node<T>> children = tree.getChildren();
     return children
         .tail()
         .foldLeft(Stream.<T>empty(), (acc, child) -> acc.appendAll(inOrder(child)))
         .prepend(tree.getValue())
         .prependAll(inOrder(children.head()));
   }
 }
Esempio n. 9
0
 /** The remote invocation occurs only if the cache misses. */
 public Stream invoke(RemoteCall c, RemoteReference ref) throws NetworkException {
   Stream args = ((RmeRemoteCall) c).getArguments();
   if (table.containsKey(args)) {
     Stream returnValue = OrbAccessor.getStream();
     returnValue.fill((RmeStream) table.get(args));
     return returnValue;
   } else {
     Stream returnValue = super.invoker.invoke(c, ref);
     Stream backupValue = OrbAccessor.getStream();
     backupValue.fill(returnValue);
     table.put(args, backupValue);
     return returnValue;
   }
 }
Esempio n. 10
0
  public ErrorCode submitFrame(FrameBuffer bgraFrame) {
    if (this.getIsPaused()) {
      resumeBroadcasting();
    } else if (!this.getIsBroadcasting()) {
      return ErrorCode.TTV_EC_STREAM_NOT_STARTED;
    }

    ErrorCode ret = m_Stream.submitVideoFrame(bgraFrame);

    // if there is a problem when submitting a frame let the client know
    if (ret != ErrorCode.TTV_EC_SUCCESS) {
      String err = ErrorCode.getString(ret);
      if (ErrorCode.succeeded(ret)) {
        reportWarning(String.format("Warning in SubmitTexturePointer: %s\n", err));
      } else {
        reportError(String.format("Error in SubmitTexturePointer: %s\n", err));

        // errors are not recoverable
        stopBroadcasting();
      }

      if (m_Listener != null) {
        m_Listener.onframeSubmissionIssue(ret);
      }
    }

    return ret;
  }
Esempio n. 11
0
  /**
   * Logs the current user out and clear the username and auth token. This will terminate the
   * broadcast if necessary.
   */
  public boolean logout() {
    if (getIsIngestTesting()) {
      return false;
    }

    // stop synchronously
    if (this.getIsBroadcasting()) {
      m_Stream.stop(false);
    }

    m_UserName = "";
    m_AuthToken = new AuthToken();

    if (!m_LoggedIn) {
      return false;
    }

    m_LoggedIn = false;

    // only fire the event if the logout was explicitly requested
    if (!m_ShuttingDown) {
      try {
        if (m_Listener != null) {
          m_Listener.onLoggedOut();
        }
      } catch (Exception x) {
        reportError(x.toString());
      }
    }

    setBroadcastState(BroadcastState.Initialized);

    return true;
  }
Esempio n. 12
0
  /**
   * Sets the visible data about the channel of the currently logged in user.
   *
   * @param channel The name of the channel.
   * @param game The name of the game. If the empty string or null then this parameter is ignored.
   * @param title The title of the channel. If the empty string or null then this parameter is
   *     ignored.
   * @return Whether or not the request was made
   */
  public boolean setStreamInfo(String channel, String game, String title) {
    if (!m_LoggedIn) {
      return false;
    }

    if (channel == null || channel == "") {
      channel = m_UserName;
    }

    if (game == null) {
      game = "";
    }

    if (title == null) {
      title = "";
    }

    StreamInfoForSetting info = new StreamInfoForSetting();
    info.streamTitle = title;
    info.gameName = game;

    ErrorCode err = m_Stream.setStreamInfo(m_AuthToken, channel, info);
    checkError(err);

    return ErrorCode.succeeded(err);
  }
Esempio n. 13
0
  public static void main(String[] args) {

    Map<Integer, HashSet<String>> withSet =
        Stream.of("jon", "andrew", "harvey", "bil")
            .collect(Collectors.groupingBy(String::length, HashSet::new));
    out.println(withSet);
  }
Esempio n. 14
0
 /**
  * Requests a list of all games matching the given search string. The result will be returned
  * asynchronously via OnGameNameListReceived.
  *
  * @param str Whether or not the request was made
  */
 public void requestGameNameList(String str) {
   ErrorCode ret = m_Stream.getGameNameList(str);
   if (ErrorCode.failed(ret)) {
     String err = ErrorCode.getString(ret);
     reportError(String.format("Error in GetGameNameList: %s\n", err));
   }
 }
Esempio n. 15
0
 @Override
 default Seq<T> dropRight(int n) {
   if (n >= length()) {
     return Stream.empty();
   } else {
     return traverse().dropRight(n);
   }
 }
Esempio n. 16
0
 @Override
 default Seq<T> takeRight(int n) {
   if (isEmpty()) {
     return Stream.empty();
   } else {
     return traverse().takeRight(n);
   }
 }
Esempio n. 17
0
  public static void main(String[] args) throws IOException {
    Path path = Paths.get("../alice.txt");
    String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);

    Stream<String> words = Stream.of(contents.split("[\\P{L}]+"));
    show("words", words);
    Stream<String> song = Stream.of("gently", "down", "the", "stream");
    show("song", song);
    Stream<String> silence = Stream.empty();
    silence = Stream.<String>empty(); // Explicit type specification
    show("silence", silence);

    Stream<String> echos = Stream.generate(() -> "Echo");
    show("echos", echos);

    Stream<Double> randoms = Stream.generate(Math::random);
    show("randoms", randoms);

    Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));
    show("integers", integers);

    Stream<String> wordsAnotherWay = Pattern.compile("[\\P{L}]+").splitAsStream(contents);
    show("wordsAnotherWay", wordsAnotherWay);

    try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
      show("lines", lines);
    }
  }
Esempio n. 18
0
 @Override
 default Seq<T> distinctBy(Comparator<? super T> comparator) {
   Objects.requireNonNull(comparator, "comparator is null");
   if (isEmpty()) {
     return Stream.empty();
   } else {
     return traverse().distinctBy(comparator);
   }
 }
Esempio n. 19
0
 @Override
 default <U> Seq<T> distinctBy(Function<? super T, ? extends U> keyExtractor) {
   Objects.requireNonNull(keyExtractor, "keyExtractor is null");
   if (isEmpty()) {
     return Stream.empty();
   } else {
     return traverse().distinctBy(keyExtractor);
   }
 }
Esempio n. 20
0
 @Override
 default Seq<T> filter(Predicate<? super T> predicate) {
   Objects.requireNonNull(predicate, "predicate is null");
   if (isEmpty()) {
     return Stream.empty();
   } else {
     return traverse().filter(predicate);
   }
 }
Esempio n. 21
0
  /**
   * Send the beginning datapoint of an event that has a beginning and end.
   *
   * @param name A specific name for an event meant to be queryable
   * @param streamTime Number of milliseconds into the broadcast for when event occurs
   * @param humanDescription Long form string to describe the meaning of an event. Maximum length is
   *     1000 characters
   * @param data A valid JSON object that is the payload of an event. Values in this JSON object
   *     have to be strings. Maximum of 50 keys are allowed. Maximum length for values are 255
   *     characters.
   * @return A positive, unique sequenceId returned that associates a start and end event together.
   *     This will be -1 if failed.
   */
  public long startSpanMetaData(
      String name, long streamTime, String humanDescription, String data) {
    long ret =
        m_Stream.sendStartSpanMetaData(m_AuthToken, name, streamTime, humanDescription, data);
    if (ret == -1) {
      reportError(String.format("Error in SendStartSpanMetaData\n"));
    }

    return ret;
  }
Esempio n. 22
0
  /**
   * Runs a commercial on the channel. Must be broadcasting.
   *
   * @return Whether or not successful
   */
  public boolean runCommercial() {
    if (!this.getIsBroadcasting()) {
      return false;
    }

    ErrorCode err = m_Stream.runCommercial(m_AuthToken);
    checkError(err);

    return ErrorCode.succeeded(err);
  }
Esempio n. 23
0
 public static <T> void show(String title, Stream<T> stream) {
   final int SIZE = 10;
   List<T> firstElements = stream.limit(SIZE + 1).collect(Collectors.toList());
   System.out.print(title + ": ");
   if (firstElements.size() <= SIZE) System.out.println(firstElements);
   else {
     firstElements.remove(SIZE);
     String out = firstElements.toString();
     System.out.println(out.substring(0, out.length() - 1) + ", ...]");
   }
 }
Esempio n. 24
0
  public void connectGraph() {
    // make sure I have some elements - not sure what to do otherwise
    assert !streamElements.isEmpty();

    // go through the list and connect it together:
    ListIterator<Stream> childIter;
    childIter = (ListIterator<Stream>) streamElements.iterator();
    Stream source = null;

    while (childIter.hasNext()) {
      // advance the iterator:
      Stream sink = childIter.next();
      assert sink != null;

      // setup the sink itself
      sink.setupOperator();

      if (source != null && source.getOutputChannel() != null) {
        // create and connect a pass filter
        ChannelConnectFilter connect = new ChannelConnectFilter();
        Channel in = source.getOutputChannel();
        Channel out = sink.getInputChannel();
        connect.useChannels(in, out);
        connect.setupOperator();
      }
      source = sink;
    }

    // set myself up with proper input and output
    {
      inputChannel = streamElements.getFirst().getInputChannel();
      outputChannel = streamElements.getLast().getOutputChannel();
    }
  }
Esempio n. 25
0
  void setupBufferLengths(Scheduler buffers) {
    ListIterator<Stream> childIter;
    childIter = (ListIterator<Stream>) streamElements.iterator();
    Stream source = null;
    Stream sink = null;

    // go through all the children
    while (childIter.hasNext()) {
      // advance the iterator:
      Stream child = childIter.next();
      assert child != null;
      child.setupBufferLengths(buffers);

      source = sink;
      sink = child;

      if (source != null) {
        assert sink != null;

        int buffSize = buffers.getBufferSizeBetween(new Iterator(source), new Iterator(sink));
        assert buffSize != 0;

        StreamIt.totalBuffer += buffSize;

        source.getOutputChannel().makePassThrough();
        sink.getInputChannel().setChannelSize(buffSize);
      }
    }
  }
Esempio n. 26
0
  private void updateWindowsServiceInstaller() {
    try {
      File dir = new File(directory, "CTP");
      if (suppressFirstPathElement) dir = dir.getParentFile();
      File windows = new File(dir, "windows");
      File install = new File(windows, "install.bat");
      cp.appendln(Color.black, "Windows service installer:");
      cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
      String bat = getFileText(install);
      Properties props = new Properties();
      String home = dir.getAbsolutePath();
      cp.appendln(Color.black, "...home: " + home);
      home = home.replaceAll("\\\\", "\\\\\\\\");
      props.put("home", home);

      bat = replace(bat, props);
      setFileText(install, bat);
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println("Unable to update the windows service install.barfile.");
    }
  }
Esempio n. 27
0
  /**
   * Send a singular action metadata point to Twitch's metadata service.
   *
   * @param name A specific name for an event meant to be queryable
   * @param streamTime Number of milliseconds into the broadcast for when event occurs
   * @param humanDescription Long form string to describe the meaning of an event. Maximum length is
   *     1000 characters
   * @param data A valid JSON object that is the payload of an event. Values in this JSON object
   *     have to be strings. Maximum of 50 keys are allowed. Maximum length for values are 255
   *     characters.
   * @return True if submitted and no error, false otherwise.
   */
  public boolean sendActionMetaData(
      String name, long streamTime, String humanDescription, String data) {
    ErrorCode ret =
        m_Stream.sendActionMetaData(m_AuthToken, name, streamTime, humanDescription, data);
    if (ErrorCode.failed(ret)) {
      String err = ErrorCode.getString(ret);
      reportError(String.format("Error while sending meta data: %s\n", err));

      return false;
    }

    return true;
  }
Esempio n. 28
0
  /**
   * Cleans up and shuts down the SDK and the controller. This will force broadcasting to terminate
   * and the user to be logged out.
   */
  public boolean shutdownTwitch() {
    if (!m_SdkInitialized) {
      return true;
    } else if (getIsIngestTesting()) {
      return false;
    }

    m_ShuttingDown = true;

    logout();

    m_Stream.setStreamCallbacks(null);
    m_Stream.setStatCallbacks(null);

    ErrorCode err = m_Stream.shutdown();
    checkError(err);

    m_SdkInitialized = false;
    m_ShuttingDown = false;
    setBroadcastState(BroadcastState.Uninitialized);

    return true;
  }
Esempio n. 29
0
  public static void main(String... args) {

    List<Integer> numbers = Arrays.asList(3, 4, 5, 1, 2);

    Arrays.stream(numbers.toArray()).forEach(System.out::println);
    int calories = Dish.menu.stream().mapToInt(Dish::getCalories).sum();
    System.out.println("Number of calories:" + calories);

    // max and OptionalInt
    OptionalInt maxCalories = Dish.menu.stream().mapToInt(Dish::getCalories).max();

    int max;
    if (maxCalories.isPresent()) {
      max = maxCalories.getAsInt();
    } else {
      // we can choose a default value
      max = 1;
    }
    System.out.println(max);

    // numeric ranges
    IntStream evenNumbers = IntStream.rangeClosed(1, 100).filter(n -> n % 2 == 0);

    System.out.println(evenNumbers.count());

    Stream<int[]> pythagoreanTriples =
        IntStream.rangeClosed(1, 100)
            .boxed()
            .flatMap(
                a ->
                    IntStream.rangeClosed(a, 100)
                        .filter(b -> Math.sqrt(a * a + b * b) % 1 == 0)
                        .boxed()
                        .map(b -> new int[] {a, b, (int) Math.sqrt(a * a + b * b)}));

    pythagoreanTriples.forEach(t -> System.out.println(t[0] + ", " + t[1] + ", " + t[2]));
  }
Esempio n. 30
0
 private void setOwnership(File dir, String group, String owner) {
   try {
     Path path = dir.toPath();
     UserPrincipalLookupService lookupService =
         FileSystems.getDefault().getUserPrincipalLookupService();
     GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(group);
     UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(owner);
     PosixFileAttributeView pfav =
         Files.getFileAttributeView(path, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
     pfav.setGroup(groupPrincipal);
     pfav.setOwner(userPrincipal);
   } catch (Exception ex) {
     cp.appendln("Unable to set the file group and owner for\n   " + dir);
   }
 }