/** * JobTracker.submitJob() kicks off a new job. * * <p>Create a 'JobInProgress' object, which contains both JobProfile and JobStatus. Those two * sub-objects are sometimes shipped outside of the JobTracker. But JobInProgress adds info that's * useful for the JobTracker alone. * * <p>We add the JIP to the jobInitQueue, which is processed asynchronously to handle * split-computation and build up the right TaskTracker/Block mapping. */ public synchronized JobStatus submitJob(String jobFile) throws IOException { totalSubmissions++; JobInProgress job = new JobInProgress(jobFile, this, this.conf); synchronized (jobs) { synchronized (jobsByArrival) { synchronized (jobInitQueue) { jobs.put(job.getProfile().getJobId(), job); jobsByArrival.add(job); jobInitQueue.add(job); jobInitQueue.notifyAll(); } } } return job.getStatus(); }
/** * Gets the urlClassLoader that enables to access to the objects jar files. * * @return an URLClassLoader */ public URLClassLoader getObjectsClassLoader() { if (objectsClassLoader == null) { try { if (isExecutionMode()) { URL[] listUrl = new URL[1]; listUrl[0] = instance.getTangaraPath().toURI().toURL(); objectsClassLoader = new URLClassLoader(listUrl); } else { File f = new File(instance.getTangaraPath().getParentFile(), "objects"); File[] list = f.listFiles(); Vector<URL> vector = new Vector<URL>(); for (int i = 0; i < list.length; i++) { if (list[i].getName().endsWith(".jar")) vector.add(list[i].toURI().toURL()); } File flib = new File( instance.getTangaraPath().getParentFile().getAbsolutePath().replace("\\", "/") + "/objects/lib"); File[] listflib = flib.listFiles(); for (int j = 0; j < listflib.length; j++) { if (listflib[j].getName().endsWith(".jar")) vector.add(listflib[j].toURI().toURL()); } URL[] listUrl = new URL[vector.size()]; for (int j = 0; j < vector.size(); j++) listUrl[j] = vector.get(j); objectsClassLoader = new URLClassLoader(listUrl); } } catch (Exception e1) { displayError("URL MAL FORMED " + e1); return null; } } return objectsClassLoader; }
public synchronized void dispatchMessage(ClientInfo aClientInfo, String aMessage) { Socket socket = aClientInfo.mSocket; aMessage = "<" + aClientInfo.login + "> " + aMessage; mMessageQueue.add(aMessage); System.out.println(aMessage); notify(); }
public void addThread(WorkerThread thread) { threads.add(thread); Logger.log(Level.DEBUG, Messages.getString("connection_opened", Settings.getLocale())); if (FancyFileServer.getGUI() != null) { FancyFileServer.getGUI().updateConnectionsCounter(); } }
/** Utility method to stuff an entire enumeration into a vector */ public static Vector Enum2Vector(Enumeration e) { Vector v = new Vector(); while (e.hasMoreElements()) { v.add(e.nextElement()); } return v; }
public void addConnectionListener(NCCPConnection.ConnectionListener l) { if (!listeners.contains(l)) { ExpCoordinator.printer.print( new String("NCCPConnection.addConnectionListener to " + toString()), 6); listeners.add(l); } }
public static Vector expandFileList(String[] files, boolean inclDirs) { Vector v = new Vector(); if (files == null) return v; for (int i = 0; i < files.length; i++) v.add(new File(URLDecoder.decode(files[i]))); for (int i = 0; i < v.size(); i++) { File f = (File) v.get(i); if (f.isDirectory()) { File[] fs = f.listFiles(); for (int n = 0; n < fs.length; n++) v.add(fs[n]); if (!inclDirs) { v.remove(i); i--; } } } return v; }
public synchronized TaskReport[] getReduceTaskReports(String jobid) { JobInProgress job = (JobInProgress) jobs.get(jobid); if (job == null) { return new TaskReport[0]; } else { Vector reports = new Vector(); Vector completeReduceTasks = job.reportTasksInProgress(false, true); for (Iterator it = completeReduceTasks.iterator(); it.hasNext(); ) { TaskInProgress tip = (TaskInProgress) it.next(); reports.add(tip.generateSingleReport()); } Vector incompleteReduceTasks = job.reportTasksInProgress(false, false); for (Iterator it = incompleteReduceTasks.iterator(); it.hasNext(); ) { TaskInProgress tip = (TaskInProgress) it.next(); reports.add(tip.generateSingleReport()); } return (TaskReport[]) reports.toArray(new TaskReport[reports.size()]); } }
public Vector completedJobs() { Vector v = new Vector(); for (Iterator it = jobs.values().iterator(); it.hasNext(); ) { JobInProgress jip = (JobInProgress) it.next(); JobStatus status = jip.getStatus(); if (status.getRunState() == JobStatus.SUCCEEDED) { v.add(jip); } } return v; }
public Vector runningJobs() { Vector v = new Vector(); for (Iterator it = jobs.values().iterator(); it.hasNext(); ) { JobInProgress jip = (JobInProgress) it.next(); JobStatus status = jip.getStatus(); if (status.getRunState() == JobStatus.RUNNING) { v.add(jip); } } return v; }
public Track add(Track track) { synchronized (this) { Track copy; if ((copy = getTrack(track)) == null) { copy = new Track((Element) doc.importNode(track.getElement(), false)); docElt.appendChild(copy.getElement()); tracks.add(copy); hash.put(copy.getKey(), copy); } return copy; } }
public void sendMessage(NCCP.Message msg) { if (isClosed() || isFailed()) connect(); if (isConnected()) { ExpCoordinator.printer.print("NCCPConnection::sendMessage", 5); if (proxy != null) proxy.sendMessage(msg, this); else { if (nonProxy != null) nonProxy.sendMessage(msg); } } else // still can't connect { pendingMessages.add(msg); } }
public void load(InputStream is) throws IOException, ParserConfigurationException, SAXException { doc = db.parse(is); docElt = doc.getDocumentElement(); if (docElt.getTagName().equals(docElementName)) { NodeList nl = docElt.getElementsByTagName(trackElementName); for (int i = 0; i < nl.getLength(); i++) { Element elt = (Element) nl.item(i); Track track = new Track(elt); tracks.add(track); hash.put(track.getKey(), track); } } }
public static Vector extractLinks(String rawPage, String page) { int index = 0; Vector links = new Vector(); while ((index = page.indexOf("<a ", index)) != -1) { if ((index = page.indexOf("href", index)) == -1) break; if ((index = page.indexOf("=", index)) == -1) break; String remaining = rawPage.substring(++index); StringTokenizer st = new StringTokenizer(remaining, "\t\n\r\"'>#"); String strLink = st.nextToken(); if (!links.contains(strLink)) links.add(strLink); } return links; }
private String[] getNoAuthCiperSuites(String ciperSuites[]) { // Count the number of ciper suites. Vector<Integer> v = new Vector<Integer>(); for (int i = 0; i < ciperSuites.length; i++) { if (ciperSuites[i].indexOf("anon") != -1) v.add(new Integer(i)); } String ret[] = new String[v.size()]; for (int i = 0; i < v.size(); i++) { int tmp = v.get(i).intValue(); ret[i] = ciperSuites[tmp]; } return ret; }
public void run() { try { while (true) { Socket link = server.accept(); String id = Name + "_" + idCount; idCount++; Responder r = new Responder(); Session ias = new Session(id, this, link, r); clients.add(ias); Log.info(Name + ": Added client " + ias.sid); } } catch (Exception e) { Log.severe(Name + ": run " + e.toString()); } }
public void nick_name(String msg) { try { String name = msg.substring(13); this.setName(name); Vector v = father.onlineList; boolean isRepeatedName = false; int size = v.size(); for (int i = 0; i < size; i++) { ServerAgentThread tempSat = (ServerAgentThread) v.get(i); if (tempSat.getName().equals(name)) { isRepeatedName = true; break; } } if (isRepeatedName == true) { dout.writeUTF("<#NAME_REPEATED#>"); din.close(); dout.close(); sc.close(); flag = false; } else { v.add(this); father.refreshList(); String nickListMsg = ""; StringBuilder nickListMsgSb = new StringBuilder(); size = v.size(); for (int i = 0; i < size; i++) { ServerAgentThread tempSat = (ServerAgentThread) v.get(i); nickListMsgSb.append("!"); nickListMsgSb.append(tempSat.getName()); } nickListMsgSb.append("<#NICK_LIST#>"); nickListMsg = nickListMsgSb.toString(); Vector tempv = father.onlineList; size = tempv.size(); for (int i = 0; i < size; i++) { ServerAgentThread tempSat = (ServerAgentThread) tempv.get(i); tempSat.dout.writeUTF(nickListMsg); if (tempSat != this) { tempSat.dout.writeUTF("<#MSG#>" + this.getName() + "is now online...."); } } } } catch (IOException e) { e.printStackTrace(); } }
/** Update a message */ public void updateData(SOAPMonitorData soap) { int row; if (filter_data == null) { // No filter, so just fire table updated row = data.indexOf(soap); if (row != -1) { fireTableRowsUpdated(row, row); } } else { // Check if the row was being displayed row = filter_data.indexOf(soap); if (row == -1) { // Row was not displayed, so check for if it // now needs to be displayed if (filterMatch(soap)) { int index = -1; row = data.indexOf(soap) + 1; while ((row < data.size()) && (index == -1)) { index = filter_data.indexOf(data.elementAt(row)); if (index != -1) { // Insert at this location filter_data.add(index, soap); } row++; } if (index == -1) { // Insert at end index = filter_data.size(); filter_data.addElement(soap); } fireTableRowsInserted(index, index); } } else { // Row was displayed, so check if it needs to // be updated or removed if (filterMatch(soap)) { fireTableRowsUpdated(row, row); } else { filter_data.remove(soap); fireTableRowsDeleted(row, row); } } } }
public void run() { boolean status; sf.DEBUG("Listen server running."); // open up our server socket try { m_serverSocket = new ServerSocket(m_nPort); } catch (IOException e) { sf.VERBOSE("Could not listen on port: " + m_nPort); if (sf.cntrlWndw != null) { sf.cntrlWndw.ClearListenServer(); } return; } sf.VERBOSE("Listening for client connections on port " + m_nPort); // if (SerialForward.bSourceSim) // { SetDataSource(); sf.InitSerialPortIO(); // } // start listening for connections try { ClientServicer rcv; Socket currentSocket; while (!m_bShutdown) { currentSocket = m_serverSocket.accept(); ClientServicer newServicer = new ClientServicer(currentSocket, sf, this); newServicer.start(); vctServicers.add(newServicer); } m_serverSocket.close(); } catch (IOException e) { /*try { this.sleep(500); } catch (Exception e2) { }*/ sf.VERBOSE("Server Socket closed"); } finally { ShutdownAllClientServicers(); if (sf.serialPortIO != null) sf.serialPortIO.Shutdown(); sf.VERBOSE("--------------------------"); if (sf.cntrlWndw != null) { sf.cntrlWndw.ClearListenServer(); } } }
/** * Returns MediaDescription object with the specified properties. The returned object will respond * to Media.getMediaFormats(boolean) with a Vector of String objects specified by the 'formats * argument. * * @param media the media type, eg "audio" * @param port port number on which to receive media * @param numPorts number of ports used for this media stream * @param transport transport type, eg "RTP/AVP" * @param formats list of formats which should be specified by the returned MediaDescription * @return MediaDescription */ public MediaDescription createMediaDescription( String media, int port, int numPorts, String transport, String[] formats) { MediaDescriptionImpl mediaDescriptionImpl = new MediaDescriptionImpl(); try { MediaField mediaImpl = new MediaField(); mediaImpl.setMediaType(media); mediaImpl.setMediaPort(port); mediaImpl.setPortCount(numPorts); mediaImpl.setProtocol(transport); Vector formatsV = new Vector(formats.length); for (int i = 0; i < formats.length; i++) formatsV.add(formats[i]); mediaImpl.setMediaFormats(formatsV); mediaDescriptionImpl.setMedia(mediaImpl); } catch (SdpException s) { s.printStackTrace(); } return mediaDescriptionImpl; }
/** * Send the plugin list to a client. The list depends of the client's groups * * @param source the user that asked this command */ private void sendPluginList(ObjectConnection oc, String source) { Vector plist = new Vector(); Iterator plugins; String line = ""; try { UserConcept user = store.getUserStore().getUser(source); plugins = store.getPluginStore().getAuthorizedPlugins(user); while (plugins.hasNext()) { PluginConcept plugin = (PluginConcept) plugins.next(); line = plugin.getName(); line += " " + plugin.getVersion(); plist.add(line); } oc.write(plist); } catch (Exception e) { Logging.getLogger().warning("Unable to send the plugin list."); e.printStackTrace(); } }
public void addSession(Session ias) { clients.add(ias); }
public static void main(String[] args) throws IOException, InterruptedException { System.out.println("Auction Server starting"); try { // Get hostname by textual representation of IP address InetAddress addr = InetAddress.getLocalHost(); // = InetAddress.getByName("127.0.0.1"); String hostname = addr.getHostName(); // Get the host name System.out.println("ip address = " + addr.toString() + "\nHost name = " + hostname); } catch (UnknownHostException e) { } // used to let host user control flow of program BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // System.out.println("How many players are needed?"); int numPlayersNeeded = 2; // Integer.valueOf(br.readLine()); // make an auction with which clients interact Auction myAuction = new Auction(5, numPlayersNeeded); // auction with 5 slots // SELECT TYPE OF AUCTION Vector<SimultaneousAscendingAuctionServerThread> myThreads = new Vector<SimultaneousAscendingAuctionServerThread>(); ServerSocket serverSocket = null; int portNum = 7; // the luckiest port there is! // Try reading in the IP and socket number from the text file... try { BufferedReader in = new BufferedReader(new FileReader("./src/IP_and_Port.txt")); // two lines in this file. First is hostName/IP address, and second is socket number of host String hName = in.readLine(); // use the hostname found above and skip this one portNum = Integer.valueOf(in.readLine()); in.close(); } catch (IOException e) { } try { serverSocket = new ServerSocket(portNum); } catch (IOException e) { System.err.println("AuctionServer could not listen on port: " + portNum + "."); System.exit(-1); } System.out.println("Clients should join the auction now..."); boolean started = false; boolean firstThread = true; // used to designate first thread as "reporter" while (!started) { // (listening && !myAuction.isOver() ){ SimultaneousAscendingAuctionServerThread aThread = new SimultaneousAscendingAuctionServerThread( serverSocket.accept(), myAuction, numPlayersNeeded); // set first thread as the "reporter", so only one copy of info printed to cmd prompt aThread.start(); if (firstThread) { aThread.setReporter(true); firstThread = false; } myThreads.add(aThread); if (myThreads.size() >= numPlayersNeeded) { started = true; System.out.println("Auction should be ready to go..."); } else System.out.println( "need more players. Thread-count = " + myThreads.size() + " , idCount = " + myAuction.bidderIDs.size()); // myAuction was passed as a shallow copy... so only one auction exists } System.out.println("\nAuction has started with " + myThreads.size() + " agents!\n"); // The auction is running right now... can you feel it? // System.out.println("Press Enter to end host connections and close..."); // br.readLine(); // System.out.println("Auction is complete... closing connections"); for (int i = 0; i < myThreads.size(); i++) myThreads.get(i).join(); for (int i = 0; i < myThreads.size(); i++) if (myThreads.get(i).isAlive()) myThreads.get(i).closeConnection(); serverSocket.close(); } // end main()
public static void main(String[] args) { String specloc = System.getProperty("spec"); if (specloc == null) { System.out.print("No spec file given, quitting"); System.exit(0); } DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z"); java.util.Date date = new java.util.Date(); String startstamp = dateFormat.format(date); boolean firstrun = true; while (true) { System.out.println("Loading XML Spec file: " + specloc); // BufferedWriter out = null; SocketAcceptor acceptor = null; SocketAcceptor statusacceptor = null; Vector<MonitorThread> monitorlist = new Vector<MonitorThread>(); try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File(specloc)); doc.getDocumentElement().normalize(); String heartbeatportString = doc.getDocumentElement().getAttribute("heartbeatport"); String statusportString = doc.getDocumentElement().getAttribute("statusport"); String logfiledir = doc.getDocumentElement().getAttribute("logfiledir"); String masterlabel = doc.getDocumentElement().getAttribute("label"); String nodeid = doc.getDocumentElement().getAttribute("id"); String smtphost = doc.getDocumentElement().getAttribute("smtphost"); String l1mailto = doc.getDocumentElement().getAttribute("l1mailto"); String l2mailto = doc.getDocumentElement().getAttribute("l2mailto"); String l2threshold = doc.getDocumentElement().getAttribute("l2threshold"); if (heartbeatportString == null || heartbeatportString.equals("")) { System.out.println("No heartbeat specified in spec, quitting"); System.exit(0); } if (statusportString == null || statusportString.equals("")) { System.out.println("No status port specified in spec, quitting"); System.exit(0); } if (logfiledir == null || logfiledir.equals("")) { System.out.println("No logfile directory location specified in spec, quitting"); System.exit(0); } int heartbeatport = Integer.valueOf(heartbeatportString).intValue(); System.out.println("This Monitor is using port " + heartbeatport + " for heartbeat"); int statusport = Integer.valueOf(statusportString).intValue(); System.out.println("This Monitor is using port " + statusport + " for status updates"); System.out.println("Logging to directory " + logfiledir); Log log = new Log(logfiledir); log.nodelabel = masterlabel; log.setMailer(smtphost, l1mailto, l2mailto, convertStringToInt(l2threshold)); if (firstrun) { firstrun = false; log.logit("Monitor Node Started", "start", null); } log.logit("Logging started", "", null); ThreadPing threadping = new ThreadPing(log, false); Thread pinger = new Thread(threadping); threadping.thisThread = pinger; pinger.start(); log.pinger = threadping; // ShutdownHook hook = new ShutdownHook(out); // Runtime.getRuntime().addShutdownHook(hook); // Starting Heartbeat server acceptor = new NioSocketAcceptor(); acceptor.getSessionConfig().setReuseAddress(true); acceptor.getSessionConfig().setTcpNoDelay(true); acceptor.setReuseAddress(true); // acceptor.getFilterChain().addLast("logger", new LoggingFilter()); acceptor .getFilterChain() .addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); acceptor.setReuseAddress(true); // acceptor.setCloseOnDeactivation(true); acceptor.getSessionConfig().setTcpNoDelay(true); acceptor.setDefaultLocalAddress(new InetSocketAddress(heartbeatport)); Vector<IoSession> sessionlist = new Vector<IoSession>(); acceptor.setHandler(new HeartBeatHandler(sessionlist)); acceptor.bind(); // Starting Path Monitoring NodeList listOfServers = doc.getElementsByTagName("check"); int totalServers = listOfServers.getLength(); System.out.println("Total # of checks: " + totalServers); // Vector<PingMonitorThread> pinglist = new Vector<PingMonitorThread>(); // Vector<PortMonitorThread> portlist = new Vector<PortMonitorThread>(); // Vector<HeartbeatMonitorThread> heartbeatlist = new Vector<HeartbeatMonitorThread>(); System.out.println(); for (int i = 0; i < totalServers; i++) { Node serverNode = listOfServers.item(i); Element serverNodeElement = (Element) serverNode; String checklabel = serverNodeElement.getAttribute("label"); String host = serverNodeElement .getElementsByTagName("host") .item(0) .getChildNodes() .item(0) .getNodeValue(); String checktype = serverNodeElement .getElementsByTagName("checktype") .item(0) .getChildNodes() .item(0) .getNodeValue(); boolean enabled = true; if (serverNodeElement.getElementsByTagName("enabled").item(0) != null && serverNodeElement .getElementsByTagName("enabled") .item(0) .getChildNodes() .item(0) .getNodeValue() .toLowerCase() .equals("false")) { enabled = false; } String successrateString = serverNodeElement .getElementsByTagName("successrate") .item(0) .getChildNodes() .item(0) .getNodeValue(); String retryrateString = serverNodeElement .getElementsByTagName("retryrate") .item(0) .getChildNodes() .item(0) .getNodeValue(); // String l2thresholdoverride = // serverNodeElement.getElementsByTagName("l2threshold").item(0).getChildNodes().item(0).getNodeValue(); String l2thresholdoverride = getElementValue("l2threshold", serverNodeElement); // String l1mailtoadd = // serverNodeElement.getElementsByTagName("l1mailto").item(0).getChildNodes().item(0).getNodeValue(); String l1mailtoadd = getElementValue("l1mailto", serverNodeElement); // String l2mailtoadd = // serverNodeElement.getElementsByTagName("l2mailto").item(0).getChildNodes().item(0).getNodeValue(); String l2mailtoadd = getElementValue("l2mailto", serverNodeElement); int l2thresholdoverrideint = convertStringToInt(l2thresholdoverride); String[] l1mailtoaddarray = new String[0]; String[] l2mailtoaddarray = new String[0]; if (!l1mailtoadd.equals("")) { l1mailtoaddarray = l1mailtoadd.split(","); } if (!l2mailtoadd.equals("")) { l2mailtoaddarray = l2mailtoadd.split(","); } // System.out.println(l1mailtoaddarray.length + "-" + l2mailtoaddarray.length); int successrate = 30; int retryrate = 30; if (host == null || host.equals("")) { System.out.println("No Host, skipping this path"); enabled = false; } if (successrateString == null || successrateString.equals("")) { System.out.println( "No Success Rate defined, using default (" + successrate + " seconds)"); } else { successrate = Integer.valueOf(successrateString).intValue(); } if (retryrateString == null || retryrateString.equals("")) { System.out.println("No retry rate defined, using default (" + retryrate + " seconds)"); } else { retryrate = Integer.valueOf(retryrateString).intValue(); } System.out.println(checklabel); if (checktype.equals("heartbeat")) { String portString = serverNodeElement .getElementsByTagName("port") .item(0) .getChildNodes() .item(0) .getNodeValue(); if (portString == null || portString.equals("")) { System.out.println("No Heartbeat, skipping this path"); } else { int heartbeat = Integer.valueOf(portString).intValue(); System.out.println("Starting Heartbeat Check:"); System.out.println("Host: " + host); System.out.println("Port: " + heartbeat); System.out.println(); HeartbeatMonitorThread m = new HeartbeatMonitorThread( host, heartbeat, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Heartbeat Check - " + host + ":" + heartbeat, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit( "Heartbeat Check - " + host + ":" + heartbeat + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } } else if (checktype.equals("ping")) { System.out.println("Starting Ping Check:"); System.out.println("Host: " + host); System.out.println(); PingMonitorThread m = new PingMonitorThread(host, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Ping Check - " + host, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit("Ping Check - " + host + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } else if (checktype.equals("port")) { String portString = serverNodeElement .getElementsByTagName("port") .item(0) .getChildNodes() .item(0) .getNodeValue(); if (portString == null || portString.equals("")) { System.out.println("No Port Given, skipping"); } else { int heartbeat = Integer.valueOf(portString).intValue(); System.out.println("Starting Port Check:"); System.out.println("Host: " + host); System.out.println("Port: " + heartbeat); System.out.println(); PortMonitorThread m = new PortMonitorThread(host, heartbeat, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Port Check - " + host + ":" + heartbeat, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit( "Port Check - " + host + ":" + heartbeat + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } } } statusacceptor = new NioSocketAcceptor(); statusacceptor.setReuseAddress(true); // statusacceptor.getFilterChain().addLast("logger", new LoggingFilter()); statusacceptor.getSessionConfig().setTcpNoDelay(true); statusacceptor.getSessionConfig().setKeepAlive(true); statusacceptor.getSessionConfig().setBothIdleTime(5); statusacceptor.getSessionConfig().setReaderIdleTime(5); statusacceptor.getSessionConfig().setWriteTimeout(5); // statusacceptor.setReuseAddress(true); statusacceptor.setCloseOnDeactivation(true); statusacceptor.setDefaultLocalAddress(new InetSocketAddress(statusport)); statusacceptor.setHandler( new StatusHttpProtocolHandler( monitorlist, acceptor, statusacceptor, log, masterlabel, nodeid, sessionlist, startstamp)); statusacceptor.bind(); System.out.println("Status Listener activated..."); } catch (Exception e) { e.printStackTrace(); try { // out.flush(); // out.close(); } catch (Exception e2) { } try { Thread.sleep(30000); } catch (Exception e3) { } } for (int x = 0; x < monitorlist.size(); x++) { if (monitorlist.get(x).getThisThread() != null) { try { monitorlist.get(x).getThisThread().join(); } catch (Exception e) { } } } if (acceptor != null) { while (acceptor.isActive() || !acceptor.isDisposed()) { try { Thread.sleep(1000); } catch (Exception e) { } } } if (statusacceptor != null) { while (statusacceptor.isActive() || !statusacceptor.isDisposed()) { try { Thread.sleep(1000); } catch (Exception e) { } } } System.out.println("Main thread has reached end, reloading..."); /* try { Thread.sleep(9999999); } catch (Exception e) { e.printStackTrace(); } */ } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); ResultSet rs = null; try { // SET UP Context environment, to look for Data Pooling Resource Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB"); Connection dbcon = ds.getConnection(); // ########### SEARCH INPUT PARAMETERS, EXECUTE search // ##################################################### Vector<String> params = new Vector<String>(); params.add(request.getParameter("fname")); params.add(request.getParameter("lname")); params.add(request.getParameter("title")); params.add(request.getParameter("year")); params.add(request.getParameter("director")); List<Movie> movies = new ArrayList<Movie>(); movies = SQLServices.getMovies(params.toArray(new String[params.size()]), dbcon); // ########## SET DEFAULT SESSION() PARAMETERS #################################### request.getSession().removeAttribute("movies"); request.getSession().removeAttribute("linkedListMovies"); request.getSession().removeAttribute("hasPaged"); request.getSession().setAttribute("hasPaged", "no"); request.getSession().setAttribute("movies", movies); request.getSession().setAttribute("currentIndex", "0"); request.getSession().setAttribute("defaultN", "5"); // ########## IF MOVIES FROM SEARCH NON-EMPTY ########################################### List<String> fields = Movie.fieldNames(); int count = 1; if (!movies.isEmpty()) { request.setAttribute("movies", movies); for (String field : fields) { request.setAttribute("f" + count++, field); } request.getRequestDispatcher("../movieList.jsp").forward(request, response); } else { out.println("<html><head><title>error</title></head>"); out.println("<body><h1>could not find any movies, try your search again.</h1>"); out.println("<p> we are terribly sorry, please go back. </p>"); out.println("<table border>"); out.println("</table>"); } dbcon.close(); } catch (SQLException ex) { while (ex != null) { System.out.println("SQL Exception: " + ex.getMessage()); ex = ex.getNextException(); } } catch (java.lang.Exception ex) { out.println( "<html>" + "<head><title>" + "moviedb: error" + "</title></head>\n<body>" + "<p>SQL error in doGet: " + ex.getMessage() + "</p></body></html>"); return; } out.close(); }
public static void main(String[] args) throws Exception { boolean isInteractive = false; classUrl = MynaInstaller.class.getResource("MynaInstaller.class").toString(); isJar = (classUrl.indexOf("jar") == 0); if (!isJar) { System.err.println("Installer can only be run from inside a Myna distribution war file"); System.exit(1); } Thread.sleep(1000); Console console = System.console(); String response = null; CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption( "c", "context", true, "Webapp context. Must Start with \"/\" Default: " + webctx); options.addOption("h", "help", false, "Displays help."); options.addOption( "w", "webroot", true, "Webroot to use. Will be created if webroot/WEB-INF does not exist. Default: " + webroot); options.addOption( "l", "logfile", true, "Log file to use. Will be created if it does not exist. Default: ./<context>.log"); options.addOption( "s", "servername", true, "Name of this instance. Will also be the name of the init script. Defaults to either \"myna\" or the value of <context> if defined"); // options.addOption( "P", "purpose", true, "Purpose of the Server, such as DEV,PROD,TRAIN, etc. // Defaults to DEV" ); options.addOption("p", "port", true, "HTTP port. Set to 0 to disable HTTP. Default: " + port); options.addOption( "sp", "ssl-port", true, "SSL (HTTPS) port. Set to 0 to disable SSL, Default: 0"); options.addOption( "ks", "keystore", true, "keystore path. Default: <webroot>/WEB-INF/myna/myna_keystore"); options.addOption("ksp", "ks-pass", true, "keystore password. Default: " + ksPass); options.addOption("ksa", "ks-alias", true, "certificate alias. Default: " + ksAlias); modeOptions.add("upgrade"); modeOptions.add("install"); options.addOption( "m", "mode", true, "Mode: one of " + modeOptions.toString() + ". \n" + "\"upgrade\": Upgrades myna installation in webroot and exits. " + "\"install\": Unpacks to webroot, and installs startup files"); options.addOption( "u", "user", true, "User to own and run the Myna installation. Only applies to unix installs. Default: nobody"); HelpFormatter formatter = new HelpFormatter(); String cmdSyntax = "java -jar myna-X.war -m <mode> [options]"; try { CommandLine line = parser.parse(options, args); Option option; if (args.length == 0) { formatter.printHelp(cmdSyntax, options); response = console.readLine("\nContinue with Interactive Install? (y/N)"); if (response.toLowerCase().equals("y")) { isInteractive = true; } else System.exit(1); } // Help if (line.hasOption("help")) { formatter.printHelp(cmdSyntax, options); System.exit(1); } // mode if (line.hasOption("mode")) { mode = line.getOptionValue("mode"); if (!modeOptions.contains(mode)) { System.err.println( "Invalid Arguments. Reason: Mode must be in " + modeOptions.toString()); formatter.printHelp(cmdSyntax, options); System.exit(1); } } else if (isInteractive) { option = options.getOption("mode"); console.printf("\n" + option.getDescription()); do { response = console.readLine("\nEnter " + option.getLongOpt() + "(" + mode + "): "); if (!response.isEmpty()) mode = response; } while (!modeOptions.contains(mode)); } // webroot if (line.hasOption("webroot")) { webroot = line.getOptionValue("webroot"); } else if (isInteractive) { option = options.getOption("webroot"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webroot + "): "); if (!response.isEmpty()) webroot = response; } // port if (line.hasOption("port")) { port = Integer.parseInt(line.getOptionValue("port")); } else if (isInteractive && mode.equals("install")) { option = options.getOption("port"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + port + "): "); if (!response.isEmpty()) port = Integer.parseInt(response); } // context if (line.hasOption("context")) { webctx = line.getOptionValue("context"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("context"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webctx + "): "); if (!response.isEmpty()) webctx = response; } if (!webctx.startsWith("/")) { webctx = "/" + webctx; } // servername (depends on context) if (!webctx.equals("/")) { serverName = webctx.substring(1); } if (line.hasOption("servername")) { serverName = line.getOptionValue("servername"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("servername"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + serverName + "): "); if (!response.isEmpty()) serverName = response; } // user if (line.hasOption("user")) { user = line.getOptionValue("user"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("user"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + user + "): "); if (!response.isEmpty()) user = response; } // logfile logFile = "myna.log"; if (!webctx.equals("/")) { logFile = webctx.substring(1) + ".log"; } if (line.hasOption("logfile")) { logFile = line.getOptionValue("logfile"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("logfile"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "path(" + logFile + "): "); if (!response.isEmpty()) logFile = response; } // ssl-port if (line.hasOption("ssl-port")) { sslPort = Integer.parseInt(line.getOptionValue("ssl-port")); } else if (isInteractive && mode.equals("install")) { option = options.getOption("ssl-port"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + sslPort + "): "); if (!response.isEmpty()) sslPort = Integer.parseInt(response); } // ks-pass if (line.hasOption("ks-pass")) { ksPass = line.getOptionValue("ks-pass"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("ks-pass"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksPass + "): "); if (!response.isEmpty()) ksPass = response; } // ks-alias if (line.hasOption("ks-alias")) { ksAlias = line.getOptionValue("ks-alias"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("ks-alias"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksAlias + "): "); if (!response.isEmpty()) ksAlias = response; } // keystore String appBase = new File(webroot).getCanonicalPath(); if (keystore == null) { keystore = appBase + "/WEB-INF/myna/myna_keystore"; } if (line.hasOption("keystore")) { keystore = line.getOptionValue("keystore"); } else if (isInteractive && mode.equals("install")) { option = options.getOption("keystore"); console.printf("\n" + option.getDescription()); response = console.readLine("\nEnter " + option.getLongOpt() + "(" + keystore + "): "); if (!response.isEmpty()) keystore = response; } javaOpts = line.getArgList(); } catch (ParseException exp) { System.err.println("Invalid Arguments. Reason: " + exp.getMessage()); formatter.printHelp(cmdSyntax, options); System.exit(1); } if (isInteractive) { System.out.println("\nProceeed with the following settings?:\n"); System.out.println("mode = " + mode); System.out.println("webroot = " + webroot); if (mode.equals("install")) { System.out.println("port = " + port); System.out.println("context = " + webctx); System.out.println("servername = " + serverName); System.out.println("user = "******"logfile = " + logFile); System.out.println("ssl-port = " + sslPort); System.out.println("ks-pass = "******"ks-alias = " + ksAlias); System.out.println("keystore = " + keystore); } response = console.readLine("Continue? (Y/n)"); if (response.toLowerCase().equals("n")) System.exit(1); } File wrFile = new File(webroot); webroot = wrFile.toString(); if (mode.equals("install")) { adminPassword = console.readLine("\nCreate an Admin password for this installation: "); } // unpack myna if necessary if (!wrFile.exists() || mode.equals("upgrade") || mode.equals("install")) { upgrade(wrFile); } if (mode.equals("install")) { File propertiesFile = new File(wrFile.toURI().resolve("WEB-INF/classes/general.properties")); FileInputStream propertiesFileIS = new FileInputStream(propertiesFile); Properties generalProperties = new Properties(); generalProperties.load(propertiesFileIS); propertiesFileIS.close(); if (!adminPassword.isEmpty()) { org.jasypt.util.password.StrongPasswordEncryptor cryptTool = new org.jasypt.util.password.StrongPasswordEncryptor(); generalProperties.setProperty("admin_password", cryptTool.encryptPassword(adminPassword)); } generalProperties.setProperty("instance_id", serverName); generalProperties.store( new java.io.FileOutputStream(propertiesFile), "Myna General Properties"); String javaHome = System.getProperty("java.home"); webroot = new File(webroot).getCanonicalPath(); if (serverName.length() == 0) serverName = "myna"; if (java.lang.System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { if (!new File(logFile).isAbsolute()) { logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString(); } File templateFile = new File( wrFile.toURI().resolve("WEB-INF/myna/install/windows/update_myna_service.cmd")); String initScript = FileUtils.readFileToString(templateFile) .replaceAll("\\{webctx\\}", webctx) .replaceAll("\\{server\\}", Matcher.quoteReplacement(serverName)) .replaceAll("\\{webroot\\}", Matcher.quoteReplacement(webroot)) .replaceAll("\\{logfile\\}", Matcher.quoteReplacement(logFile)) .replaceAll("\\{javahome\\}", Matcher.quoteReplacement(javaHome)) .replaceAll("\\{port\\}", new Integer(port).toString()) .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString()) .replaceAll("\\{keystore\\}", Matcher.quoteReplacement(keystore)) .replaceAll("\\{ksPass\\}", Matcher.quoteReplacement(ksPass)) .replaceAll("\\{ksAlias\\}", Matcher.quoteReplacement(ksAlias)); File scriptFile = new File(wrFile.toURI().resolve("WEB-INF/myna/install/update_myna_service.cmd")); FileUtils.writeStringToFile(scriptFile, initScript); // Runtime.getRuntime().exec("cmd /c start " + scriptFile.toString()).waitFor(); System.out.println( "\nInstalled Service 'Myna App Server " + serverName + "' the following settings:\n"); System.out.println( "\nInit script '" + scriptFile + "' created with the following settings:\n"); System.out.println("memory=256MB"); System.out.println("serverName=" + serverName); System.out.println("javaHome=" + javaHome); System.out.println("context=" + webctx); System.out.println("port=" + port); System.out.println("myna_home=" + webroot); System.out.println("logfile=" + logFile); System.out.println("sslPort=" + sslPort); System.out.println("keyStore=" + keystore); System.out.println("ksPass="******"ksAlias=" + ksAlias); System.out.println( "\nEdit and and run the command file in " + scriptFile + " to update this service"); } else { String curUser = java.lang.System.getProperty("user.name"); if (!curUser.equals("root")) { System.out.println("Install mode must be run as root."); System.exit(1); } if (!new File(logFile).isAbsolute()) { logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString(); } File templateFile = new File(wrFile.toURI().resolve("WEB-INF/myna/install/linux/init_script")); String initScript = FileUtils.readFileToString(templateFile) .replaceAll("\\{webctx\\}", webctx) .replaceAll("\\{server\\}", serverName) .replaceAll("\\{user\\}", user) .replaceAll("\\{webroot\\}", webroot) .replaceAll("\\{javahome\\}", javaHome) .replaceAll("\\{logfile\\}", logFile) .replaceAll("\\{port\\}", new Integer(port).toString()) .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString()) .replaceAll("\\{keystore\\}", keystore) .replaceAll("\\{ksPass\\}", ksPass) .replaceAll("\\{ksAlias\\}", ksAlias); File scriptFile = new File(wrFile.toURI().resolve("WEB-INF/myna/install/" + serverName)); FileUtils.writeStringToFile(scriptFile, initScript); if (new File("/etc/init.d").exists()) { exec("chown -R " + user + " " + webroot); exec("chown root " + scriptFile.toString()); exec("chmod 700 " + scriptFile.toString()); exec("cp " + scriptFile.toString() + " /etc/init.d/"); System.out.println( "\nInit script '/etc/init.d/" + serverName + "' created with the following settings:\n"); } else { System.out.println( "\nInit script '" + scriptFile + "' created with the following settings:\n"); } System.out.println("user="******"memory=256MB"); System.out.println("server=" + serverName); System.out.println("context=" + webctx); System.out.println("port=" + port); System.out.println("myna_home=" + webroot); System.out.println("logfile=" + logFile); System.out.println("sslPort=" + sslPort); System.out.println("keyStore=" + keystore); System.out.println("ksPass="******"ksAlias=" + ksAlias); System.out.println("\nEdit this file to customize startup behavior"); } } }
public synchronized void addClient(ClientInfo aClientInfo) { mClients.add(aClientInfo); }
public void actionPerformed(ActionEvent e) { SpinnerNumberModel m = ((SpinnerNumberModel) daysnr.getModel()); int days = m.getNumber().intValue(); String location = ((JTextField) loc).getText(); java.util.List<PointOfInterest> points = parent.textFieldPoints(location); if (!points.isEmpty()) { double latitude = points.get(0).getLatlon().latitude.getDegrees(), longitude = points.get(0).getLatlon().longitude.getDegrees(); // we want only the firs two decimals latitude = ((double) ((long) (latitude * 100))) / 100; longitude = ((double) ((long) (latitude * 100))) / 100; String APIKey = "65ea00ff33143650113112"; String address = "http://free.worldweatheronline.com/feed/weather.ashx?" + "key=" + APIKey + "&num_of_days=" + days + "&q=" + latitude + "," + longitude + "&format=json&cc=no"; try { URL link = new URL(address); URLConnection yc = link.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); Vector<WeatherElements> elem = new Vector<WeatherElements>(); String jsonFile = in.readLine(); int i1 = 0, i2 = 0; for (int i = 0; i < days; i++) { i1 = jsonFile.indexOf("\"date\"", i2) + 9; i2 = jsonFile.indexOf("\"", i1); String date = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"precipMM\"", i2) + 13; i2 = jsonFile.indexOf("\"", i1); String rain = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"tempMaxC\"", i2) + 13; i2 = jsonFile.indexOf("\"", i1); String tempMax = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"tempMinC\"", i2) + 13; i2 = jsonFile.indexOf("\"", i1); String tempMin = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"value\"", i2) + 10; i2 = jsonFile.indexOf("\"", i1); String weatherStatus = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"value\"", i2) + 10; i2 = jsonFile.indexOf("\"", i1); String imgLink = jsonFile.substring(i1, i2); imgLink = imgLink.replace("\\", ""); i2++; i1 = jsonFile.indexOf("\"winddirDegree\"", i2) + 18; i2 = jsonFile.indexOf("\"", i1); String windDirDegree = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"winddirection\"", i2) + 18; i2 = jsonFile.indexOf("\"", i1); String windDir = jsonFile.substring(i1, i2); i2++; i1 = jsonFile.indexOf("\"windspeedKmph\"", i2) + 18; i2 = jsonFile.indexOf("\"", i1); String windSpeed = jsonFile.substring(i1, i2); i2++; WeatherElements o = new WeatherElements( date, rain, tempMax, tempMin, weatherStatus, imgLink, windDirDegree, windDir, windSpeed); elem.add(o); } weatherIcon.setVisible(true); dateout.setText(elem.elementAt(0).date); weatherIcon.setText("<html><img src=\"" + elem.elementAt(0).imgLink + "\" /></html>"); weatherstatus.setText("<html><h1>" + elem.elementAt(0).weatherStatus + "</h1></html>"); temperature.setText( "<html>Temperatures:<br />Temp min: " + elem.elementAt(0).tempMin + "°C<br />Temp max: " + elem.elementAt(0).tempMax + "°C</html>"); rain.setText("Rain: " + elem.elementAt(0).rain + " mm"); wind.setText( "<html>Wind: <br />" + "<img src=\"http://www.worldweatheronline.com" + "/App_Themes/Default/images/wind/" + elem.elementAt(0).windDir + ".png\" /><br />" + "Wind speed: " + elem.elementAt(0).windSpeed + "Km/h<br />" + elem.elementAt(0).windDir + "(" + elem.elementAt(0).windDirDegree + "°)</html>"); buttons.removeAll(); pageNum.removeAll(); buttons.updateUI(); pageNum.updateUI(); JButton previous = new JButton("Previous"); previous.setEnabled(false); previous.setName("prev"); JButton next = new JButton("Next"); next.setName("next"); if (days == 1) { next.setEnabled(false); } JTextField current = new JTextField("1", 3); current.setEditable(false); JTextField maxNum = new JTextField("" + elem.size(), 3); maxNum.setEditable(false); pageNum.add(current); pageNum.add(maxNum); previous.addActionListener( new WeatherButtonsActionListener( previous, next, weatherIcon, dateout, weatherstatus, temperature, rain, wind, elem, current)); next.addActionListener( new WeatherButtonsActionListener( previous, next, weatherIcon, dateout, weatherstatus, temperature, rain, wind, elem, current)); buttons.add(next); buttons.add(previous); JButton genHTML = new JButton("Generate HTML"); genHTML.addActionListener(new genHTMLWeatherReport(parent, elem)); buttons.add(genHTML); } catch (Exception ex) { parent.standardDialogBox("Fetching data error", "Somethnig goes wrong with the connection"); } } else { parent.standardDialogBox("Incorrect input", "Input is incorrect!"); } }
private void mapAndTocForFile(File f, File path, String underscore) { // we get the single name of the file and the urlname int under_index2 = f.getName().indexOf("_"); int point_index2 = f.getName().indexOf("."); String named = f.getName().substring(under_index2 + 1, point_index2); String tmp = path.getAbsolutePath() + "Main_pages/fr/"; String url_name = f.getPath().replace("\\", "/").substring(tmp.length()); String targetName = url_name.substring(0, url_name.lastIndexOf(".html")); // now we will add into the map and the toc print.println("<mapID target=\"" + targetName + "\" url=\"pages/" + url_name + "\"/>"); File dir_associated = new File(f.getParent(), named); if ((dir_associated.exists() && dir_associated.isDirectory()) || named.equals("objects")) { print2.println( "<tocitem text=\"" + getTitle(f) + "\" target=\"" + targetName + "\" image=\"tamicon\">"); if (dir_associated.exists()) { // Apres on fait pareil pour tous les sous fichiers File[] sub_files = dir_associated.listFiles(); for (int i = 0; i < sub_files.length; i++) { if (!sub_files[i].getName().equals("CVS") && sub_files[i].isFile()) { if (sub_files[i].getName().endsWith(".html")) mapAndTocForFile(sub_files[i], path, underscore); else { try { copyFile( sub_files[i], new File(path, "pages/" + named + "/" + sub_files[i].getName())); } catch (IOException e) { LOG.error("Error while copying normal files in help " + e); } } } } } if (named.equals("objects")) { // Specialement pour les objets on les rajoute tous File objects_dir = new File( Configuration.instance() .getTangaraPath() .getParentFile() .getAbsolutePath() .replace("\\", "/") + "/objects/"); File[] listfiles = objects_dir.listFiles(); Vector<String> list_names = new Vector<String>(); HashMap<String, String> map = new HashMap<String, String>(); for (int i = 0; i < listfiles.length; i++) { try { if (listfiles[i].getName().endsWith(".jar")) { int point_index = listfiles[i].getName().lastIndexOf("."); String name = listfiles[i].getName().substring(0, point_index); // Copy the pages in the right directory File object_dir = new File(path, "pages/" + name); object_dir.mkdir(); File object_ressource = new File( Configuration.instance() .getTangaraPath() .getParentFile() .getAbsolutePath() .replace("\\", "/") + "/objects/resources/" + name + "/Help"); if (object_ressource.exists()) { File[] list_html_object = object_ressource.listFiles(); for (int e = 0; e < list_html_object.length; e++) { if (list_html_object[e].getName().endsWith(".html")) { int under_index = list_html_object[e].getName().lastIndexOf("_"); if (underscore.equals("") && under_index == -1) copyFile( list_html_object[e], new File(path, "pages/" + name + "/" + list_html_object[e].getName())); else if (!underscore.equals("")) { if (list_html_object[e].getName().contains(underscore)) copyFile( list_html_object[e], new File(path, "pages/" + name + "/" + list_html_object[e].getName())); } } else copyFile( list_html_object[e], new File(path, "pages/" + name + "/" + list_html_object[e].getName())); } // Gets the name of the object in the selected language String name_lang = null; if (underscore.equals("")) name_lang = name; else { name_lang = getLangName(listfiles[i]); } if (name_lang != null) { list_names.add(name_lang); map.put(name_lang, name); // Add to the map file print.println( "<mapID target=\"" + name + "\" url=\"pages/" + name + "/index" + underscore + ".html\" />"); } } } } catch (Exception e2) { LOG.error("Error2 getHelp " + e2); } } // Add to the tam file Collections.sort(list_names); for (String s : list_names) { print2.println( "<tocitem text=\"" + s + "\" target=\"" + map.get(s) + "\" image=\"fileicon\" />"); } } print2.println("</tocitem>"); } else { // pas de sous fichiers print2.println( "<tocitem text=\"" + getTitle(f) + "\" target=\"" + targetName + "\" image=\"fileicon\"/>"); } File parent = new File(path, "pages/" + url_name.substring(0, url_name.lastIndexOf(named) - 3)); if (!parent.exists()) parent.mkdirs(); File in_pages = new File(path, "pages/" + url_name); try { in_pages.createNewFile(); copyFile(f, in_pages); } catch (IOException e3) { LOG.error("Error 3 getHelp " + e3 + " " + f.getName()); } }