Java tutorial
/******************************************************************************* * Copyright (C) 2013, University of Patras, Greece* * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package eu.xipi.bro4xipi; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.Random; import java.util.Vector; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.GenericPortlet; import javax.portlet.PortletException; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import javax.portlet.PortletRequestDispatcher; import javax.portlet.PortletURL; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.liferay.portal.kernel.servlet.SessionErrors; import com.liferay.portal.kernel.servlet.SessionMessages; import eu.xipi.bro4xipi.brokermodel.BrokerJpaController; import eu.xipi.bro4xipi.resourceadvisor.AdvicedOffer; import eu.xipi.bro4xipi.resourceadvisor.OfferedPlan; import eu.xipi.bro4xipi.resourceadvisor.ResourceAdvisor; import eu.xipi.bro4xipi.transformation.XiPiBroker; import gr.upatras.ece.nam.broker.Broker; import gr.upatras.ece.nam.broker.model.availabilitycontract.Availability; import gr.upatras.ece.nam.broker.model.availabilitycontract.Cost; import gr.upatras.ece.nam.broker.model.availabilitycontract.ResourceServiceContract; import gr.upatras.ece.nam.broker.model.federationscenarios.ServiceRequest; import gr.upatras.ece.nam.broker.model.providersite.DomainManager; import gr.upatras.ece.nam.broker.model.providersite.Site; import gr.upatras.ece.nam.broker.model.resources.OfferedResource; import gr.upatras.ece.nam.broker.model.services.OfferedService; import gr.upatras.ece.nam.broker.model.users.Account; import gr.upatras.ece.nam.broker.model.users.ResourcesProvider; /** * * the main class of the portlet * @author ctranoris * */ public class Bro4xipi extends GenericPortlet { // @BeanReference(name = "eu.xipi.bro4xipi.brokermodel.BrokerJpaController") protected enum portletViewstatusEnum { PVDEFINITION, PVPLANS, PVSELECTEDPLAN }; protected portletViewstatusEnum portletViewstatus = portletViewstatusEnum.PVDEFINITION; private BrokerJpaController brokerJpaCtrl; protected String editJSP; protected String viewJSP; protected String viewPlansJSP; protected String viewSelectedPlanJSP; protected String startsessionobjPage; private static final transient Log logger = LogFactory.getLog(Bro4xipi.class.getName()); private static EntityManagerFactory emf; private static EntityManager entityManager; private Broker broker; public BrokerJpaController getBrokerJpaCtrl() { return brokerJpaCtrl; } public void setBrokerJpaCtrl(BrokerJpaController brokerJpaCtrl) { this.brokerJpaCtrl = brokerJpaCtrl; } public void setup() { logger.info("Calling setup"); eu.xipi.bro4xipi.brokermodel.BrokerJpaController b = new BrokerJpaController(); this.brokerJpaCtrl = b; Bro4xipi.emf = PersistenceManager.getInstance().getEntityManagerFactory(); Bro4xipi.entityManager = emf.createEntityManager(); } /* (non-Javadoc) * @see javax.portlet.GenericPortlet#init() */ public void init() throws PortletException { logger.info("in init"); editJSP = getInitParameter("edit-jsp"); viewJSP = getInitParameter("view-jsp"); viewPlansJSP = getInitParameter("viewPlans-jsp"); viewSelectedPlanJSP = getInitParameter("viewSelectedPlan-jsp"); startsessionobjPage = getInitParameter("startsessionobj-jsp"); if (brokerJpaCtrl != null) logger.info("Init Bro4xipi GenericPortlet brokerJpaCtrl=" + brokerJpaCtrl.toString()); else logger.info("Init Bro4xipi GenericPortlet brokerJpaCtrl=NULL!"); setup(); if (brokerJpaCtrl != null) { logger.info("Init Bro4xipi GenericPortlet brokerJpaCtrl=" + brokerJpaCtrl.toString()); brokerJpaCtrl.setEntityManager(entityManager); entityManager.getTransaction().begin(); broker = brokerJpaCtrl.getFirstBroker(); entityManager.getTransaction().commit(); if (broker != null) { logger.info("brokerJpaCtrl.getFirstBroker()=" + broker.getName()); } else { logger.info("brokerJpaCtrl.getFirstBroker()= NULL!"); } } else logger.info("Init Bro4xipi GenericPortlet brokerJpaCtrl=NULL!"); } /* (non-Javadoc) * @see javax.portlet.GenericPortlet#doEdit(javax.portlet.RenderRequest, javax.portlet.RenderResponse) */ public void doEdit(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { renderResponse.setContentType("text/html"); PortletURL addNameURL = renderResponse.createActionURL(); addNameURL.setParameter("addName", "addName"); renderRequest.setAttribute("addNameURL", addNameURL.toString()); include(editJSP, renderRequest, renderResponse); } /* (non-Javadoc) * @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse) */ public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { logger.info("in doView.."); PortletPreferences prefs = renderRequest.getPreferences(); //Try to get the session object XiPiScenarioRequest sr = (XiPiScenarioRequest) renderRequest.getPortletSession() .getAttribute("JSPxipiScenarioRequest"); if (sr == null) { //session obj bean not yet created logger.info("===> IN doView: (sr == null) "); include(startsessionobjPage, renderRequest, renderResponse); //in here the session bean is created! //this should be after include! sr = (XiPiScenarioRequest) renderRequest.getPortletSession().getAttribute("JSPxipiScenarioRequest"); logger.info("===>XiPiScenarioRequest sr just created sr=" + sr.toString()); sr.setScenarioName("myNewExperiment"); sr.setBroker(broker); renderRequest.getPortletSession().setAttribute("JSPxipiScenarioRequest", sr); } else { //the session object already exists logger.info("===> IN doView: (XiPiScenarioRequest sr != null) !!!! sr=" + sr.toString()); sr.setBroker(broker); } if (portletViewstatus == portletViewstatusEnum.PVDEFINITION) include(viewJSP, renderRequest, renderResponse); else if (portletViewstatus == portletViewstatusEnum.PVPLANS) include(viewPlansJSP, renderRequest, renderResponse); else if (portletViewstatus == portletViewstatusEnum.PVSELECTEDPLAN) include(viewSelectedPlanJSP, renderRequest, renderResponse); } /* (non-Javadoc) * @see javax.portlet.GenericPortlet#processAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse) */ public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { //uncomment to view more debug info for passed parameters between pages // logger.debug("==> in processAction"); // Enumeration<String> pns = actionRequest.getParameterNames(); // while (pns.hasMoreElements()) // logger.debug("==> in processAction pns.nextElement() ="+pns.nextElement()); // // Enumeration<String> atns = actionRequest.getAttributeNames(); // while (atns.hasMoreElements()) // logger.debug("==> in processAction atns.nextElement() ="+atns.nextElement()); // // Enumeration<String> propns = actionRequest.getPropertyNames(); // while (propns.hasMoreElements()) // logger.debug("==> in processAction getPropertyNames.nextElement() ="+propns.nextElement()); String mvcPath = actionRequest.getParameter("mvcPath"); //works like a statemachine according to which page we wish to view if (mvcPath != null) { if (mvcPath.equals("startTransformation")) startTransformation(actionRequest, actionResponse); else if (mvcPath.equals("addScenarioAction")) addScenarioAction(actionRequest, actionResponse); else if (mvcPath.equals("backToAddScenarioURL")) startScenarioAction(actionRequest, actionResponse); else if (mvcPath.equals("viewSelectedPlanAction")) viewSelectedPlanAction(actionRequest, actionResponse); else if (mvcPath.equals("backToViewPlansAction")) viewPlansAction(actionRequest, actionResponse); } } /** * * It will display the page with the selected plan * @param actionRequest * @param actionResponse * @throws IOException * @throws PortletException */ public void viewSelectedPlanAction(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { String selectedPlanId = actionRequest.getParameter("planid"); logger.info("==> in viewSelectedPlanAction selectedPlanId=" + selectedPlanId); portletViewstatus = portletViewstatusEnum.PVSELECTEDPLAN; XiPiScenarioRequest sr = (XiPiScenarioRequest) actionRequest.getPortletSession() .getAttribute("JSPxipiScenarioRequest"); sr.setSelectedPlanId(Integer.parseInt(selectedPlanId)); actionResponse.setPortletMode(PortletMode.VIEW); } /** * It will display the page with Offered plans * @param actionRequest * @param actionResponse * @throws IOException * @throws PortletException */ public void viewPlansAction(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { logger.info("==> in viewPlansAction"); portletViewstatus = portletViewstatusEnum.PVPLANS; actionResponse.setPortletMode(PortletMode.VIEW); } /** * It will display the main view page of a scenario * * @param actionRequest * @param actionResponse * @throws IOException * @throws PortletException */ public void addScenarioAction(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { logger.info("==> in addScenarioAction"); portletViewstatus = portletViewstatusEnum.PVPLANS; Enumeration<String> pns = actionRequest.getPortletSession().getAttributeNames(); while (pns.hasMoreElements()) { String s = pns.nextElement(); logger.info("==> in addScenarioAction getAttributeNames.nextElement() =" + s); Object obj = actionRequest.getPortletSession().getAttribute(s); logger.info("==> in addScenarioAction, obj=" + obj.toString()); if (obj instanceof XiPiScenarioRequest) { XiPiScenarioRequest sr = (XiPiScenarioRequest) obj; logger.info("==> in addScenarioAction, srname=" + sr.getScenario().getName()); if (sr.getBroker() == null) sr.setBroker(broker); } } XiPiScenarioRequest sr = (XiPiScenarioRequest) actionRequest.getPortletSession() .getAttribute("JSPxipiScenarioRequest"); if (sr != null) { sr.setBroker(broker); logger.info("Setting broker to XiPiScenarioRequest = " + broker.toString()); String inputScenarioName = actionRequest.getParameter("inputScenarioName"); sr.setScenarioName(inputScenarioName); DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm z"); Date startDate; try { startDate = df.parse(actionRequest.getParameter("startDate")); sr.setStartDate(startDate); Date endDate = df.parse(actionRequest.getParameter("endDate")); sr.setEndDate(endDate); for (Iterator<ServiceRequest> iterator = sr.getScenario().getServicesRequest() .getServiceRequestList().iterator(); iterator.hasNext();) { ServiceRequest servReq = (ServiceRequest) iterator.next(); if (servReq instanceof ServiceRequest) { ServiceRequest serviceRequest = (ServiceRequest) servReq; logger.info("serviceRequest.getName()=" + serviceRequest.getName()); } } logger.debug("Starting ResourceAdvisor"); //logger.info("Contracts=" + brokerJpaCtrl.countServiceContracts() ); ResourceAdvisor ra = new ResourceAdvisor(broker, sr.getScenario(), brokerJpaCtrl); ra.CalculateOffers(); Vector<OfferedPlan> offeredPlans = ra.getOfferedPlans(); for (OfferedPlan offeredPlan : offeredPlans) { logger.info("========= " + offeredPlan.getProposedScenario().getName() + " #" + offeredPlan.getPlanID() + " ========="); Vector<AdvicedOffer> offer = offeredPlan.getAdvicedOffers(); for (AdvicedOffer advicedOffer : offer) { logger.info(advicedOffer.getFullOfferedResourceIDRevert()); } } sr.setOfferedPlans(offeredPlans); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.info("==> in addScenarioAction, XiPiScenarioRequest sr= =" + sr.getScenario().getName()); } else { logger.info("==> in addScenarioAction, XiPiScenarioRequest sr= NULL !"); } actionResponse.setPortletMode(PortletMode.VIEW); } /** * * used to return back to scenario view * @param actionRequest * @param actionResponse * @throws IOException * @throws PortletException */ public void startScenarioAction(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { logger.info("==> in startScenarioAction"); portletViewstatus = portletViewstatusEnum.PVDEFINITION; actionResponse.setPortletMode(PortletMode.VIEW); } /** * * only called from edit mode to start manually the transformation * This process takes time (about 10-15 minutes) * @param actionRequest * @param actionResponse * @throws IOException * @throws PortletException */ public void startTransformation(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { logger.info("In startTransformation"); broker = brokerJpaCtrl.getFirstBroker(); while (broker != null) { //delete all brokers found if any...normally should be only one logger.info("Delete found brokers"); entityManager.getTransaction().begin(); brokerJpaCtrl.delete(broker); entityManager.getTransaction().commit(); broker = brokerJpaCtrl.getFirstBroker(); } logger.info("Starting transofrmation"); XiPiBroker xipibroker = new XiPiBroker(); //xipibroker.setMakeOnlyOneTaxonomy(true); //used to test a smalled transformation String endpointUrl = "http://www.xipi.eu/InfinityServices-portlet/json"; xipibroker.setEndPointUrl(endpointUrl); xipibroker.setURLAPI_getTechnicalComponents(endpointUrl + "?serviceClassName=com.liferay.infinity.service.InfrastructureServiceUtil&serviceMethodName=getTechnicalComponents"); xipibroker.setURLAPI_getInfrastructuresById(endpointUrl + "?serviceClassName=com.liferay.infinity.service.InfrastructureServiceUtil&serviceMethodName=getInfrastructuresById&serviceParameters=[id]&id="); xipibroker.setURLAPI_searchInfrastructures(endpointUrl + "?serviceClassName=com.liferay.infinity.service.InfrastructureServiceUtil&serviceMethodName=searchInfrastructures&serviceParameters=[text,country,component]&text=_$TEXTSEARCH_&country=_$COUNTRYID_&component=_$COMPONENTID_"); xipibroker.setURLAPI_getComponentDetail(endpointUrl + "?serviceClassName=com.liferay.infinity.service.InfrastructureServiceUtil&serviceMethodName=getComponentDetail&serviceParameters=[idInfra,idComponent]&idInfra=_$INFRAID_&idComponent=_$COMPONENTID_"); xipibroker.setURLAPI_getValue4Field(endpointUrl + "?serviceClassName=com.liferay.infinity.service.InfrastructureServiceUtil&serviceMethodName=getValue4Field"); //xipibroker.setMakeOnlyOneTaxonomy(true); xipibroker.startTransformation(true); Broker bro = xipibroker.getBroker(); // Broker bro = createTestBroker(); if (bro != null) { logger.info("Transformation finished. Broker is =" + bro.getName()); entityManager.getTransaction().begin(); brokerJpaCtrl.addBroker(bro); entityManager.getTransaction().commit(); logger.info("Broker and all data saved succesfully"); broker = brokerJpaCtrl.getFirstBroker(); logger.info("Broker getFirstBroker"); } else logger.info("Transformation finished. Broker is = NULL"); } protected void include(String path, RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { PortletRequestDispatcher portletRequestDispatcher = getPortletContext().getRequestDispatcher(path); if (portletRequestDispatcher == null) { logger.error(path + " is not a valid include"); } else { portletRequestDispatcher.include(renderRequest, renderResponse); } } }