Example usage for java.util Date setTime

List of usage examples for java.util Date setTime

Introduction

In this page you can find the example usage for java.util Date setTime.

Prototype

public void setTime(long time) 

Source Link

Document

Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

Usage

From source file:com.handywedge.binarystore.store.aws.BinaryStoreManagerImpl.java

private URL getPresignedUrl(AmazonS3 s3client, String buckrtName, String key) {
    logger.info("getPresignedUrl start.");

    java.util.Date expiration = new java.util.Date();
    long milliSeconds = expiration.getTime();
    milliSeconds += Long.parseLong(PropertiesUtil.get("aws.presignedurl.expiration"));
    expiration.setTime(milliSeconds);

    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(buckrtName, key);
    generatePresignedUrlRequest.setMethod(HttpMethod.GET);
    generatePresignedUrlRequest.setExpiration(expiration);

    URL PresignedUrl = s3client.generatePresignedUrl(generatePresignedUrlRequest);

    logger.info("getPresignedUrl: end. url={}", PresignedUrl);
    return PresignedUrl;
}

From source file:org.nuxeo.ecm.core.storage.sql.S3BinaryManager.java

@Override
protected URI getRemoteUri(String digest, ManagedBlob blob, HttpServletRequest servletRequest)
        throws IOException {
    String key = bucketNamePrefix + digest;
    Date expiration = new Date();
    expiration.setTime(expiration.getTime() + directDownloadExpire * 1000);
    GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);
    request.addRequestParameter("response-content-type", getContentTypeHeader(blob));
    request.addRequestParameter("response-content-disposition", getContentDispositionHeader(blob, null));
    request.setExpiration(expiration);/*from  w  w w  .  j a  va  2  s. c  o m*/
    URL url = amazonS3.generatePresignedUrl(request);
    try {
        return url.toURI();
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

From source file:org.openmrs.web.servlet.ShowGraphServlet.java

/**
 * Get the FromDate object from the given string that is the time in milliseconds. If
 * dateFromRequest is null, return 1 year ago from today.
 *
 * @param dateFromRequest String that was passed into this servlet
 * @return Date parsed from dateFromRequest string
 * @should return one year previous to today if parameter is null
 * @should return same date as given string parameter
 *//*from   w w w .  ja  v a 2  s. c  o m*/
protected Date getFromDate(String dateFromRequest) {
    Date returnedDate = new Date(); // default to right now

    if (dateFromRequest != null && dateFromRequest.length() > 0) {
        returnedDate.setTime(Long.parseLong(dateFromRequest));
    } else {
        Calendar cal = Calendar.getInstance();
        cal.setTime(returnedDate);
        cal.set(cal.get(Calendar.YEAR) - 1, cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        returnedDate = cal.getTime();
    }

    return returnedDate;
}

From source file:org.apache.flink.runtime.io.network.netty.NettyConnectionManager.java

@Override
public void start(ChannelManager channelManager) throws IOException {
    LOG.info(String.format("Starting with %d incoming and %d outgoing connection threads.", numInThreads,
            numOutThreads));//from  w  w  w  .  j  a  v  a 2  s.co m
    LOG.info(String.format("Setting low water mark to %d and high water mark to %d bytes.", lowWaterMark,
            highWaterMark));
    LOG.info(String.format("Close channels after idle for %d ms.", closeAfterIdleForMs));

    final BufferProviderBroker bufferProviderBroker = channelManager;
    final EnvelopeDispatcher envelopeDispatcher = channelManager;

    int numHeapArenas = 0;
    int numDirectArenas = numInThreads + numOutThreads;
    int pageSize = bufferSize << 1;
    int chunkSize = 16 << 20; // 16 MB

    // shift pageSize maxOrder times to get to chunkSize
    int maxOrder = (int) (Math.log(chunkSize / pageSize) / Math.log(2));

    PooledByteBufAllocator pooledByteBufAllocator = new PooledByteBufAllocator(true, numHeapArenas,
            numDirectArenas, pageSize, maxOrder);

    String msg = String.format(
            "Instantiated PooledByteBufAllocator with direct arenas: %d, heap arenas: %d, "
                    + "page size (bytes): %d, chunk size (bytes): %d.",
            numDirectArenas, numHeapArenas, pageSize, (pageSize << maxOrder));
    LOG.info(msg);

    // --------------------------------------------------------------------
    // server bootstrap (incoming connections)
    // --------------------------------------------------------------------
    in = new ServerBootstrap();
    in.group(new NioEventLoopGroup(numInThreads)).channel(NioServerSocketChannel.class)
            .localAddress(bindAddress, bindPort).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new InboundEnvelopeDecoder(bufferProviderBroker))
                            .addLast(new InboundEnvelopeDispatcher(envelopeDispatcher));
                }
            }).option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(pageSize))
            .option(ChannelOption.ALLOCATOR, pooledByteBufAllocator);

    // --------------------------------------------------------------------
    // client bootstrap (outgoing connections)
    // --------------------------------------------------------------------
    out = new Bootstrap();
    out.group(new NioEventLoopGroup(numOutThreads)).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new OutboundEnvelopeEncoder());
                }
            }).option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, lowWaterMark)
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, highWaterMark)
            .option(ChannelOption.ALLOCATOR, pooledByteBufAllocator).option(ChannelOption.TCP_NODELAY, false)
            .option(ChannelOption.SO_KEEPALIVE, true);

    try {
        in.bind().sync();
    } catch (InterruptedException e) {
        throw new IOException(e);
    }

    if (LOG.isDebugEnabled()) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Date date = new Date();

                while (true) {
                    try {
                        Thread.sleep(DEBUG_PRINT_QUEUED_ENVELOPES_EVERY_MS);

                        date.setTime(System.currentTimeMillis());

                        System.out.println(date);
                        System.out.println(getNonZeroNumQueuedEnvelopes());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}

From source file:UserInterface.TMAnalystRole.TMAnaylstWorkAreaJPanel.java

private void generateGraph(Train selectedTrain) {

    ArrayList<TrainOffered> selectedTrainOfferedListWEEKDAYS = new ArrayList<>();
    ArrayList<TrainOffered> selectedTrainOfferedListWEEKENDS = new ArrayList<>();

    int days = (int) spnrRecord.getValue();
    Date today = new Date();
    Date olderThanToday = new Date();
    olderThanToday.setTime(today.getTime() + (long) (-days) * 1000 * 60 * 60 * 24);
    long todayDate = (today.getTime()) / (1000 * 60 * 60 * 24);
    long olderDate = (olderThanToday.getTime()) / (1000 * 60 * 60 * 24);

    for (TrainOffered selectedTrainOffered : enterprise.getTrainsOfferedHistory().getTrainsOffered()) {
        if (selectedTrainOffered.getTrain().equals(selectedTrain)) {
            long selectedDate = (selectedTrainOffered.getDayOffered().getTime()) / (1000 * 60 * 60 * 24);
            if (selectedDate >= olderDate && selectedDate <= todayDate) {
                Calendar date = Calendar.getInstance();
                date.setTime(selectedTrainOffered.getDayOffered());
                if ((date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
                        || ((date.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY))) {
                    if (!selectedTrainOfferedListWEEKENDS.contains(selectedTrainOffered)) {
                        selectedTrainOfferedListWEEKENDS.add(selectedTrainOffered);
                    }/*  w w  w  .  j a  v a 2  s .  co  m*/
                } else {
                    if (!selectedTrainOfferedListWEEKDAYS.contains(selectedTrainOffered)) {
                        selectedTrainOfferedListWEEKDAYS.add(selectedTrainOffered);
                    }
                }
            }
        }
    }

    Map<TimeSlot.TimeSlotRange, Integer> weekendData = new HashMap<TimeSlot.TimeSlotRange, Integer>();

    for (TrainOffered selectedTrainOfferedOnWeekend : selectedTrainOfferedListWEEKENDS) {
        for (TrainStatus rt : selectedTrainOfferedOnWeekend.getRunningTrains()) {
            if (weekendData.containsKey(rt.getTrainSchedule().getTimeSlot())) {
                Integer previousValue = weekendData.get(rt.getTrainSchedule().getTimeSlot());
                weekendData.put(rt.getTrainSchedule().getTimeSlot(), previousValue + rt.getRunningCapacity());
            } else {
                weekendData.put(rt.getTrainSchedule().getTimeSlot(), rt.getRunningCapacity());
            }
        }
    }

    ArrayList<Integer> sortedWeekendData = new ArrayList<>();
    if (weekendData.size() > 0) {
        for (TimeSlot.TimeSlotRange tsr : TimeSlot.TimeSlotRange.values()) {
            sortedWeekendData.add(weekendData.get(tsr));
        }
    }

    Map<TimeSlot.TimeSlotRange, Integer> weekdayData = new HashMap<>();

    for (TrainOffered selectedTrainOfferedOnWeekDays : selectedTrainOfferedListWEEKDAYS) {
        for (TrainStatus rt : selectedTrainOfferedOnWeekDays.getRunningTrains()) {
            if (weekdayData.containsKey(rt.getTrainSchedule().getTimeSlot())) {
                Integer previousValue = weekdayData.get(rt.getTrainSchedule().getTimeSlot());
                weekdayData.put(rt.getTrainSchedule().getTimeSlot(), previousValue + rt.getRunningCapacity());
            } else {
                weekdayData.put(rt.getTrainSchedule().getTimeSlot(), rt.getRunningCapacity());
            }
        }
    }

    ArrayList<Integer> sortedWeekDayDataList = new ArrayList<>();
    if (weekdayData.size() > 0) {
        for (TimeSlot.TimeSlotRange tsr : TimeSlot.TimeSlotRange.values()) {
            sortedWeekDayDataList.add(weekdayData.get(tsr));
        }
    }

    CategoryDataset dataset;
    String series1 = "Weekdays";
    String series2 = "Weekends";
    String series3 = "Maximum Capcity";

    DefaultCategoryDataset dataset1 = new DefaultCategoryDataset();

    for (int i = 0; i < sortedWeekendData.size(); i++) {
        dataset1.addValue(Math.round(sortedWeekendData.get(i) / selectedTrainOfferedListWEEKENDS.size()),
                series2, TimeSlot.TimeSlotRange.values()[i].getValue());
    }

    for (int i = 0; i < sortedWeekDayDataList.size(); i++) {
        // System.out.println("Key = " + entry.getKey().getValue() + ", Value = " + Math.round(entry.getValue()/selectedTrainOfferedListWEEKENDS.size()));
        dataset1.addValue(Math.round(sortedWeekDayDataList.get(i) / selectedTrainOfferedListWEEKDAYS.size()),
                series1, TimeSlot.TimeSlotRange.values()[i].getValue());
    }

    for (int i = 0; i < 15; i++) {
        // System.out.println("Key = " + entry.getKey().getValue() + ", Value = " + Math.round(entry.getValue()/selectedTrainOfferedListWEEKENDS.size()));
        dataset1.addValue(selectedTrain.getTrainCapacity(), series3,
                TimeSlot.TimeSlotRange.values()[i].getValue());
    }

    dataset = dataset1;

    final JFreeChart chart = ChartFactory.createLineChart(
            "Average Congestion of Train : " + selectedTrain.getTrainName(), // chart title
            "Time Slot", // domain axis label
            "Congestion Level", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    chart.setBackgroundPaint(Color.white);

    final CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.white);

    ChartFrame chartPanel = new ChartFrame("Line Chart of Train", chart);
    chartPanel.setSize(this.getWidth(), this.getHeight() + 200);
    chartPanel.setVisible(true);

}

From source file:TimeSpan.java

/**
 * Adds the duration of this time span to the provided {@code Date}
 * instance, moving it forward in time.// ww  w .j  a v  a 2  s  .  com
 *
 * @param d the date whose value will be moved forward by the duration of
 *        this time span
 */
public void addTo(Date d) {
    Calendar c = Calendar.getInstance();
    c.setTime(d);
    addTo(c);
    d.setTime(c.getTime().getTime());
}

From source file:com.springrts.springls.statistics.Statistics.java

/**
 * This will create "statistics.dat" file which will contain all records
 * from the last 7 days.//  ww  w .j  a  v  a 2 s  . c o  m
 */
private boolean createAggregateFile() {

    String fileName = STATISTICS_FOLDER + "statistics.dat";

    Writer outF = null;
    Writer out = null;
    try {
        // overwrite if it exists, or create new one
        outF = new FileWriter(fileName, false);
        out = new BufferedWriter(outF);
        String line;

        SimpleDateFormat formatter = new SimpleDateFormat("ddMMyy");
        Date today = today();
        long msPerDay = 1000 * 60 * 60 * 24;
        // get file names for last 7 days (that is today + previous 6 days)
        for (int i = 7; i > 0; i--) {
            Date day = new Date();
            day.setTime(today.getTime() - (((long) i - 1) * msPerDay));
            String dayStr = formatter.format(day);
            File fileDay = new File(STATISTICS_FOLDER + formatter.format(dayStr) + ".dat");
            Reader inF = null;
            BufferedReader in = null;
            try {
                inF = new FileReader(fileDay);
                in = new BufferedReader(inF);
                LOG.trace("Found stats: <{}>", fileDay.getAbsolutePath());
                while ((line = in.readLine()) != null) {
                    out.write(dayStr);
                    out.write(' ');
                    out.write(line);
                    out.write(Misc.EOL);
                }
            } catch (IOException ex) {
                LOG.trace("Skipped stats: <" + fileDay.getAbsolutePath() + ">", ex);
            } finally {
                if (in != null) {
                    in.close();
                } else if (inF != null) {
                    inF.close();
                }
            }
        }
    } catch (IOException ex) {
        LOG.error("Unable to access file <" + fileName + ">. Skipping ...", ex);
        return false;
    } finally {
        try {
            if (out != null) {
                out.close();
            } else if (outF != null) {
                outF.close();
            }
        } catch (IOException ex) {
            LOG.trace("Failed closing aggregate statistics file-writer for" + " file: " + fileName, ex);
        }
    }

    return true;
}

From source file:org.apache.unomi.web.ContextServlet.java

@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    final Date timestamp = new Date();
    if (request.getParameter("timestamp") != null) {
        timestamp.setTime(Long.parseLong(request.getParameter("timestamp")));
    }/*from  w w  w  . jav a 2  s  . c o m*/
    // first we must retrieve the context for the current visitor, and build a Javascript object to attach to the
    // script output.
    String profileId;

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String httpMethod = httpServletRequest.getMethod();
    //        logger.debug(HttpUtils.dumpRequestInfo(httpServletRequest));

    // set up CORS headers as soon as possible so that errors are not misconstrued on the client for CORS errors
    HttpUtils.setupCORSHeaders(httpServletRequest, response);

    if ("options".equals(httpMethod.toLowerCase())) {
        response.flushBuffer();
        return;
    }

    Profile profile = null;

    String cookieProfileId = null;
    Cookie[] cookies = httpServletRequest.getCookies();
    for (Cookie cookie : cookies) {
        if (profileIdCookieName.equals(cookie.getName())) {
            cookieProfileId = cookie.getValue();
        }
    }

    Session session = null;

    String personaId = request.getParameter("personaId");
    if (personaId != null) {
        PersonaWithSessions personaWithSessions = profileService.loadPersonaWithSessions(personaId);
        if (personaWithSessions == null) {
            logger.error("Couldn't find persona with id=" + personaId);
            profile = null;
        } else {
            profile = personaWithSessions.getPersona();
            session = personaWithSessions.getLastSession();
        }
    }

    String sessionId = request.getParameter("sessionId");

    if (cookieProfileId == null && sessionId == null && personaId == null) {
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    boolean profileCreated = false;

    ContextRequest contextRequest = null;
    String scope = null;
    String stringPayload = HttpUtils.getPayload(httpServletRequest);
    if (stringPayload != null) {
        ObjectMapper mapper = CustomObjectMapper.getObjectMapper();
        JsonFactory factory = mapper.getFactory();
        try {
            contextRequest = mapper.readValue(factory.createParser(stringPayload), ContextRequest.class);
        } catch (Exception e) {
            logger.error("Cannot read payload " + stringPayload, e);
            return;
        }
        scope = contextRequest.getSource().getScope();
    }

    int changes = EventService.NO_CHANGE;

    if (profile == null) {
        if (sessionId != null) {
            session = profileService.loadSession(sessionId, timestamp);
            if (session != null) {
                profileId = session.getProfileId();
                profile = profileService.load(profileId);
                profile = checkMergedProfile(response, profile, session);
            }
        }
        if (profile == null) {
            // profile not stored in session
            if (cookieProfileId == null) {
                // no profileId cookie was found, we generate a new one and create the profile in the profile service
                profile = createNewProfile(null, response, timestamp);
                profileCreated = true;
            } else {
                profile = profileService.load(cookieProfileId);
                if (profile == null) {
                    // this can happen if we have an old cookie but have reset the server,
                    // or if we merged the profiles and somehow this cookie didn't get updated.
                    profile = createNewProfile(null, response, timestamp);
                    profileCreated = true;
                    HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain);
                } else {
                    profile = checkMergedProfile(response, profile, session);
                }
            }
        } else if ((cookieProfileId == null || !cookieProfileId.equals(profile.getItemId()))
                && !profile.isAnonymousProfile()) {
            // profile if stored in session but not in cookie
            HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain);
        }
        // associate profile with session
        if (sessionId != null && session == null) {
            session = new Session(sessionId, profile, timestamp, scope);
            changes |= EventService.SESSION_UPDATED;
            Event event = new Event("sessionCreated", session, profile, scope, null, session, timestamp);

            event.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
            event.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);
            logger.debug("Received event " + event.getEventType() + " for profile=" + profile.getItemId()
                    + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp="
                    + timestamp);
            changes |= eventService.send(event);
        }
    }

    if (profileCreated) {
        changes |= EventService.PROFILE_UPDATED;

        Event profileUpdated = new Event("profileUpdated", session, profile, scope, null, profile, timestamp);
        profileUpdated.setPersistent(false);
        profileUpdated.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
        profileUpdated.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);

        logger.debug("Received event {} for profile={} {} target={} timestamp={}",
                profileUpdated.getEventType(), profile.getItemId(),
                session != null ? " session=" + session.getItemId() : "", profileUpdated.getTarget(),
                timestamp);
        changes |= eventService.send(profileUpdated);
    }

    ContextResponse data = new ContextResponse();
    data.setProfileId(profile.isAnonymousProfile() ? cookieProfileId : profile.getItemId());

    if (privacyService.isRequireAnonymousBrowsing(profile.getItemId())) {
        profile = privacyService.getAnonymousProfile();
        session.setProfile(profile);
        changes = EventService.SESSION_UPDATED;
    }

    if (contextRequest != null) {
        changes |= handleRequest(contextRequest, profile, session, data, request, response, timestamp);
    }

    if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED && profile != null) {
        profileService.save(profile);
    }
    if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED && session != null) {
        profileService.saveSession(session);
    }

    String extension = httpServletRequest.getRequestURI()
            .substring(httpServletRequest.getRequestURI().lastIndexOf(".") + 1);
    boolean noScript = "json".equals(extension);
    String contextAsJSONString = CustomObjectMapper.getObjectMapper().writeValueAsString(data);
    Writer responseWriter;
    if (noScript) {
        response.setCharacterEncoding("UTF-8");
        responseWriter = response.getWriter();
        response.setContentType("application/json");
        IOUtils.write(contextAsJSONString, responseWriter);
    } else {
        responseWriter = response.getWriter();
        responseWriter.append("window.digitalData = window.digitalData || {};\n").append("var cxs = ")
                .append(contextAsJSONString).append(";\n");

        // now we copy the base script source code
        InputStream baseScriptStream = getServletContext().getResourceAsStream(
                profile instanceof Persona ? IMPERSONATE_BASE_SCRIPT_LOCATION : BASE_SCRIPT_LOCATION);
        IOUtils.copy(baseScriptStream, responseWriter);
    }

    responseWriter.flush();
}

From source file:tools.xor.logic.DefaultCloneDataType.java

public void cloneDataType() {

    // create person
    Technician owner = new Technician();
    owner.setName("TOMMY_HILFIGHER");
    owner.setDisplayName("Tommy Hilfigher");
    owner.setDescription("A famous fashion designer");
    owner.setUserName("thilf");
    owner.setSkill("fashion design");
    owner = (Technician) aggregateService.create(owner, new Settings());
    Person person = (Person) aggregateService.read(owner, new Settings());

    // Create Task
    Task task = new Task();
    task.setName("CREATE_GOWN");
    task.setDisplayName("Create wedding gown");
    task.setDescription("Design a wedding gown");
    task.setAssignedTo(person);//  w ww  .  j av  a 2  s  .  c o  m
    Date finish = new Date();
    task.setScheduledFinish(finish);
    task = (Task) aggregateService.create(task, getSettings());
    task = (Task) aggregateService.read(task, getSettings());

    // Ensure task is persisted
    assert (task.getId() != null);
    assert (task.getAssignedTo() != null);
    assert (task.getAssignedTo().getId() != null);

    // ensure change the date in the from instance does not affect the date object in the to instance
    // We need to make sure a clone is being made and the same object is not referenced
    finish.setTime(finish.getTime() + TimeUnit.DAYS.toMillis(1));
    assert (finish.getTime() != task.getScheduledFinish().getTime());
}

From source file:it.infn.ct.downtime.Downtime.java

private void sendHTMLEmail(String TO, String FROM, String SMTP_HOST, File file) {

    String[] downtime_text = new String[4];

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);

    // Get the default Session object.
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    try {//from www.  j a  v  a 2s  . c  o  m
        //Get Document Builder
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        //Build Document
        Document document = builder.parse(file);

        //Normalize the XML Structure; It's just too important !!
        document.getDocumentElement().normalize();

        //Here comes the root node
        Element root = document.getDocumentElement();
        NodeList List = document.getElementsByTagName("DOWNTIME");

        for (int i = 0; i < List.getLength(); i++) {
            Node node = List.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) node;

                // Downtime period
                downtime_text[0] = "SCHEDULED Downtime period <br/>";
                downtime_text[0] += "Start of downtime \t[UCT]: "
                        + eElement.getElementsByTagName("FORMATED_START_DATE").item(0).getTextContent()
                        + "<br/>";
                downtime_text[0] += "End  of downtime \t[UCT]: "
                        + eElement.getElementsByTagName("FORMATED_END_DATE").item(0).getTextContent()
                        + "<br/><br/>";

                // Entities in downtime
                downtime_text[1] = "<b><u>Entities in downtime:</u></b><br/>";
                downtime_text[1] += "Server Host: "
                        + eElement.getElementsByTagName("HOSTED_BY").item(0).getTextContent() + "<br/><br/>";
                for (int k = 0; k < eElement.getElementsByTagName("SERVICE").getLength(); k++) {
                    downtime_text[1] += "Nodes: "
                            + eElement.getElementsByTagName("HOSTNAME").item(k).getTextContent() + "<br/>";
                    downtime_text[1] += "Service Type: "
                            + eElement.getElementsByTagName("SERVICE_TYPE").item(k).getTextContent() + "<br/>";
                    downtime_text[1] += "Hosted service(s): "
                            + eElement.getElementsByTagName("HOSTNAME").item(k).getTextContent() + "<br/><br/>";
                }

                // Description
                downtime_text[2] = "<b><u>Description:</u></b><br/>";
                downtime_text[2] += eElement.getElementsByTagName("DESCRIPTION").item(0).getTextContent()
                        + "<br/>";
                downtime_text[2] += "More details are available in this <a href="
                        + eElement.getElementsByTagName("GOCDB_PORTAL_URL").item(0).getTextContent()
                        + "> link</a>" + "<br/><br/>";

                // Severity
                downtime_text[3] = "<b><u>Severity:</u></b> ";
                downtime_text[3] += eElement.getElementsByTagName("SEVERITY").item(0).getTextContent()
                        + "<br/><br/>";

                // Sending notification                
                // Create a default MimeMessage object.
                javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);

                // Set From: header field of the header.
                message.setFrom(new javax.mail.internet.InternetAddress(FROM));

                // Set To: header field of the header.
                message.addRecipient(javax.mail.Message.RecipientType.TO,
                        new javax.mail.internet.InternetAddress(TO));
                //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM));

                // Set Subject: header field
                message.setSubject(" [EGI DOWNTIME] ANNOUNCEMENT ");

                Date currentDate = new Date();
                currentDate.setTime(currentDate.getTime());

                // Send the actual HTML message, as big as you like
                message.setContent("<br/><H4>"
                        + "<img src=\"http://scilla.man.poznan.pl:8080/confluence/download/attachments/5505438/egi_logo.png\" width=\"100\">"
                        + "</H4>" + "Long Tail of Science (LToS) services in downtime<br/><br/>"
                        + downtime_text[0] + downtime_text[1] + downtime_text[2] + downtime_text[3]
                        + "<b><u>TimeStamp:</u></b><br/>" + currentDate + "<br/><br/>"
                        + "<b><u>Disclaimer:</u></b><br/>"
                        + "<i>This is an automatic message sent by the LToS Science Gateway based on Liferay technology."
                        + "<br/><br/>", "text/html");

                // Send notification to the user
                javax.mail.Transport.send(message);
            }
        }
    } catch (MessagingException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    }
}