private final void socketrun() {
   do {
     if (link.socketport != 0) {
       try {
         Socket socket =
             new Socket(InetAddress.getByName(getCodeBase().getHost()), link.socketport);
         socket.setSoTimeout(30000);
         socket.setTcpNoDelay(true);
         link.s = socket;
       } catch (Exception _ex) {
         link.s = null;
       }
       link.socketport = 0;
     }
     if (link.runme != null) {
       Thread thread = new Thread(link.runme);
       thread.setDaemon(true);
       thread.start();
       link.runme = null;
     }
     if (link.iplookup != null) {
       String s = "unknown";
       try {
         s = InetAddress.getByName(link.iplookup).getHostName();
       } catch (Exception _ex) {
       }
       link.host = s;
       link.iplookup = null;
     }
     try {
       Thread.sleep(100L);
     } catch (Exception _ex) {
     }
   } while (true);
 }
Example #2
1
 void start() {
   if (t == null) {
     t = new Thread(this, "UDP.OutgoingPacketHandler thread");
     t.setDaemon(true);
     t.start();
   }
 }
Example #3
1
 @Override
 /** {@inheritDoc} */
 public Thread newThread(Runnable r) {
   Thread t = new Thread(r);
   t.setDaemon(true);
   return t;
 }
Example #4
0
  /**
   * 'handler' can be of any type that implements 'exportedInterface', but only methods declared by
   * the interface (and its superinterfaces) will be invocable.
   */
  public <T> InAppServer(
      String name,
      String portFilename,
      InetAddress inetAddress,
      Class<T> exportedInterface,
      T handler) {
    this.fullName = name + "Server";
    this.exportedInterface = exportedInterface;
    this.handler = handler;

    // In the absence of authentication, we shouldn't risk starting a server as root.
    if (System.getProperty("user.name").equals("root")) {
      Log.warn(
          "InAppServer: refusing to start unauthenticated server \"" + fullName + "\" as root!");
      return;
    }

    try {
      File portFile = FileUtilities.fileFromString(portFilename);
      secretFile = new File(portFile.getPath() + ".secret");
      Thread serverThread = new Thread(new ConnectionAccepter(portFile, inetAddress), fullName);
      // If there are no other threads left, the InApp server shouldn't keep us alive.
      serverThread.setDaemon(true);
      serverThread.start();
    } catch (Throwable th) {
      Log.warn("InAppServer: couldn't start \"" + fullName + "\".", th);
    }
    writeNewSecret();
  }
 /**
  * Send a message to a specified address.
  *
  * @param message Pre-formatted message to send.
  * @param receiverAddress Address to send it to.
  * @param receiverPort Receiver port.
  * @throws IOException If there is a problem connecting or sending.
  */
 public void sendMessage(
     byte message[], InetAddress receiverAddress, int receiverPort, boolean retry)
     throws IOException {
   if (message == null || receiverAddress == null)
     throw new IllegalArgumentException("Null argument");
   SSLSocket sock =
       (SSLSocket)
           this.stack.ioHandler.sendBytes(receiverAddress, receiverPort, "TLS", message, retry);
   //
   // Created a new socket so close the old one and s
   // Check for null (bug fix sent in by Christophe)
   if (sock != mySock && sock != null) {
     try {
       if (mySock != null) mySock.close();
     } catch (IOException ex) {
       /* ignore */
     }
     mySock = sock;
     this.myClientInputStream = mySock.getInputStream();
     this.myClientOutputStream = mySock.getOutputStream();
     // start a new reader on this end of the pipe.
     Thread mythread = new Thread(this);
     mythread.setDaemon(true);
     mythread.setName("TLSMessageChannelThread");
     mythread.start();
   }
 }
  /**
   * Start the server.
   *
   * @throws IOException if the socket is in use.
   */
  public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket.bind(
        (hostname != null)
            ? new InetSocketAddress(hostname, myPort)
            : new InetSocketAddress(myPort));

    myThread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                do {
                  try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    asyncRunner.exec(
                        new Runnable() {
                          @Override
                          public void run() {
                            OutputStream outputStream = null;
                            try {
                              outputStream = finalAccept.getOutputStream();
                              TempFileManager tempFileManager = tempFileManagerFactory.create();
                              HTTPSession session =
                                  new HTTPSession(
                                      tempFileManager,
                                      inputStream,
                                      outputStream,
                                      finalAccept.getInetAddress());
                              while (!finalAccept.isClosed()) {
                                session.execute();
                              }
                            } catch (Exception e) {
                              // When the socket is closed by the client,
                              // we throw our own SocketException
                              // to break the "keep alive" loop above.
                              if (!(e instanceof SocketException
                                  && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                e.printStackTrace();
                              }
                            } finally {
                              safeClose(outputStream);
                              safeClose(inputStream);
                              safeClose(finalAccept);
                              unRegisterConnection(finalAccept);
                            }
                          }
                        });
                  } catch (IOException e) {
                  }
                } while (!myServerSocket.isClosed());
              }
            });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
  }
Example #7
0
 public void start() {
   if (thread == null) {
     thread = new Thread(this, "UDP.UcastReceiverThread");
     thread.setDaemon(true);
     running = true;
     thread.start();
   }
 }
 @Override
 public void exec(Runnable code) {
   ++requestCount;
   Thread t = new Thread(code);
   t.setDaemon(true);
   t.setName("NanoHttpd Request Processor (#" + requestCount + ")");
   t.start();
 }
Example #9
0
  /** Start the network listening thread. */
  void start() {
    this.running = true;

    Thread thread = new Thread(this, "IceConnector@" + hashCode());

    thread.setDaemon(true);
    thread.start();
  }
Example #10
0
  @Override
  protected void setUp() throws Exception {
    tmp = IO.getFile("generated/tmp");
    tmp.mkdirs();
    IO.copy(IO.getFile("testdata/ws"), tmp);
    workspace = Workspace.getWorkspace(tmp);
    workspace.refresh();

    InfoRepository repo = workspace.getPlugin(InfoRepository.class);
    t1 = create("bsn-1", new Version(1, 0, 0));
    t2 = create("bsn-2", new Version(1, 0, 0));

    repo.put(new FileInputStream(t1), null);
    repo.put(new FileInputStream(t2), null);
    t1 = repo.get("bsn-1", new Version(1, 0, 0), null);
    t2 = repo.get("bsn-2", new Version(1, 0, 0), null);
    repo.put(new FileInputStream(IO.getFile("generated/biz.aQute.remote.launcher.jar")), null);

    workspace.getPlugins().add(repo);

    File storage = IO.getFile("generated/storage-1");
    storage.mkdirs();

    configuration = new HashMap<String, Object>();
    configuration.put(
        Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    configuration.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath());

    configuration.put(
        Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.2");

    framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration);
    framework.init();
    framework.start();
    context = framework.getBundleContext();
    location = "reference:" + IO.getFile("generated/biz.aQute.remote.agent.jar").toURI().toString();
    agent = context.installBundle(location);
    agent.start();

    thread =
        new Thread() {
          @Override
          public void run() {
            try {
              Main.main(
                  new String[] {
                    "-s", "generated/storage", "-c", "generated/cache", "-p", "1090", "-et"
                  });
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    thread.setDaemon(true);
    thread.start();

    super.setUp();
  }
Example #11
0
 synchronized void start() {
   if (queue.closed()) queue.reset();
   if (thread == null || !thread.isAlive()) {
     thread = getThreadFactory().newThread(this, "ViewHandler");
     thread.setDaemon(
         false); // thread cannot terminate if we have tasks left, e.g. when we as coord leave
     thread.start();
   }
 }
Example #12
0
  public void startConsole(boolean jLine) {
    this.jLine = jLine;

    sender = new ColoredCommandSender();
    Thread thread = new ConsoleCommandThread();
    thread.setName("ConsoleCommandThread");
    thread.setDaemon(true);
    thread.start();
  }
Example #13
0
  public synchronized void connect(long timeout) throws TransportException {
    try {
      switch (state) {
        case 0:
          break;
        case 3:
          return; // already connected
        case 4:
          state = 0;
          throw new TransportException("Connection in error", te);
        default:
          TransportException te = new TransportException("Invalid state: " + state);
          state = 0;
          throw te;
      }

      state = 1;
      te = null;
      thread = new Thread(this, name);
      thread.setDaemon(true);

      synchronized (thread) {
        thread.start();
        thread.wait(timeout); /* wait for doConnect */

        switch (state) {
          case 1: /* doConnect never returned */
            state = 0;
            thread = null;
            throw new TransportException("Connection timeout");
          case 2:
            if (te != null) {
                /* doConnect throw Exception */
              state = 4; /* error */
              thread = null;
              throw te;
            }
            state = 3; /* Success! */
            return;
        }
      }
    } catch (InterruptedException ie) {
      state = 0;
      thread = null;
      throw new TransportException(ie);
    } finally {
      /* This guarantees that we leave in a valid state
       */
      if (state != 0 && state != 3 && state != 4) {
        if (log.level >= 1) log.println("Invalid state: " + state);
        state = 0;
        thread = null;
      }
    }
  }
Example #14
0
  public static void main(String[] args) {

    Thread thread = new Thread(new Download(args));
    thread.setDaemon(true);
    thread.start();
    try {
      thread.join();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #15
0
  // Install redirection of passed InputStream and OutputStream from passed JavaVM
  // to this vm standard output and input streams.
  public static void plugTogether(JavaVM vm, InputStream in, OutputStream out) {
    String name = null;

    synchronized (lock) {
      name = "TestLibrary: StreamPipe-" + (count++);
    }

    Thread pipe = new StreamPipe(vm, in, out, name);
    pipe.setDaemon(true);
    pipe.start();
  }
Example #16
0
  /**
   * Creates an instance.
   *
   * @param pout Source of inputs
   * @param jTextArea Where the inputs are written.
   */
  public JConsoleOutLinker(PipedOutputStream pout, JTextArea jTextArea) {
    try {
      this.pin = new PipedInputStream(pout);
    } catch (IOException ioe) {
      throw new UIError("Unable to create input stream!");
    }
    this.jTextArea = jTextArea;

    thisThread = new Thread(this);
    thisThread.setDaemon(true);
    thisThread.start();
  }
Example #17
0
  public void startConsole(boolean jLine) {
    this.jLine = jLine;

    sender = new ColoredCommandSender();
    Thread thread = new ConsoleCommandThread();
    thread.setName("ConsoleCommandThread");
    thread.setDaemon(true);
    thread.start();

    /*logger.removeHandler(consoleHandler);
    consoleHandler = new FancyConsoleHandler();
    consoleHandler.setFormatter(new DateOutputFormatter(CONSOLE_DATE));
    logger.addHandler(consoleHandler);*/
  }
Example #18
0
 /**
  * Asynchronously sends a message to a single server, registering a listener to receive a callback
  * on success or exception. Multiple asynchronous lookups can be performed in parallel. Since the
  * callback may be invoked before the function returns, external synchronization is necessary.
  *
  * @param query The query to send
  * @param listener The object containing the callbacks.
  * @return An identifier, which is also a parameter in the callback
  */
 public Object sendAsync(final Message query, final ResolverListener listener) {
   final Object id;
   synchronized (this) {
     id = new Integer(uniqueID++);
   }
   Record question = query.getQuestion();
   String qname;
   if (question != null) qname = question.getName().toString();
   else qname = "(none)";
   String name = this.getClass() + ": " + qname;
   Thread thread = new ResolveThread(this, query, id, listener);
   thread.setName(name);
   thread.setDaemon(true);
   thread.start();
   return id;
 }
Example #19
0
  /**
   * Creates and starts the {@link #sendKeepAliveMessageThread} which is to send STUN keep-alive
   * <tt>Message</tt>s to the STUN server associated with the <tt>StunCandidateHarvester</tt> of
   * this instance in order to keep the <tt>Candidate</tt>s harvested by this instance alive.
   */
  private void createSendKeepAliveMessageThread() {
    synchronized (sendKeepAliveMessageSyncRoot) {
      Thread t = new SendKeepAliveMessageThread(this);
      t.setDaemon(true);
      t.setName(getClass().getName() + ".sendKeepAliveMessageThread: " + hostCandidate);

      boolean started = false;

      sendKeepAliveMessageThread = t;
      try {
        t.start();
        started = true;
      } finally {
        if (!started && (sendKeepAliveMessageThread == t)) sendKeepAliveMessageThread = null;
      }
    }
  }
Example #20
0
 /**
  * Forward stream in separate thread.
  *
  * @param name the name of the stream
  * @param out the output stream
  * @param in the input stream
  * @param releaseSemaphore if true the semaphore will be released
  */
 private void forward(
     @NonNls final String name,
     final OutputStream out,
     final InputStream in,
     final boolean releaseSemaphore) {
   final Runnable action =
       new Runnable() {
         public void run() {
           byte[] buffer = new byte[BUFFER_SIZE];
           int rc;
           try {
             try {
               try {
                 while ((rc = in.read(buffer)) != -1) {
                   out.write(buffer, 0, rc);
                 }
               } finally {
                 out.close();
               }
             } finally {
               in.close();
             }
           } catch (IOException e) {
             System.err.println(
                 GitBundle.message("sshmain.forwarding.failed", name, e.getMessage()));
             e.printStackTrace();
             myExitCode = 1;
             if (releaseSemaphore) {
               // in the case of error, release semaphore, so that application could exit
               myForwardCompleted.release(1);
             }
           } finally {
             if (releaseSemaphore) {
               myForwardCompleted.release(1);
             }
           }
         }
       };
   @SuppressWarnings({"HardCodedStringLiteral"})
   final Thread t = new Thread(action, "Forwarding " + name);
   t.setDaemon(true);
   t.start();
 }
Example #21
0
  public static void main(PeerFactory peerFactory, KeyStore keyStore, String[] args)
      throws Exception {

    long time = System.currentTimeMillis();
    String relPath;
    if ((args != null) && (args.length > 0) && args[0].equals("sh")) {
      relPath = pathToStoresSH;
    } else {
      relPath = pathToStores;
    }
    PATH = new File(System.getProperty("test.src", "."), relPath);
    CipherTest.peerFactory = peerFactory;
    System.out.print("Initializing test '" + peerFactory.getName() + "'...");
    //      secureRandom = new SecureRandom();
    //      secureRandom.nextInt();
    //      trustStore = readKeyStore(trustStoreFile);
    CipherTest.keyStore = keyStore;
    //      keyStore = readKeyStore(keyStoreFile);
    KeyManagerFactory keyFactory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyFactory.init(keyStore, "test12".toCharArray());
    keyManager = (X509ExtendedKeyManager) keyFactory.getKeyManagers()[0];

    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    trustManager = (X509TrustManager) tmf.getTrustManagers()[0];

    //      trustManager = new AlwaysTrustManager();
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager}, null);
    SSLContext.setDefault(context);

    CipherTest cipherTest = new CipherTest(peerFactory);
    Thread serverThread = new Thread(peerFactory.newServer(cipherTest), "Server");
    serverThread.setDaemon(true);
    serverThread.start();
    System.out.println("Done");
    cipherTest.run();
    time = System.currentTimeMillis() - time;
    System.out.println("Done. (" + time + " ms)");
  }
  /**
   * Initializes the server stored list. Synchronize server stored groups and contacts with the
   * local groups and contacts.
   */
  @Override
  public void init() {
    try {
      SipAccountIDImpl accountID = (SipAccountIDImpl) sipProvider.getAccountID();

      if (!accountID.isXiVOEnable()) return;

      boolean useSipCredentials = accountID.isClistOptionUseSipCredentials();

      String serverAddress = accountID.getClistOptionServerUri();
      String username = accountID.getAccountPropertyString(ProtocolProviderFactory.USER_ID);
      Address userAddress = sipProvider.parseAddressString(username);

      if (useSipCredentials) {
        username = ((SipUri) userAddress.getURI()).getUser();
      } else {
        username = accountID.getClistOptionUser();
      }

      try {
        connect(serverAddress);
      } catch (Throwable ex) {
        showError(ex, null, null);
        logger.error("Error connecting to server", ex);
        return;
      }

      Thread thread = new Thread(this, this.getClass().getName());
      thread.setDaemon(true);
      thread.start();

      if (!login(username)) {
        showError(null, null, "Unauthorized. Cannot login.");
        logger.error("Cannot login.");
        return;
      }
    } catch (Throwable t) {
      logger.error("Error init clist from xivo server");
    }
  }
 /**
  * Send message to whoever is connected to us. Uses the topmost via address to send to.
  *
  * @param msg is the message to send.
  * @param retry
  */
 private void sendMessage(byte[] msg, boolean retry) throws IOException {
   SSLSocket sock =
       (SSLSocket)
           this.stack.ioHandler.sendBytes(
               this.peerAddress, this.peerPort, this.peerProtocol, msg, retry);
   // Created a new socket so close the old one and stick the new
   // one in its place but dont do this if it is a datagram socket.
   // (could have replied via udp but received via tcp!).
   if (sock != mySock && sock != null) {
     try {
       if (mySock != null) mySock.close();
     } catch (IOException ex) {
     }
     mySock = sock;
     this.myClientInputStream = mySock.getInputStream();
     this.myClientOutputStream = mySock.getOutputStream();
     Thread thread = new Thread(this);
     thread.setDaemon(true);
     thread.setName("TLSMessageChannelThread");
     thread.start();
   }
 }
Example #24
0
  /** Starts the unicast and multicast receiver threads */
  void startThreads() throws Exception {
    if (ucast_receiver == null) {
      // start the listener thread of the ucast_recv_sock
      ucast_receiver = new UcastReceiver();
      ucast_receiver.start();
      if (Trace.trace) {
        Trace.info("UDP.startThreads()", "created unicast receiver thread");
      }
    }

    if (ip_mcast) {
      if (mcast_receiver != null) {
        if (mcast_receiver.isAlive()) {
          if (Trace.trace) {
            Trace.info(
                "UDP.createThreads()",
                "did not create new multicastreceiver thread as existing "
                    + "multicast receiver thread is still running");
          }
        } else {
          mcast_receiver = null; // will be created just below...
        }
      }

      if (mcast_receiver == null) {
        mcast_receiver = new Thread(this, "UDP mcast receiver");
        mcast_receiver.setPriority(Thread.MAX_PRIORITY); // needed ????
        mcast_receiver.setDaemon(true);
        mcast_receiver.start();
      }
    }
    if (use_outgoing_packet_handler) {
      outgoing_packet_handler.start();
    }
    if (use_incoming_packet_handler) {
      incoming_packet_handler.start();
    }
  }
Example #25
0
 private void runCpu() {
   if (cpuThread != null && cpuThread.isAlive()) return;
   runButton.setEnabled(false);
   execButton.setEnabled(false);
   stepButton.setEnabled(false);
   pauseButton.setEnabled(true);
   cpuThread =
       new Thread(
           new Runnable() {
             public void run() {
               debugger.run();
               // on halt
               runButton.setEnabled(true);
               execButton.setEnabled(true);
               stepButton.setEnabled(true);
               pauseButton.setEnabled(false);
               registersModel.fireUpdate();
               memoryModel.fireUpdate(0, RAM_SIZE - 1); // TODO optimize
             }
           },
           "CpuThread");
   cpuThread.setDaemon(true);
   cpuThread.start();
 }
 /**
  * Constructor - gets called from the SIPStack class with a socket on accepting a new client. All
  * the processing of the message is done here with the stack being freed up to handle new
  * connections. The sock input is the socket that is returned from the accept. Global data that is
  * shared by all threads is accessible in the Server structure.
  *
  * @param sock Socket from which to read and write messages. The socket is already connected (was
  *     created as a result of an accept).
  * @param sipStack Ptr to SIP Stack
  */
 protected TLSMessageChannel(
     SSLSocket sock, SIPMessageStack sipStack, TLSMessageProcessor msgProcessor)
     throws IOException {
   if (LogWriter.needsLogging) {
     sipStack.logWriter.logMessage("creating new TLSMessageChannel ");
     sipStack.logWriter.logStackTrace();
   }
   mySock = sock;
   peerAddress = mySock.getInetAddress();
   myAddress = sipStack.getHostAddress();
   myClientInputStream = mySock.getInputStream();
   myClientOutputStream = mySock.getOutputStream();
   mythread = new Thread(this);
   mythread.setDaemon(true);
   mythread.setName("TLSMessageChannelThread");
   // Stash away a pointer to our stack structure.
   stack = sipStack;
   this.tlsMessageProcessor = msgProcessor;
   this.myPort = this.tlsMessageProcessor.getPort();
   // Bug report by Vishwashanti Raj Kadiayl
   super.messageProcessor = msgProcessor;
   // Can drop this after response is sent potentially.
   mythread.start();
 }
 public static void startpriv(InetAddress inetaddress) {
   threadliveid = (int) (Math.random() * 99999999D);
   if (active) {
     try {
       Thread.sleep(500L);
     } catch (Exception _ex) {
     }
     active = false;
   }
   socketreq = 0;
   threadreq = null;
   dnsreq = null;
   savereq = null;
   urlreq = null;
   socketip = inetaddress;
   Thread thread = new Thread(new signlink());
   thread.setDaemon(true);
   thread.start();
   while (!active)
     try {
       Thread.sleep(50L);
     } catch (Exception _ex) {
     }
 }
 /**
  * Runs a test query agains the stun server. If it works we set useStun to true, otherwise we set
  * it to false.
  */
 private void launchStunServerTest() {
   Thread stunServerTestThread =
       new Thread("StunServerTestThread") {
         public void run() {
           DatagramSocket randomSocket = initRandomPortSocket();
           try {
             StunAddress stunAddress = detector.getMappingFor(randomSocket);
             randomSocket.disconnect();
             if (stunAddress != null) {
               useStun = true;
               logger.trace(
                   "StunServer check succeeded for server: "
                       + detector.getServerAddress()
                       + " and local port: "
                       + randomSocket.getLocalPort());
             } else {
               useStun = false;
               logger.trace(
                   "StunServer check failed for server: "
                       + detector.getServerAddress()
                       + " and local port: "
                       + randomSocket.getLocalPort()
                       + ". No address returned by server.");
             }
           } catch (Throwable ex) {
             logger.error(
                 "Failed to run a stun query against " + "server :" + detector.getServerAddress(),
                 ex);
             if (randomSocket.isConnected()) randomSocket.disconnect();
             useStun = false;
           }
         }
       };
   stunServerTestThread.setDaemon(true);
   stunServerTestThread.start();
 }
Example #29
0
  public static void main(String[] args) throws IOException {
    // now grab the first arg and see if it is a known command
    String firstArg = args.length > 0 ? args[0] : "";

    if (firstArg.contains("-help") || "-?".equals(firstArg)) {
      // setup the class loader
      MoquiStart moquiStartLoader = new MoquiStart(true);
      Thread.currentThread().setContextClassLoader(moquiStartLoader);
      Runtime.getRuntime()
          .addShutdownHook(new MoquiShutdown(null, null, moquiStartLoader.jarFileList));
      initSystemProperties(moquiStartLoader, false);

      System.out.println("Internal Class Path Jars:");
      for (JarFile jf : moquiStartLoader.jarFileList) {
        String fn = jf.getName();
        System.out.println(fn.contains("moqui_temp") ? fn.substring(fn.indexOf("moqui_temp")) : fn);
      }
      System.out.println("------------------------------------------------");
      System.out.println(
          "Current runtime directory (moqui.runtime): " + System.getProperty("moqui.runtime"));
      System.out.println(
          "Current configuration file (moqui.conf): " + System.getProperty("moqui.conf"));
      System.out.println(
          "To set these properties use something like: java -Dmoqui.conf=conf/MoquiStagingConf.xml -jar moqui.war ...");
      System.out.println("------------------------------------------------");
      System.out.println("Usage: java -jar moqui.war [command] [arguments]");
      System.out.println("-help, -? ---- Help (this text)");
      System.out.println("-load -------- Run data loader");
      System.out.println(
          "    -types=<type>[,<type>] ------- Data types to load (can be anything, common are: seed, seed-initial, demo, ...)");
      System.out.println(
          "    -components=<name>[,<name>] -- Component names to load for data types; if none specified loads from all");
      System.out.println("    -location=<location> ---- Location of data file to load");
      System.out.println(
          "    -timeout=<seconds> ------ Transaction timeout for each file, defaults to 600 seconds (10 minutes)");
      System.out.println(
          "    -dummy-fks -------------- Use dummy foreign-keys to avoid referential integrity errors");
      System.out.println(
          "    -use-try-insert --------- Try insert and update on error instead of checking for record first");
      System.out.println("    -tenantId=<tenantId> ---- ID for the Tenant to load the data into");
      System.out.println(
          "  If no -types or -location argument is used all known data files of all types will be loaded.");
      System.out.println("[default] ---- Run embedded Winstone server.");
      System.out.println(
          "  See https://code.google.com/p/winstone/wiki/CmdLineOption for all argument details.");
      System.out.println("  Selected argument details:");
      System.out.println(
          "    --httpPort               = set the http listening port. -1 to disable, Default is 8080");
      System.out.println(
          "    --httpListenAddress      = set the http listening address. Default is all interfaces");
      System.out.println(
          "    --httpsPort              = set the https listening port. -1 to disable, Default is disabled");
      System.out.println(
          "    --ajp13Port              = set the ajp13 listening port. -1 to disable, Default is 8009");
      System.out.println(
          "    --controlPort            = set the shutdown/control port. -1 to disable, Default disabled");
      System.out.println("");
      System.exit(0);
    }

    // make a list of arguments, remove the first one (the command)
    List<String> argList = new ArrayList<String>(Arrays.asList(args));

    // now run the command
    if ("-load".equals(firstArg)) {
      MoquiStart moquiStartLoader = new MoquiStart(true);
      Thread.currentThread().setContextClassLoader(moquiStartLoader);
      Runtime.getRuntime()
          .addShutdownHook(new MoquiShutdown(null, null, moquiStartLoader.jarFileList));
      initSystemProperties(moquiStartLoader, false);

      Map<String, String> argMap = new HashMap<String, String>();
      for (String arg : argList) {
        if (arg.startsWith("-")) arg = arg.substring(1);
        if (arg.contains("=")) {
          argMap.put(arg.substring(0, arg.indexOf("=")), arg.substring(arg.indexOf("=") + 1));
        } else {
          argMap.put(arg, "");
        }
      }

      try {
        System.out.println("Loading data with args [" + argMap + "]");
        Class<?> c = moquiStartLoader.loadClass("org.moqui.Moqui");
        Method m = c.getMethod("loadData", new Class[] {Map.class});
        m.invoke(null, argMap);
      } catch (Exception e) {
        System.out.println(
            "Error loading or running Moqui.loadData with args [" + argMap + "]: " + e.toString());
        e.printStackTrace();
      }
      System.exit(0);
    }

    // ===== Done trying specific commands, so load the embedded server

    // Get a start loader with loadWebInf=false since the container will load those we don't want to
    // here (would be on classpath twice)
    MoquiStart moquiStartLoader = new MoquiStart(false);
    Thread.currentThread().setContextClassLoader(moquiStartLoader);
    // NOTE: the MoquiShutdown hook is not set here because we want to get the winstone Launcher
    // object first, so done below...
    initSystemProperties(moquiStartLoader, true);

    Map<String, String> argMap = new HashMap<String, String>();
    for (String arg : argList) {
      if (arg.startsWith("--")) arg = arg.substring(2);
      if (arg.contains("=")) {
        argMap.put(arg.substring(0, arg.indexOf("=")), arg.substring(arg.indexOf("=") + 1));
      } else {
        argMap.put(arg, "");
      }
    }

    try {
      argMap.put("warfile", moquiStartLoader.outerFile.getName());
      System.out.println("Running Winstone embedded server with args [" + argMap + "]");

      /* for old Winstone 0.9.10:
      Class<?> c = moquiStartLoader.loadClass("winstone.Launcher");
      Method initLogger = c.getMethod("initLogger", new Class[] { Map.class });
      Method shutdown = c.getMethod("shutdown");
      // init the Winstone logger
      initLogger.invoke(null, argMap);
      // start Winstone with a new instance of the server
      Constructor wlc = c.getConstructor(new Class[] { Map.class });
      Object winstone = wlc.newInstance(argMap);
      */

      Class<?> c = moquiStartLoader.loadClass("net.winstone.Server");
      Method start = c.getMethod("start");
      // Method shutdown = c.getMethod("shutdown");
      // start Winstone with a new instance of the server
      Constructor wlc = c.getConstructor(new Class[] {Map.class});
      Object winstone = wlc.newInstance(argMap);
      start.invoke(winstone);

      // NOTE: winstone seems to have its own shutdown hook in the newer version, so using hook to
      // close files only:
      Thread shutdownHook = new MoquiShutdown(null, null, moquiStartLoader.jarFileList);
      shutdownHook.setDaemon(true);
      Runtime.getRuntime().addShutdownHook(shutdownHook);
    } catch (Exception e) {
      System.out.println(
          "Error loading or running Winstone embedded server with args ["
              + argMap
              + "]: "
              + e.toString());
      e.printStackTrace();
    }

    // now wait for break...
  }
Example #30
0
 public Thread newThread(Runnable r) {
   Thread t = DEFAULT.newThread(r);
   t.setDaemon(true);
   return t;
 }