Example usage for java.util Date setSeconds

List of usage examples for java.util Date setSeconds

Introduction

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

Prototype

@Deprecated
public void setSeconds(int seconds) 

Source Link

Document

Sets the seconds of this Date to the specified value.

Usage

From source file:skoa.helpers.Graficos.java

private void compararFicheros(String freferencia, String fcomparar) {
    System.out.println("min=" + rangoMinutos + ".");
    File fr = new File(ruta + freferencia); //El primer fichero es el de referencia, y del que se sacan los incrementos.
    File fc = new File(ruta + fcomparar);
    FileReader fr1 = null, fr2 = null;
    BufferedReader linea1 = null, linea2 = null;
    String L1 = null, L2 = null;//ww  w . ja  va2s .co m
    SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    //Vamos a abrir los dos ficheros a la vez, leyendo lnea por lnea y comparando.
    try {
        File temp = new File(ruta + "temp.txt");
        if (!temp.exists())
            temp.createNewFile(); //Crea el fichero
        //LEEMOS EL PRIMER FICHERO
        fr1 = new FileReader(fr);
        linea1 = new BufferedReader(fr1);
        Vector<String> fechas = new Vector<String>(); //vector donde irn todas las fechas
        Date d1 = null, dini = null, dfin = null;
        boolean primeravez = true, nuevo = true;
        float media1 = 0;
        int nelem1 = 0, segd1 = 0;
        String fecha = "", aux = "", lant = "";
        while ((L1 = linea1.readLine()) != null) {
            aux = L1.substring(0, L1.indexOf("\t")); //Fecha de la lnea.
            d1 = formatoDelTexto.parse(aux);
            String Ssegd1 = aux.substring(aux.indexOf(" ") + 7, aux.indexOf(" ") + 9);
            segd1 = Integer.parseInt(Ssegd1);
            d1.setSeconds(segd1);
            if (nuevo) { //Si terminamos el intervalo, pasamos al siguiente.
                Calendar c = Calendar.getInstance();
                if (!primeravez) {//Si no es la primera iteracion, se guarda antes de inicializar.
                    //System.out.println(media1+"  "+nelem1);
                    media1 = media1 / nelem1;
                    BufferedWriter bw = new BufferedWriter(new FileWriter(ruta + "temp.txt", true)); //Para escribir.
                    String x1 = "" + media1;
                    if (!x1.contentEquals("NaN"))
                        bw.write("" + fecha + "\t" + media1 + " " + unidad + "\n");
                    bw.close();
                    media1 = nelem1 = 0;
                    String v = lant.substring(lant.indexOf("\t") + 1);
                    v = v.substring(0, v.indexOf(" "));
                    media1 = Float.parseFloat(v);//Se inicializan con los valores de la anterior linea.
                    nelem1 = 1;
                } else {
                    String u = L1.substring(L1.indexOf("\t") + 1);
                    unidad = u.substring(u.indexOf(" ") + 1);
                    lant = L1;
                    //Si es la 1 vez, tambin se inicializa la fecha inicial.
                }
                primeravez = false;
                fecha = lant.substring(0, lant.indexOf("\t"));
                fechas.add(fecha);
                //Inserta la fecha en el vector de fechas, para luego usarlo en el 2 fichero.
                Date diniaux = formatoDelTexto.parse(fecha);
                String Ssegd2 = fecha.substring(fecha.indexOf(" ") + 7, fecha.indexOf(" ") + 9);
                int segd2 = Integer.parseInt(Ssegd2);
                c.setTime(diniaux);
                dini = c.getTime();
                dini.setSeconds(segd2);
                //System.out.println("Ini="+dini);
                c.add(Calendar.MINUTE, Integer.parseInt(rangoMinutos));
                dfin = c.getTime();
                dfin.setSeconds(segd2);
                //System.out.println("Fin="+dfin);
                nuevo = false;//Esta variable se usa para definir otra vez un nuevo intervalo
            }
            if (d1.compareTo(dini) == 0) { //Fechas Iguales
                aux = L1.substring(L1.indexOf("\t") + 1);
                aux = aux.substring(0, aux.indexOf(" "));
                media1 = media1 + Float.parseFloat(aux);
                nelem1++;
            } else if (d1.compareTo(dini) > 0 && d1.compareTo(dfin) < 0) { //Est dentro del intervalo
                aux = L1.substring(L1.indexOf("\t") + 1);
                aux = aux.substring(0, aux.indexOf(" "));
                media1 = media1 + Float.parseFloat(aux);
                nelem1++;
            } else {//Si la fecha es menor que la fecha inicial o mayor que la final, se cambia de intervalo.
                nuevo = true;
            }
            lant = L1;
        }
        //guardo lo ultimo y penultimo si lo hay
        media1 = media1 / nelem1;
        BufferedWriter bw = new BufferedWriter(new FileWriter(ruta + "temp.txt", true)); //Para escribir.
        String x1 = "" + media1;
        String auxi = dini.toGMTString(); //d mon yyyy hh:mm:ss
        String d = auxi.substring(0, auxi.indexOf(" "));
        if (Integer.parseInt(d) < 10)
            d = "0" + d;
        auxi = auxi.substring(auxi.indexOf(" ") + 1);
        String m = auxi.substring(0, auxi.indexOf(" "));
        if (m.contentEquals("Jan"))
            m = "01";
        if (m.contentEquals("Feb"))
            m = "02";
        if (m.contentEquals("Mar"))
            m = "03";
        if (m.contentEquals("Apr"))
            m = "04";
        if (m.contentEquals("May"))
            m = "05";
        if (m.contentEquals("Jun"))
            m = "06";
        if (m.contentEquals("Jul"))
            m = "07";
        if (m.contentEquals("Aug"))
            m = "08";
        if (m.contentEquals("Sep"))
            m = "09";
        if (m.contentEquals("Oct"))
            m = "10";
        if (m.contentEquals("Nov"))
            m = "11";
        if (m.contentEquals("Dec"))
            m = "12";
        auxi = auxi.substring(auxi.indexOf(" ") + 1);
        String y = auxi.substring(0, auxi.indexOf(" "));
        auxi = auxi.substring(auxi.indexOf(" ") + 1);
        String h = auxi.substring(0, auxi.indexOf(" "));
        //System.out.println(y+"-"+m+"-"+d+" "+h);
        if (!x1.contentEquals("NaN"))
            bw.write("" + y + "-" + m + "-" + d + " " + h + "\t" + media1 + " " + unidad + "\n");
        bw.close();
        fechas.add(y + "-" + m + "-" + d + " " + h);
        fecha = lant.substring(0, lant.indexOf("\t"));
        if (!fecha.isEmpty()) {
            String auxr = lant.substring(lant.indexOf("\t") + 1);
            auxr = auxr.substring(0, auxr.indexOf(" "));
            media1 = Float.parseFloat(auxr);
            bw = new BufferedWriter(new FileWriter(ruta + "temp.txt", true)); //Para escribir.
            x1 = "" + media1;
            if (!x1.contentEquals("NaN"))
                bw.write("" + fecha + "\t" + media1 + " " + unidad + "\n");
            bw.close();
            fechas.add(fecha);
        }
        fr1.close();
        //for (int i=0;i<fechas.size();i++) System.out.println("*"+fechas.elementAt(i));

        //Leido el primer fichero, leo el segundo.
        File temp2 = new File(ruta + "temp2.txt");
        if (!temp2.exists())
            temp2.createNewFile(); //Crea el fichero
        fr2 = new FileReader(fc);
        linea2 = new BufferedReader(fr2);
        int pos = 0;
        String fechaf = "";
        media1 = nelem1 = 0;
        nuevo = true;
        primeravez = true;
        while ((L2 = linea2.readLine()) != null) {
            aux = L2.substring(0, L2.indexOf("\t")); //Fecha de la lnea.
            d1 = formatoDelTexto.parse(aux);
            String Ssegd1 = aux.substring(aux.indexOf(" ") + 7, aux.indexOf(" ") + 9);
            segd1 = Integer.parseInt(Ssegd1);
            d1.setSeconds(segd1);
            if (nuevo) { //Si terminamos el intervalo, pasamos al siguiente.            
                Calendar c = Calendar.getInstance();
                if (!primeravez) {//Si no es la primera iteracion, se guarda antes de inicializar.
                    media1 = media1 / nelem1;
                    BufferedWriter bw1 = new BufferedWriter(new FileWriter(ruta + "temp2.txt", true)); //Para escribir.
                    x1 = "" + media1;
                    if (!x1.contentEquals("NaN"))
                        bw1.write("" + /*fechas.elementAt(pos)+"\t"+*/media1 + " " + unidad + "\n");
                    bw1.close();
                    pos++;
                    //media1=nelem1=0;
                    String v = lant.substring(lant.indexOf("\t") + 1);
                    v = v.substring(0, v.indexOf(" "));
                    media1 = Float.parseFloat(v);//Se inicializan con los valores de la anterior linea.
                    nelem1 = 1;
                } else {
                    String u = L2.substring(L2.indexOf("\t") + 1);
                    unidad = u.substring(u.indexOf(" ") + 1);
                    lant = L1;
                    pos = 0;
                    //Si es la 1 vez, tambin se inicializa la fecha inicial.
                }
                //System.out.println(fechas.elementAt(pos));
                primeravez = false;
                fecha = fechas.elementAt(pos);
                Date diniaux = formatoDelTexto.parse(fecha);
                String Ssegd2 = fecha.substring(fecha.indexOf(" ") + 7, fecha.indexOf(" ") + 9);
                int segd2 = Integer.parseInt(Ssegd2);
                c.setTime(diniaux);
                dini = c.getTime(); //FECHA INICIAL.                    
                dini.setSeconds(segd2);

                if (pos + 1 >= fechas.size())
                    break;
                fechaf = fechas.elementAt(pos + 1);
                Date dfinaux = formatoDelTexto.parse(fechaf);
                Ssegd2 = fecha.substring(fechaf.indexOf(" ") + 7, fechaf.indexOf(" ") + 9);
                segd2 = Integer.parseInt(Ssegd2);
                c.setTime(dfinaux);
                dfin = c.getTime(); //FECHA FINAL
                dfin.setSeconds(segd2);
                //System.out.println("INI="+dini);
                //System.out.println("FIN="+dfin);
                nuevo = false;//Esta variable se usa para definir otra vez un nuevo intervalo
            }
            if (d1.compareTo(dini) == 0) { //Fechas Iguales
                aux = L2.substring(L2.indexOf("\t") + 1);
                aux = aux.substring(0, aux.indexOf(" "));
                media1 = media1 + Float.parseFloat(aux);
                nelem1++;
            } else if (d1.compareTo(dini) > 0 && d1.compareTo(dfin) < 0) { //Est dentro del intervalo
                aux = L2.substring(L2.indexOf("\t") + 1);
                aux = aux.substring(0, aux.indexOf(" "));
                media1 = media1 + Float.parseFloat(aux);
                nelem1++;
            } else {//Si la fecha es menor que la fecha inicial o mayor que la final, se cambia de intervalo.
                nuevo = true;
            }
            lant = L2;
        }
        //guardo lo ultimo si lo hay
        fecha = lant.substring(0, lant.indexOf("\t"));
        if (!fecha.isEmpty()) {
            String auxr = lant.substring(lant.indexOf("\t") + 1);
            auxr = auxr.substring(0, auxr.indexOf(" "));
            media1 = Float.parseFloat(auxr);
            BufferedWriter bw2 = new BufferedWriter(new FileWriter(ruta + "temp2.txt", true)); //Para escribir.
            x1 = "" + media1;
            if (!x1.contentEquals("NaN"))
                bw2.write("" + /*fechas.elementAt(pos+1)+"\t"+*/media1 + " " + unidad + "\n");
            bw2.close();
        }
        fr2.close();
        //CREAMOS EL UNIFICADO
        File unificado = new File(ruta + "unificado.txt");
        if (!unificado.exists())
            unificado.createNewFile(); //Crea el fichero
        fr1 = new FileReader(temp);
        linea1 = new BufferedReader(fr1);
        fr2 = new FileReader(temp2);
        linea2 = new BufferedReader(fr2);
        L1 = L2 = "";
        BufferedWriter bwf = new BufferedWriter(new FileWriter(ruta + "unificado.txt", true)); //Para escribir.
        while ((L1 = linea1.readLine()) != null && (L2 = linea2.readLine()) != null) {
            bwf.write(L1 + "\t" + L2 + "\n");
        }
        bwf.close();
        fechas.removeAllElements();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != fr1)
                fr1.close(); //cierra el 1 fichero.
            if (null != fr2)
                fr2.close(); //cierra el 2 fichero.
        } catch (Exception e2) { //Sino salta una excepcion.
            e2.printStackTrace();
        }
    }
    File temp1 = new File(ruta + "temp.txt");
    File temp2 = new File(ruta + "temp2.txt");
    temp1.delete();
    temp2.delete();
}

From source file:ProcessRequest.java

public JSONObject getWeight(final String host, final int port, final int numChars, final int weightBeginPos,
        final int weightEndPos, final int termChar, final int statusBeginPos, final int statusEndPos,
        final int normalChar, final int motionChar, int timeout, final String overcapacity) {
    //Thread socketThread = new Thread() {
    //   public void run() {
    //cannot run in thread
    Socket connection = null;/*  w  w  w.  j a v a  2 s .co m*/
    JSONObject returnObject = new JSONObject();
    try {
        System.out.println("opening socket");
        connection = new Socket(host, port);
        System.out.println("getting stream");
        InputStreamReader reader = new InputStreamReader(connection.getInputStream());
        System.out.println("creating character buffer");
        boolean success = false;
        java.util.Date beginDate = new java.util.Date();
        java.util.Date endDate = (java.util.Date) beginDate.clone();
        endDate.setSeconds(endDate.getSeconds() + timeout);
        while (!success) {
            beginDate = new java.util.Date();
            if (beginDate.after(endDate)) {
                returnObject.put("error", "the operation timed out");
                //out.println(returnObject.toString(5));
                return returnObject;
            }
            String string = new String();
            int count = 0;
            while (reader.read() != (char) (termChar)) {
                if (count > 5000) {
                    break;
                }
                count++;
            }
            if (count > 5000) {
                returnObject.put("error",
                        "termchar was not found in the stream.  are you sure the scale is set up correctly?");
                //out.println(returnObject.toString(5));
                return returnObject;
            }
            for (int i = 0; i < numChars; i++) {
                string += (char) (reader.read());
            }
            //get negative marker also
            String weight = string.substring(weightBeginPos - 1, weightEndPos);
            String status = string.substring(statusBeginPos - 1, statusEndPos);
            String uom = string.substring(9, 11);
            System.out.println("weight: '" + weight + "'");
            System.out.println("status: '" + status + "'");
            System.out.println("uom   : '" + uom + "'");

            if (string.contains(overcapacity)) {
                returnObject.put("error", "Over Capacity!");
                return returnObject;
            } else {
                System.out.println("extracting weight value");
                returnObject.put("weight", new Integer(weight).toString());
                System.out.println("checking motion");
                if (status.charAt(0) == ((char) (normalChar))) {
                    returnObject.put("motion", false);
                } else if (status.charAt(0) == ((char) (motionChar))) {
                    returnObject.put("motion", true);
                } else {
                    returnObject.put("error", "Invalid Motion Char!\n(check web service settings)");
                }
                System.out.println("checking uom");
                if (uom.equals("LB")) {
                    returnObject.put("uom", "lbs");
                } else if (uom.equals("KG")) {
                    returnObject.put("uom", "kg");
                } else {
                    //unknown weight type, no cause for error here.
                }
            }
            System.out.println("sending resultant json");
            //out.println(returnObject.toString(5));
            success = true;
        }
    } catch (Exception e) {
        System.out.println("ERROR");
        System.out.println("ERROR: could not connect to scale: " + e.toString());
        try {
            returnObject.put("error", "could not connect to scale: " + e.toString());
            return returnObject;
            //out.println(returnObject.toString(5));
        } catch (Exception je) {
            //out.println("parser error?");
            returnObject.put("error", je.toString());
            return returnObject;
        }
    } finally {
        try {
            connection.close();
        } catch (Exception e) {
            //don't care at this point.
        }
        return returnObject;
    }
    //   }
    //};

    //socketThread.start();
}

From source file:com.krawler.spring.crm.common.crmManagerDAOImpl.java

/**
 * To convert a date and time selected separately by user into corresponding combined datetime
 * from users selected timezone to systems timezone
 *
 * The first step is to keep track of the time difference in order to change the date if required.
 * Two time only objects dtold and dtcmp are created for this purpose.
 *
 * The date passed and the time passed that are in system timezone are formatted without
 * timezone and then parsed into the required timezone and then the time values are set
 * back to the date value sent.//from   ww  w . ja va 2s.  c  om
 *
 **/
public Date converttz(String timeZoneDiff, Date dt, String time) {
    Calendar cal = Calendar.getInstance();
    try {
        if (timeZoneDiff == null || timeZoneDiff.isEmpty()) {
            timeZoneDiff = "-7:00";
        }
        String val;
        SimpleDateFormat sdf = new SimpleDateFormat("HHmm 'Hrs'");
        Date dtold = sdf.parse("0000 Hrs");
        if (!time.endsWith("Hrs")) {
            sdf = new SimpleDateFormat("hh:mm a");
            dtold = sdf.parse("00:00 AM");
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
        sdf2.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDiff)); // Setting the timezone passed

        Date dt1 = sdf.parse(time); // Setting the passed time to the date object in system timezone

        sdf.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDiff)); // Setting the timezone passed
        Date dtcmp = sdf.parse(time); // Parsing the time to timezone using passed values
        dt1.setMonth(dt.getMonth()); // Setting the date values sent to the system time only value
        dt1.setDate(dt.getDate());
        dt1.setYear(dt.getYear());
        dt1 = sdf2.parse(sdf1.format(dt1)); // Parsing datetime into required timezone
        dt.setHours(dt1.getHours()); // Setting the time values into the sent date
        dt.setMinutes(dt1.getMinutes());
        dt.setSeconds(0);
        cal.setTime(dt);
        if (dtcmp.compareTo(dtold) < 0) { // Comparing for time value change
            cal.add(Calendar.DATE, -1); //  in order to change the date accordingly
        }
        dtold.setDate(2);
        if (dtcmp.compareTo(dtold) > 0 || dtcmp.compareTo(dtold) == 0) {
            cal.add(Calendar.DATE, 1);
        }

    } catch (ParseException ex) {
        System.out.println(ex);
    } finally {
        return cal.getTime();
    }
}

From source file:org.egov.dao.budget.BudgetDetailsHibernateDAO.java

/**
 * @description - get the list of BudgetUsage based on various parameters
 * @param queryParamMap//from ww w  . j a  v  a2  s. co  m
 *            - HashMap<String, Object> queryParamMap will have data
 *            required for the query the queryParamMap contain values :- the
 *            mis attribute values passed in the query map will be validated
 *            with the appconfig value of key=budgetaryCheck_groupby_values
 *            financialyearid - optional ExecutionDepartmentId - mandatory
 *            -if:department present in the app config value - optional
 *            -else fundId - mandatory -if:fund present in the app config
 *            value - optional -else schemeId - mandatory -if:Scheme present
 *            in the app config value - optional -else functionId -
 *            mandatory -if:function present in the app config value -
 *            optional -else subschemeId - mandatory -if:Subscheme present
 *            in the app config value - optional -else functionaryId -
 *            mandatory -if:functionary present in the app config value -
 *            optional -else boundaryId - mandatory -if:boundary present in
 *            the app config value - optional -else moduleId - optional
 *            financialYearId -optional budgetgroupId -optional fromDate
 *            -optional toDate -optional Order By - optional if passed then
 *            only Budgetary appropriation number and reference number is
 *            accepted, if not passed then default order by is date.
 * @return
 */

@Override
@SuppressWarnings("unchecked")
public List<BudgetUsage> getListBudgetUsage(final Map<String, Object> queryParamMap) {

    final StringBuffer query = new StringBuffer();
    final Map<String, String> grpByVls = new HashMap<String, String>();
    List<BudgetUsage> listBudgetUsage = null;
    query.append("select bu from BudgetUsage bu,BudgetDetail bd where  bu.budgetDetail.id=bd.id");
    final List<AppConfigValues> list = appConfigValuesService.getConfigValuesByModuleAndKey(EGF,
            BUDGETARY_CHECK_GROUPBY_VALUES);
    if (list.isEmpty())
        throw new ValidationException(EMPTY_STRING,
                "budgetaryCheck_groupby_values is not defined in AppConfig");
    final AppConfigValues appConfigValues = list.get(0);
    if (appConfigValues.getValue().indexOf(",") != 1) { // if there are more
        // than one comma
        // separated values
        // for key =
        // budgetaryCheck_groupby_values
        final String[] values = StringUtils.split(appConfigValues.getValue(), ",");
        for (final String value : values)
            grpByVls.put(value, value);
    } else
        grpByVls.put(appConfigValues.getValue(), appConfigValues.getValue());

    if (!isNull(grpByVls.get("fund")))
        if (isNull(queryParamMap.get("fundId")))
            throw new ValidationException(EMPTY_STRING, "Fund is required");
        else
            query.append(" and bd.fund.id=").append(Integer.valueOf(queryParamMap.get("fundId").toString()));
    if (!isNull(grpByVls.get("department")))
        if (isNull(queryParamMap.get("ExecutionDepartmentId")))
            throw new ValidationException(EMPTY_STRING, "Department is required");
        else
            query.append(" and bd.executingDepartment.id=")
                    .append(Integer.valueOf(queryParamMap.get("ExecutionDepartmentId").toString()));
    if (!isNull(grpByVls.get("function")))
        if (isNull(queryParamMap.get("functionId")))
            throw new ValidationException(EMPTY_STRING, "Function is required");
        else
            query.append(" and bd.function.id=")
                    .append(Long.valueOf(queryParamMap.get("functionId").toString()));
    if (!isNull(grpByVls.get("scheme")))
        if (isNull(queryParamMap.get("schemeId")))
            throw new ValidationException(EMPTY_STRING, "Scheme is required");
        else
            query.append(" and bd.scheme.id=")
                    .append(Integer.valueOf(queryParamMap.get("schemeId").toString()));
    if (!isNull(grpByVls.get("subscheme")))
        if (isNull(queryParamMap.get("subschemeId")))
            throw new ValidationException(EMPTY_STRING, "SubScheme is required");
        else
            query.append(" and bd.subScheme.id=")
                    .append(Integer.valueOf(queryParamMap.get("subschemeId").toString()));
    if (!isNull(grpByVls.get(Constants.FUNCTIONARY)))
        if (isNull(queryParamMap.get("functionaryId")))
            throw new ValidationException(EMPTY_STRING, "Functionary is required");
        else
            query.append(" and bd.functionary.id=")
                    .append(Integer.valueOf(queryParamMap.get("functionaryId").toString()));
    if (!isNull(grpByVls.get("boundary")))
        if (isNull(queryParamMap.get("boundaryId")))
            throw new ValidationException(EMPTY_STRING, "Boundary is required");
        else
            query.append(" and bd.boundary.id=")
                    .append(Integer.valueOf(queryParamMap.get("boundaryId").toString()));
    if (!isNull(queryParamMap.get("moduleId")))
        query.append(" and bu.moduleId=").append(Integer.valueOf(queryParamMap.get("moduleId").toString()));
    if (!isNull(queryParamMap.get("financialYearId")))
        query.append(" and bu.financialYearId=")
                .append(Integer.valueOf(queryParamMap.get("financialYearId").toString()));
    if (!isNull(queryParamMap.get("budgetgroupId")))
        query.append(" and bd.budgetGroup.id=")
                .append(Long.valueOf(queryParamMap.get("budgetgroupId").toString()));
    if (!isNull(queryParamMap.get("fromDate")))
        query.append(" and bu.updatedTime >=:from");
    if (!isNull(queryParamMap.get("toDate")))
        query.append(" and bu.updatedTime <=:to");
    if (!isNull(queryParamMap.get("Order By"))) {
        if (queryParamMap.get("Order By").toString().indexOf("appropriationnumber") == -1
                && queryParamMap.get("Order By").toString().indexOf("referenceNumber") == -1)
            throw new ValidationException(EMPTY_STRING,
                    "order by value can be only Budgetary appropriation number or Reference number or both");
        else
            query.append(" Order By ").append(queryParamMap.get("Order By"));
    } else
        query.append(" Order By bu.updatedTime");

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Budget Usage Query >>>>>>>> " + query.toString());
    final Query query1 = getCurrentSession().createQuery(query.toString());
    if (!isNull(queryParamMap.get("fromDate")))
        query1.setTimestamp("from", (Date) queryParamMap.get("fromDate"));
    if (!isNull(queryParamMap.get("toDate"))) {
        final Date date = (Date) queryParamMap.get("toDate");
        date.setMinutes(59);
        date.setHours(23);
        date.setSeconds(59);
        query1.setTimestamp("to", date);
    }

    listBudgetUsage = query1.list();
    return listBudgetUsage;

}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private String replaceDateParameters(String jpql, List<Date> dtParams) throws ParseException {
    if (jpql.contains(IConstants.DT_SEP)) {
        String[] split = jpql.split(IConstants.DT_SEP);
        int j = 0;
        SimpleDateFormat sdf = new SimpleDateFormat(IConstants.DT_YYYY_MM_DD);
        for (int i = 1; i < split.length; i++) {
            if (split[i] != null && split[i].length() > 0 && !split[i].startsWith(" ")) {
                try {
                    Date dt = sdf.parse(split[i]);
                    String last = split[i - 1].trim();
                    if (last.endsWith("<") || last.endsWith("<=")) {
                        dt.setHours(23);
                        dt.setMinutes(59);
                        dt.setSeconds(59);
                    } else if (last.endsWith(">") || last.endsWith(">=")) {
                        dt.setHours(0);/*from w ww .  j  av a 2 s  .  c o m*/
                        dt.setMinutes(0);
                        dt.setSeconds(0);
                    }
                    dtParams.add(dt);
                    split[i] = ":dt" + j;
                    j++;
                } catch (Exception e) {
                }
            }
        }
        jpql = "";
        for (int i = 0; i < split.length; i++) {
            jpql = jpql + split[i];
        }
    }
    return jpql;
}

From source file:br.gov.jfrj.siga.ex.bl.ExBL.java

/**
 * Calcula quais as marcas cada mobil ter com base nas movimentaes que
 * foram feitas no documento./*  w  w w.j av  a  2s.c o  m*/
 * 
 * @param mob
 */
private SortedSet<ExMarca> calcularMarcadores(ExMobil mob) {
    SortedSet<ExMarca> set = calcularMarcadoresTemporalidade(mob);

    ExMovimentacao ultMovNaoCanc = mob.getUltimaMovimentacaoNaoCancelada();

    Boolean isDocumentoSemEfeito = mob.doc().isSemEfeito();

    if (mob.isGeral()) {
        if (!mob.doc().isFinalizado()) {
            acrescentarMarca(set, mob, CpMarcador.MARCADOR_EM_ELABORACAO, mob.doc().getDtRegDoc(),
                    mob.doc().getCadastrante(), mob.doc().getLotaCadastrante());
            if (mob.getExDocumento().getSubscritor() != null)
                acrescentarMarca(set, mob, CpMarcador.MARCADOR_REVISAR, mob.doc().getDtRegDoc(),
                        mob.getExDocumento().getSubscritor(), null);

        }

        if (mob.getExMovimentacaoSet() != null) {
            if (isDocumentoSemEfeito) {
                for (ExMovimentacao mov : mob.getExMovimentacaoSet()) {
                    if (mov.isCancelada())
                        continue;

                    Long t = mov.getIdTpMov();
                    if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_TORNAR_SEM_EFEITO) {
                        acrescentarMarca(set, mob, CpMarcador.MARCADOR_SEM_EFEITO, mov.getDtIniMov(),
                                mov.getCadastrante(), mov.getLotaCadastrante());
                    }
                }

            } else {

                Long mDje = null;
                ExMovimentacao movDje = null;
                for (ExMovimentacao mov : mob.getExMovimentacaoSet()) {
                    if (mov.isCancelada())
                        continue;
                    Long m = null;
                    Long t = mov.getIdTpMov();
                    if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_PENDENCIA_DE_ANEXACAO) {
                        acrescentarMarca(set, mob, CpMarcador.MARCADOR_PENDENTE_DE_ANEXACAO, mov.getDtIniMov(),
                                mov.getCadastrante(), mov.getLotaCadastrante());
                    } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_VINCULACAO_PAPEL) {
                        DpLotacao lotaPerfil = null;
                        switch ((int) (long) mov.getExPapel().getIdPapel()) {
                        case (int) ExPapel.PAPEL_GESTOR:
                            m = CpMarcador.MARCADOR_COMO_GESTOR;
                            break;
                        case (int) ExPapel.PAPEL_INTERESSADO:
                            m = CpMarcador.MARCADOR_COMO_INTERESSADO;
                            break;
                        }
                        if (m != null && !mob.doc().isEliminado() && !mob.doc().isArquivadoPermanente()) {
                            if (mov.getSubscritor() != null) /* perfil foi cadastrado para a pessoa */
                                lotaPerfil = null;
                            else
                                lotaPerfil = mov.getLotaSubscritor();
                            acrescentarMarca(set, mob, m, mov.getDtIniMov(), mov.getSubscritor(), lotaPerfil);
                        }

                    } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_PEDIDO_PUBLICACAO) {
                        mDje = CpMarcador.MARCADOR_PUBLICACAO_SOLICITADA;
                        movDje = mov;
                    } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_AGENDAMENTO_DE_PUBLICACAO) {
                        mDje = CpMarcador.MARCADOR_REMETIDO_PARA_PUBLICACAO;
                        movDje = mov;
                    } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DISPONIBILIZACAO) {
                        mDje = CpMarcador.MARCADOR_DISPONIBILIZADO;
                        movDje = mov;
                    } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ANEXACAO && mob.doc().isEletronico()
                            && !mob.doc().jaTransferido()) {
                        m = CpMarcador.MARCADOR_ANEXO_PENDENTE_DE_ASSINATURA;
                        /*
                         * no  possvel usar ExMovimentacao.isAssinada()
                         * pois no h tempo habil no BD de efetivar a
                         * inclusao de movimentacao de assinatura de
                         * movimento Edson: Por que no?
                         */
                        for (ExMovimentacao movAss : mob.getExMovimentacaoSet()) {
                            if ((movAss.getExTipoMovimentacao()
                                    .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_DIGITAL_MOVIMENTACAO
                                    || movAss.getExTipoMovimentacao()
                                            .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_DOCUMENTO
                                    || movAss.getExTipoMovimentacao()
                                            .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_MOVIMENTACAO_COM_SENHA
                                    || movAss.getExTipoMovimentacao()
                                            .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_COM_SENHA)
                                    && movAss.getExMovimentacaoRef().getIdMov() == mov.getIdMov()) {
                                m = null;
                                break;
                            }
                        }
                        if (m != null)
                            acrescentarMarca(set, mob, m, mov.getDtIniMov(), mov.getCadastrante(),
                                    mov.getLotaCadastrante());
                    } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_INCLUSAO_DE_COSIGNATARIO) {
                        if (mob.getDoc().isEletronico()) {
                            if (!mob.getDoc().isAssinado())
                                m = CpMarcador.MARCADOR_REVISAR;
                            else {
                                if (mob.getDoc().isAssinadoSubscritor())
                                    m = CpMarcador.MARCADOR_COMO_SUBSCRITOR;
                                else
                                    m = CpMarcador.MARCADOR_REVISAR;
                                for (ExMovimentacao assinatura : mob.getDoc().getTodasAsAssinaturas()) {
                                    if (assinatura.getSubscritor().equivale(mov.getSubscritor())) {
                                        m = null;
                                        break;
                                    }
                                }
                            }
                            if (m != null)
                                acrescentarMarca(set, mob, m, mov.getDtIniMov(), mov.getSubscritor(), null);
                        }
                    } else if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_COM_SENHA) {
                        boolean jaAutenticado = false;
                        for (ExMovimentacao movAss : mob.getExMovimentacaoSet()) {
                            if (movAss.getExTipoMovimentacao()
                                    .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_DIGITAL_DOCUMENTO
                                    || movAss.getExTipoMovimentacao()
                                            .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_DOCUMENTO) {
                                jaAutenticado = true;
                                break;
                            }
                        }

                        if (!jaAutenticado)
                            acrescentarMarca(set, mob, CpMarcador.MARCADOR_DOCUMENTO_ASSINADO_COM_SENHA,
                                    mov.getDtIniMov(), mov.getSubscritor(), null);
                    }
                }
                if (mDje != null && !mob.doc().isEliminado()) {
                    acrescentarMarca(set, mob, mDje, movDje.getDtIniMov(), movDje.getTitular(),
                            movDje.getLotaTitular());
                }
            }
        }
        return set;
    } else if (ultMovNaoCanc == null) {
        ExMovimentacao ultMov = mob.getUltimaMovimentacao();
        Date dt = null;
        if (ultMov != null) {
            dt = ultMov.getDtIniMov();
        }
        acrescentarMarca(set, mob, CpMarcador.MARCADOR_CANCELADO, dt, mob.doc().getCadastrante(),
                mob.doc().getLotaCadastrante());
        return set;
    }

    if (!isDocumentoSemEfeito) {

        boolean apensadoAVolumeDoMesmoProcesso = mob.isApensadoAVolumeDoMesmoProcesso();

        long m = CpMarcador.MARCADOR_CANCELADO;
        long m_aDevolverFora = CpMarcador.MARCADOR_A_DEVOLVER_FORA_DO_PRAZO;
        long m_aDevolver = CpMarcador.MARCADOR_A_DEVOLVER;
        long m_aguardando = CpMarcador.MARCADOR_AGUARDANDO;
        long m_aguardandoFora = CpMarcador.MARCADOR_AGUARDANDO_DEVOLUCAO_FORA_DO_PRAZO;
        long mAnterior = m;
        Date dt = null;
        //ExMovimentacao movT = new ExMovimentacao();      
        Set<ExMovimentacao> movT = new TreeSet<ExMovimentacao>();
        //contemDataRetorno = false;

        for (ExMovimentacao mov : mob.getExMovimentacaoSet()) {
            if (mov.isCancelada())
                continue;
            Long t = mov.getIdTpMov();
            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_PENDENCIA_DE_ANEXACAO)
                m = CpMarcador.MARCADOR_PENDENTE_DE_ANEXACAO;
            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_PEDIDO_PUBLICACAO)
                m = CpMarcador.MARCADOR_PUBLICACAO_SOLICITADA;
            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DISPONIBILIZACAO)
                m = CpMarcador.MARCADOR_DISPONIBILIZADO;
            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_AGENDAMENTO_DE_PUBLICACAO)
                m = CpMarcador.MARCADOR_REMETIDO_PARA_PUBLICACAO;
            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_SOBRESTAR)
                m = CpMarcador.MARCADOR_SOBRESTADO;
            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_JUNTADA)
                m = CpMarcador.MARCADOR_JUNTADO;
            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_JUNTADA_EXTERNO)
                m = CpMarcador.MARCADOR_JUNTADO_EXTERNO;
            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_APENSACAO && apensadoAVolumeDoMesmoProcesso)
                m = CpMarcador.MARCADOR_APENSADO;
            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_TRANSFERENCIA_EXTERNA
                    || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESPACHO_TRANSFERENCIA_EXTERNA) {
                m = CpMarcador.MARCADOR_TRANSFERIDO_A_ORGAO_EXTERNO;
                transferenciasSet.add(mov);
                if (mov.getDtFimMov() != null) {
                    movT.add(mov);
                }
            }
            if ((t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESPACHO_TRANSFERENCIA
                    || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_TRANSFERENCIA)
                    && !apensadoAVolumeDoMesmoProcesso) {
                m = CpMarcador.MARCADOR_CAIXA_DE_ENTRADA;
                transferenciasSet.add(mov);
                if (mov.getDtFimMov() != null) {
                    movT.add(mov);
                }
            }
            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESPACHO && mob.doc().isEletronico()) {
                m = CpMarcador.MARCADOR_DESPACHO_PENDENTE_DE_ASSINATURA;
                for (ExMovimentacao movAss : mob.getExMovimentacaoSet()) {
                    if ((movAss.getExTipoMovimentacao()
                            .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_DIGITAL_MOVIMENTACAO
                            || movAss.getExTipoMovimentacao()
                                    .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_MOVIMENTACAO_COM_SENHA)
                            && movAss.getExMovimentacaoRef().getIdMov() == mov.getIdMov()) {
                        m = mAnterior;
                    }
                }
            }

            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CRIACAO
                    || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_RECEBIMENTO
                    || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESOBRESTAR
                    || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_DIGITAL_DOCUMENTO
                    || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_COM_SENHA
                    || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CANCELAMENTO_JUNTADA
                    || t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESAPENSACAO)
                if (mob.doc().isAssinado() || mob.doc().getExTipoDocumento().getIdTpDoc() == 2
                        || mob.doc().getExTipoDocumento().getIdTpDoc() == 3) {

                    if (!apensadoAVolumeDoMesmoProcesso) {
                        m = CpMarcador.MARCADOR_EM_ANDAMENTO;
                    } else
                        m = CpMarcador.MARCADOR_APENSADO;

                } else if (mob.isApensado()) {
                    m = CpMarcador.MARCADOR_APENSADO;
                } else {
                    m = CpMarcador.MARCADOR_PENDENTE_DE_ASSINATURA;
                }

            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ANEXACAO && mob.doc().isEletronico()) {
                m = CpMarcador.MARCADOR_ANEXO_PENDENTE_DE_ASSINATURA;
                /*
                 * no  possvel usar ExMovimentacao.isAssinada() pois no
                 * h tempo habil no BD de efetivar a inclusao de
                 * movimentacao de assinatura de movimento
                 */
                for (ExMovimentacao movAss : mob.getExMovimentacaoSet()) {
                    if ((movAss.getExTipoMovimentacao()
                            .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_DIGITAL_MOVIMENTACAO
                            || movAss.getExTipoMovimentacao()
                                    .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_DOCUMENTO
                            || movAss.getExTipoMovimentacao()
                                    .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_MOVIMENTACAO_COM_SENHA
                            || movAss.getExTipoMovimentacao()
                                    .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_COM_SENHA)
                            && movAss.getExMovimentacaoRef().getIdMov() == mov.getIdMov()) {
                        m = mAnterior;
                        break;
                    }
                }
            }

            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ASSINATURA_MOVIMENTACAO_COM_SENHA) {
                acrescentarMarca(set, mob, CpMarcador.MARCADOR_MOVIMENTACAO_ASSINADA_COM_SENHA, dt,
                        mov.getSubscritor(), null);
            }

            if (t == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CONFERENCIA_COPIA_COM_SENHA) {
                acrescentarMarca(set, mob, CpMarcador.MARCADOR_MOVIMENTACAO_CONFERIDA_COM_SENHA, dt,
                        mov.getSubscritor(), null);
            }

            if (m != mAnterior) {
                dt = mov.getDtIniMov();
                mAnterior = m;
            }
        }

        Iterator itr = movT.iterator();

        while (itr.hasNext()) {
            ExMovimentacao element = (ExMovimentacao) itr.next();

            if (element.getLotaCadastrante() != null && !transferenciasSet.isEmpty()
                    && !contemRetornoTransferencia(element)) {

                Date dtMarca = element.getDtFimMov();
                dtMarca.setHours(23);
                dtMarca.setMinutes(59);
                dtMarca.setSeconds(59);

                acrescentarMarcaTransferencia(set, mob, m_aguardando, dt, dtMarca, element.getCadastrante(),
                        element.getLotaCadastrante()); // acrescenta a
                // marca
                // "Aguardando Devoluo"

                acrescentarMarcaTransferencia(set, mob, m_aDevolver, dt, dtMarca, element.getResp(),
                        element.getLotaResp());// acrescenta a marca
                // "A Devolver"

                acrescentarMarcaTransferencia(set, mob, m_aguardandoFora, dtMarca, null,
                        element.getCadastrante(), element.getLotaCadastrante()); // acrescenta a
                // marca
                // "Aguardando Devoluo (Fora do Prazo)"

                acrescentarMarcaTransferencia(set, mob, m_aDevolverFora, dtMarca, null, element.getResp(),
                        element.getLotaResp());// acrescenta
                // a
                // marca
                // "A Devolver (Fora do Prazo)"
            }
        }

        if (m == CpMarcador.MARCADOR_PENDENTE_DE_ASSINATURA) {
            if (!mob.getDoc().isAssinadoSubscritor())
                acrescentarMarca(set, mob, CpMarcador.MARCADOR_COMO_SUBSCRITOR, dt,
                        mob.getExDocumento().getSubscritor(), null);
        }

        if (m == CpMarcador.MARCADOR_CAIXA_DE_ENTRADA) {
            if (!mob.doc().isEletronico()) {
                m = CpMarcador.MARCADOR_A_RECEBER;
                acrescentarMarca(set, mob, CpMarcador.MARCADOR_EM_TRANSITO, dt, ultMovNaoCanc.getCadastrante(),
                        ultMovNaoCanc.getLotaCadastrante());
            } else {
                if (ultMovNaoCanc.getExTipoMovimentacao()
                        .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESPACHO_TRANSFERENCIA) {
                    m = CpMarcador.MARCADOR_DESPACHO_PENDENTE_DE_ASSINATURA;
                } else {
                    acrescentarMarca(set, mob, CpMarcador.MARCADOR_EM_TRANSITO_ELETRONICO, dt,
                            ultMovNaoCanc.getCadastrante(), ultMovNaoCanc.getLotaCadastrante());
                }
            }
        }

        if (m == CpMarcador.MARCADOR_TRANSFERIDO_A_ORGAO_EXTERNO) {
            acrescentarMarca(set, mob, m, dt, ultMovNaoCanc.getCadastrante(),
                    ultMovNaoCanc.getLotaCadastrante());
        } else if (m == CpMarcador.MARCADOR_DESPACHO_PENDENTE_DE_ASSINATURA) {
            if (ultMovNaoCanc.getCadastrante().getId() != ultMovNaoCanc.getSubscritor().getId()) {
                if (ultMovNaoCanc.getLotaCadastrante().getIdLotacao() != ultMovNaoCanc.getLotaSubscritor()
                        .getIdLotacao()) {
                    acrescentarMarca(set, mob, m, dt, ultMovNaoCanc.getSubscritor(),
                            ultMovNaoCanc.getLotaSubscritor());
                } else {
                    acrescentarMarca(set, mob, m, dt, ultMovNaoCanc.getSubscritor(), null);
                }
            }
            acrescentarMarca(set, mob, m, dt, ultMovNaoCanc.getCadastrante(),
                    ultMovNaoCanc.getLotaCadastrante());
        } else if (m == CpMarcador.MARCADOR_JUNTADO || m == CpMarcador.MARCADOR_APENSADO) {
            if (!mob.isEliminado())
                acrescentarMarca(set, mob, m, dt, null, null);
        } else {
            // Edson: Os marcadores "Arq Corrente" e
            // "Aguardando andamento" so mutuamente exclusivos
            if (m != CpMarcador.MARCADOR_EM_ANDAMENTO
                    || !(mob.isArquivado() || mob.doc().getMobilGeral().isArquivado()))
                acrescentarMarca(set, mob, m, dt, ultMovNaoCanc.getResp(), ultMovNaoCanc.getLotaResp());
        }

    }
    return set;
}

From source file:org.apache.lens.server.metastore.TestMetastoreService.java

@Test(dataProvider = "mediaTypeData")
public void testCreateFactTableWithMultipleUpdatePeriods(MediaType mediaType) throws Exception {

    final String table = "testCreateFactTableWithMultipleUpdatePeriods";
    String prevDb = getCurrentDatabase(mediaType);
    final String DB = dbPFX + "testCreateFactTableWithMultipleUpdatePeriods_DB" + mediaType.getSubtype();
    createDatabase(DB, mediaType);//  w  ww  . j  a  v  a2s. c  o  m
    setCurrentDatabase(DB, mediaType);
    createStorage("S1", mediaType);
    try {
        final XCube cube = createTestCube("testCube");
        target().path("metastore").path("cubes").queryParam("sessionid", lensSessionId).request(mediaType)
                .post(Entity.entity(new GenericEntity<JAXBElement<XCube>>(cubeObjectFactory.createXCube(cube)) {
                }, mediaType), APIResult.class);
        XFactTable f = createFactTable(table);
        String[] tables = new String[] { "testTable1", "testTable2", "testTable3" };
        String[] updatePeriods = new String[] { "HOURLY", "DAILY", "MONTHLY" };
        f.getStorageTables().getStorageTable()
                .add(createStorageTblWithMultipleTableDescriptors("S1", tables, updatePeriods));
        APIResult result = target().path("metastore").path("facts").queryParam("sessionid", lensSessionId)
                .request(mediaType)
                .post(Entity.entity(new GenericEntity<JAXBElement<XFact>>(cubeObjectFactory.createXFact(f)) {
                }, mediaType), APIResult.class);
        assertSuccess(result);

        StringList factNames = target().path("metastore/facts").queryParam("sessionid", lensSessionId)
                .request(mediaType).get(StringList.class);
        assertTrue(factNames.getElements().contains(table.toLowerCase()));

        // Get the created tables
        JAXBElement<XFact> gotFactElement = target().path("metastore/facts").path(table)
                .queryParam("sessionid", lensSessionId).request(mediaType)
                .get(new GenericType<JAXBElement<XFact>>() {
                });
        XFactTable gotFact = (XFactTable) gotFactElement.getValue();
        assertTrue(gotFact.getName().equalsIgnoreCase(table));
        assertEquals(gotFact.getWeight(), 10.0);

        // Check for the created tables per update period.
        List<XUpdatePeriodTableDescriptor> updatePeriodTableDescriptor = gotFact.getStorageTables()
                .getStorageTable().get(0).getUpdatePeriods().getUpdatePeriodTableDescriptor();
        assertEquals(updatePeriodTableDescriptor.size(), 3);

        CubeFactTable cf = JAXBUtils.cubeFactFromFactTable(gotFact);

        Map<UpdatePeriod, String> updatePeriodTablePrefixMap = cf.getStoragePrefixUpdatePeriodMap().get("S1");
        for (Map.Entry entry : updatePeriodTablePrefixMap.entrySet()) {
            assertEquals(entry.getValue(), entry.getKey() + "_S1");
        }
        // Do some changes to test update
        cf.alterWeight(20.0);
        cf.alterColumn(new FieldSchema("c2", "double", "changed to double"));

        XFactTable update = JAXBUtils.factTableFromCubeFactTable(cf);
        XStorageTableElement s1Tbl = createStorageTblWithMultipleTableDescriptors("S1",
                new String[] { tables[0], tables[1] }, new String[] { updatePeriods[0], updatePeriods[1] });
        update.getStorageTables().getStorageTable().add(s1Tbl);
        // Update
        result = target().path("metastore").path("facts").path(table).queryParam("sessionid", lensSessionId)
                .request(mediaType).put(Entity
                        .entity(new GenericEntity<JAXBElement<XFact>>(cubeObjectFactory.createXFact(update)) {
                        }, mediaType), APIResult.class);
        assertSuccess(result);

        // Get the updated table
        gotFactElement = target().path("metastore/facts").path(table).queryParam("sessionid", lensSessionId)
                .request(mediaType).get(new GenericType<JAXBElement<XFact>>() {
                });
        gotFact = (XFactTable) gotFactElement.getValue();
        CubeFactTable ucf = JAXBUtils.cubeFactFromFactTable(gotFact);
        assertEquals(ucf.weight(), 20.0);
        assertTrue(ucf.getUpdatePeriods().get("S1").contains(HOURLY));
        assertTrue(ucf.getUpdatePeriods().get("S1").contains(DAILY));
        assertFalse(ucf.getUpdatePeriods().get("S1").contains(MONTHLY));

        // Add partitions
        final Date partDate = new Date();
        XPartition xp = createPartition(table, partDate);
        APIResult partAddResult = target().path("metastore/facts/").path(table).path("storages/S1/partition")
                .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity(
                        new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) {
                        }, mediaType), APIResult.class);
        assertSuccess(partAddResult);

        // add same should fail
        partAddResult = target().path("metastore/facts/").path(table).path("storages/S1/partition")
                .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity(
                        new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) {
                        }, mediaType), APIResult.class);
        assertEquals(partAddResult.getStatus(), Status.FAILED);

        xp.setLocation(xp.getLocation() + "/a/b/c");
        APIResult partUpdateResult = target().path("metastore/facts/").path(table).path("storages/S1/partition")
                .queryParam("sessionid", lensSessionId).request(mediaType).put(Entity.entity(
                        new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) {
                        }, mediaType), APIResult.class);
        assertSuccess(partUpdateResult);

        JAXBElement<XPartitionList> partitionsElement = target().path("metastore/facts").path(table)
                .path("storages/S1/partitions").queryParam("sessionid", lensSessionId)
                .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType)
                .get(new GenericType<JAXBElement<XPartitionList>>() {
                });

        //Getting partitions without filter will throw an error.
        Response res = target().path("metastore/facts").path(table).path("storages/S1/partitions")
                .queryParam("sessionid", lensSessionId).request(mediaType).get();
        assertEquals(res.getStatus(), 400);
        assertEquals(res.readEntity(String.class), "Partition filter can not be null or empty");

        XPartitionList partitions = partitionsElement.getValue();
        assertNotNull(partitions);
        assertEquals(partitions.getPartition().size(), 1);
        XPartition readPartition = partitions.getPartition().get(0);
        assertEquals(readPartition.getLocation(), xp.getLocation());
        assertEquals(readPartition.getTimePartitionSpec(), xp.getTimePartitionSpec());
        assertEquals(readPartition.getNonTimePartitionSpec(), xp.getNonTimePartitionSpec());
        assertNotNull(readPartition.getFullPartitionSpec());
        XTimePartSpecElement timePartSpec = readPartition.getTimePartitionSpec().getPartSpecElement().iterator()
                .next();
        XPartSpecElement fullPartSpec = readPartition.getFullPartitionSpec().getPartSpecElement().iterator()
                .next();
        assertEquals(timePartSpec.getKey(), fullPartSpec.getKey());
        assertEquals(UpdatePeriod.valueOf(xp.getUpdatePeriod().name())
                .format(JAXBUtils.getDateFromXML(timePartSpec.getValue())), fullPartSpec.getValue());
        DateTime date = target().path("metastore/cubes").path("testCube").path("latestdate")
                .queryParam("timeDimension", "dt").queryParam("sessionid", lensSessionId).request(mediaType)
                .get(DateTime.class);

        partDate.setMinutes(0);
        partDate.setSeconds(0);
        partDate.setTime(partDate.getTime() - partDate.getTime() % 1000);
        assertEquals(date.getDate(), partDate);
        // add two partitions, one of them already added. result should be partial
        XPartitionList parts = new XPartitionList();
        parts.getPartition().add(xp);
        parts.getPartition().add(createPartition(table, DateUtils.addHours(partDate, 1)));
        partAddResult = target().path("metastore/facts/").path(table).path("storages/S1/partitions")
                .queryParam("sessionid", lensSessionId).request(mediaType)
                .post(Entity.entity(new GenericEntity<JAXBElement<XPartitionList>>(
                        cubeObjectFactory.createXPartitionList(parts)) {
                }, mediaType), APIResult.class);
        assertEquals(partAddResult.getStatus(), Status.PARTIAL);

        // Drop the partitions
        APIResult dropResult = target().path("metastore/facts").path(table).path("storages/S1/partitions")
                .queryParam("sessionid", lensSessionId).request(mediaType).delete(APIResult.class);

        assertSuccess(dropResult);

        // Verify partition was dropped
        partitionsElement = target().path("metastore/facts").path(table).path("storages/S1/partitions")
                .queryParam("sessionid", lensSessionId)
                .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType)
                .get(new GenericType<JAXBElement<XPartitionList>>() {
                });

        partitions = partitionsElement.getValue();
        assertNotNull(partitions);
        assertEquals(partitions.getPartition().size(), 0);
        // add null in batch
        Response resp = target().path("metastore/facts/").path(table).path("storages/S1/partitions")
                .queryParam("sessionid", lensSessionId).request(mediaType).post(null);
        Assert.assertEquals(resp.getStatus(), 400);

        // Drop the cube
        WebTarget target = target().path("metastore").path("cubes").path("testCube");
        result = target.queryParam("sessionid", lensSessionId).request(mediaType).delete(APIResult.class);
        assertSuccess(result);
    } finally {
        setCurrentDatabase(prevDb, mediaType);
        dropDatabase(DB, mediaType);
    }
}

From source file:org.apache.lens.server.metastore.TestMetastoreService.java

@SuppressWarnings("deprecation")
@Test(dataProvider = "mediaTypeData")
public void testFactStoragePartitions(MediaType mediaType) throws Exception {
    final String table = "testFactStoragePartitions";
    final String DB = dbPFX + "testFactStoragePartitions_DB" + mediaType.getSubtype();
    String prevDb = getCurrentDatabase(mediaType);
    createDatabase(DB, mediaType);//from   w ww .j a v  a 2s.c  o m
    setCurrentDatabase(DB, mediaType);
    createStorage("S1", mediaType);
    createStorage("S2", mediaType);

    try {

        final XCube cube = createTestCube("testCube");
        target().path("metastore").path("cubes").queryParam("sessionid", lensSessionId).request(mediaType)
                .post(Entity.entity(new GenericEntity<JAXBElement<XCube>>(cubeObjectFactory.createXCube(cube)) {
                }, mediaType), APIResult.class);

        XFactTable f = createFactTable(table);
        f.getStorageTables().getStorageTable().add(createStorageTblElement("S1", table, "HOURLY"));
        f.getStorageTables().getStorageTable().add(createStorageTblElement("S2", table, "DAILY"));
        f.getStorageTables().getStorageTable().add(createStorageTblElement("S2", table, "HOURLY"));
        APIResult result = target().path("metastore").path("facts").queryParam("sessionid", lensSessionId)
                .request(mediaType)
                .post(Entity.entity(new GenericEntity<JAXBElement<XFact>>(cubeObjectFactory.createXFact(f)) {
                }, mediaType), APIResult.class);
        assertSuccess(result);

        APIResult partAddResult;
        // Add null partition
        Response resp = target().path("metastore/facts/").path(table).path("storages/S2/partition")
                .queryParam("sessionid", lensSessionId).request(mediaType).post(null);
        Assert.assertEquals(resp.getStatus(), 400);

        // Add wrong partition
        final Date partDate = new Date();
        XPartition xp2 = createPartition(table, partDate);
        xp2.getTimePartitionSpec().getPartSpecElement()
                .add(createTimePartSpecElement(partDate, "non_existant_time_part"));
        Response response = target().path("metastore/facts/").path(table).path("storages/S2/partition")
                .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity(
                        new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp2)) {
                        }, mediaType));
        assertEquals(response.getStatus(), 400);
        partAddResult = response.readEntity(APIResult.class);
        assertEquals(partAddResult.getStatus(), Status.FAILED);
        assertEquals(partAddResult.getMessage(),
                "No timeline found for fact=testFactStoragePartitions, storage=S2, "
                        + "update period=HOURLY, partition column=non_existant_time_part.");
        // Add a partition
        XPartition xp = createPartition(table, partDate);
        partAddResult = target().path("metastore/facts/").path(table).path("storages/S2/partition")
                .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity(
                        new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) {
                        }, mediaType), APIResult.class);
        assertSuccess(partAddResult);

        // add same should fail
        partAddResult = target().path("metastore/facts/").path(table).path("storages/S2/partition")
                .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity(
                        new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) {
                        }, mediaType), APIResult.class);
        assertEquals(partAddResult.getStatus(), Status.FAILED);

        xp.setLocation(xp.getLocation() + "/a/b/c");
        APIResult partUpdateResult = target().path("metastore/facts/").path(table).path("storages/S2/partition")
                .queryParam("sessionid", lensSessionId)
                .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType)
                .put(Entity.entity(
                        new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) {
                        }, mediaType), APIResult.class);
        assertSuccess(partUpdateResult);

        JAXBElement<XPartitionList> partitionsElement = target().path("metastore/facts").path(table)
                .path("storages/S2/partitions").queryParam("sessionid", lensSessionId)
                .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType)
                .get(new GenericType<JAXBElement<XPartitionList>>() {
                });

        XPartitionList partitions = partitionsElement.getValue();
        assertNotNull(partitions);
        assertEquals(partitions.getPartition().size(), 1);
        XPartition readPartition = partitions.getPartition().get(0);
        assertEquals(readPartition.getLocation(), xp.getLocation());
        assertEquals(readPartition.getTimePartitionSpec(), xp.getTimePartitionSpec());
        assertEquals(readPartition.getNonTimePartitionSpec(), xp.getNonTimePartitionSpec());
        assertNotNull(readPartition.getFullPartitionSpec());
        XTimePartSpecElement timePartSpec = readPartition.getTimePartitionSpec().getPartSpecElement().iterator()
                .next();
        XPartSpecElement fullPartSpec = readPartition.getFullPartitionSpec().getPartSpecElement().iterator()
                .next();
        assertEquals(timePartSpec.getKey(), fullPartSpec.getKey());
        assertEquals(UpdatePeriod.valueOf(xp.getUpdatePeriod().name())
                .format(JAXBUtils.getDateFromXML(timePartSpec.getValue())), fullPartSpec.getValue());
        DateTime date = target().path("metastore/cubes").path("testCube").path("latestdate")
                .queryParam("timeDimension", "dt").queryParam("sessionid", lensSessionId).request(mediaType)
                .get(DateTime.class);

        partDate.setMinutes(0);
        partDate.setSeconds(0);
        partDate.setTime(partDate.getTime() - partDate.getTime() % 1000);
        assertEquals(date.getDate(), partDate);
        // add two partitions, one of them already added. result should be partial
        XPartitionList parts = new XPartitionList();
        parts.getPartition().add(xp);
        parts.getPartition().add(createPartition(table, DateUtils.addHours(partDate, 1)));
        partAddResult = target().path("metastore/facts/").path(table).path("storages/S2/partitions")
                .queryParam("sessionid", lensSessionId).request(mediaType)
                .post(Entity.entity(new GenericEntity<JAXBElement<XPartitionList>>(
                        cubeObjectFactory.createXPartitionList(parts)) {
                }, mediaType), APIResult.class);
        assertEquals(partAddResult.getStatus(), Status.PARTIAL);

        // Drop the partitions
        APIResult dropResult = target().path("metastore/facts").path(table).path("storages/S2/partitions")
                .queryParam("sessionid", lensSessionId).request(mediaType).delete(APIResult.class);

        assertSuccess(dropResult);

        // Verify partition was dropped
        partitionsElement = target().path("metastore/facts").path(table).path("storages/S2/partitions")
                .queryParam("sessionid", lensSessionId)
                .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType)
                .get(new GenericType<JAXBElement<XPartitionList>>() {
                });

        partitions = partitionsElement.getValue();
        assertNotNull(partitions);
        assertEquals(partitions.getPartition().size(), 0);
        // add null in batch
        resp = target().path("metastore/facts/").path(table).path("storages/S2/partitions")
                .queryParam("sessionid", lensSessionId).request(mediaType).post(null);
        Assert.assertEquals(resp.getStatus(), 400);

        // Try adding in batch, but to a wrong endpoint
        resp = target().path("metastore/facts/").path(table).path("storages/S2/partition")
                .queryParam("sessionid", lensSessionId).request(mediaType)
                .post(Entity.entity(new GenericEntity<JAXBElement<XPartitionList>>(
                        cubeObjectFactory.createXPartitionList(toXPartitionList(xp))) {
                }, mediaType));
        assertXMLError(resp, mediaType);

        // Try adding in batch, but provide just an XPartition
        resp = target().path("metastore/facts/").path(table).path("storages/S2/partitions")
                .queryParam("sessionid", lensSessionId).request(mediaType).post(Entity.entity(
                        new GenericEntity<JAXBElement<XPartition>>(cubeObjectFactory.createXPartition(xp)) {
                        }, mediaType));
        if (mediaType.equals(MediaType.APPLICATION_XML_TYPE)) {
            assertXMLError(resp, mediaType);
        } else {
            // for json input, XPartitionList is getting created
            assertEquals(resp.getStatus(), 200);
        }

        // Try adding in batch with one partition being wrong wrt partition column.
        response = target().path("metastore/facts/").path(table).path("storages/S2/partitions")
                .queryParam("sessionid", lensSessionId).request(mediaType)
                .post(Entity.entity(new GenericEntity<JAXBElement<XPartitionList>>(
                        cubeObjectFactory.createXPartitionList(toXPartitionList(xp2))) {
                }, mediaType));
        assertEquals(response.getStatus(), 400);
        partAddResult = response.readEntity(APIResult.class);
        assertEquals(partAddResult.getStatus(), Status.FAILED);
        assertEquals(partAddResult.getMessage(),
                "No timeline found for fact=testFactStoragePartitions, storage=S2, "
                        + "update period=HOURLY, partition column=non_existant_time_part.");
        // Add in batch
        partAddResult = target().path("metastore/facts/").path(table).path("storages/S2/partitions")
                .queryParam("sessionid", lensSessionId).request(mediaType)
                .post(Entity.entity(new GenericEntity<JAXBElement<XPartitionList>>(
                        cubeObjectFactory.createXPartitionList(toXPartitionList(xp))) {
                }, mediaType), APIResult.class);
        assertSuccess(partAddResult);

        // Verify partition was added
        partitionsElement = target().path("metastore/facts").path(table).path("storages/S2/partitions")
                .queryParam("sessionid", lensSessionId)
                .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType)
                .get(new GenericType<JAXBElement<XPartitionList>>() {
                });

        partitions = partitionsElement.getValue();
        assertNotNull(partitions);
        assertEquals(partitions.getPartition().size(), 1);

        // Drop again by values
        String[] val = new String[] { HOURLY.format(partDate) };
        dropResult = target().path("metastore/facts").path(table).path("storages/S2/partition")
                .queryParam("values", StringUtils.join(val, ",")).queryParam("sessionid", lensSessionId)
                .request(mediaType).delete(APIResult.class);
        assertSuccess(dropResult);

        // Verify partition was dropped
        partitionsElement = target().path("metastore/facts").path(table).path("storages/S2/partitions")
                .queryParam("sessionid", lensSessionId)
                .queryParam("filter", "dt='" + HOURLY.format(partDate) + "'").request(mediaType)
                .get(new GenericType<JAXBElement<XPartitionList>>() {
                });

        partitions = partitionsElement.getValue();
        assertNotNull(partitions);
        assertEquals(partitions.getPartition().size(), 0);
    } finally {
        setCurrentDatabase(prevDb, mediaType);
        dropDatabase(DB, mediaType);
    }
}