Example usage for java.util GregorianCalendar setTime

List of usage examples for java.util GregorianCalendar setTime

Introduction

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

Prototype

public final void setTime(Date date) 

Source Link

Document

Sets this Calendar's time with the given Date.

Usage

From source file:mekhq.campaign.mission.Contract.java

/**
 * Only do this at the time the contract is set up, otherwise amounts may change after
 * the ink is signed, which is a no-no.//from   w ww  . j  a v  a2s  . co  m
 * @param c
 */
public void calculateContract(Campaign c) {

    //calculate base amount
    baseAmount = (long) (paymentMultiplier * getLength() * c.getContractBase());

    //calculate overhead
    switch (overheadComp) {
    case OH_HALF:
        overheadAmount = (long) (0.5 * c.getOverheadExpenses() * getLength());
        break;
    case OH_FULL:
        overheadAmount = 1 * c.getOverheadExpenses() * getLength();
        break;
    default:
        overheadAmount = 0;
    }

    //calculate support amount
    if (c.getCampaignOptions().usePeacetimeCost() && c.getCampaignOptions().getUnitRatingMethod()
            .equals(mekhq.campaign.rating.UnitRatingMethod.CAMPAIGN_OPS)) {
        supportAmount = (long) ((straightSupport / 100.0) * c.getPeacetimeCost() * getLength());
    } else {
        long maintCosts = 0;
        for (Unit u : c.getUnits()) {
            if (u.getEntity() instanceof Infantry && !(u.getEntity() instanceof BattleArmor)) {
                continue;
            }
            maintCosts += u.getWeeklyMaintenanceCost();
        }
        maintCosts *= 4;
        supportAmount = (long) ((straightSupport / 100.0) * maintCosts * getLength());
    }

    //calculate transportation costs
    if (null != getPlanet()) {
        JumpPath jumpPath = c.calculateJumpPath(c.getCurrentPlanet(), getPlanet());

        // FM:Mercs transport payments take into account owned transports and do not use CampaignOps dropship costs.
        // CampaignOps doesn't care about owned transports and does use its own dropship costs.
        boolean campaignOps = c.getCampaignOptions().useEquipmentContractBase();
        transportAmount = (long) ((transportComp / 100.0) * 2 * c.calculateCostPerJump(campaignOps, campaignOps)
                * jumpPath.getJumps());
    }

    //calculate transit amount for CO
    if (c.getCampaignOptions().usePeacetimeCost() && c.getCampaignOptions().getUnitRatingMethod()
            .equals(mekhq.campaign.rating.UnitRatingMethod.CAMPAIGN_OPS)) {
        //contract base * transport period * reputation * employer modifier
        transitAmount = (long) (c.getContractBase()
                * (((c.calculateJumpPath(c.getCurrentPlanet(), getPlanet()).getJumps()) * 2) / 4)
                * (c.getUnitRatingMod() * .2 + .5) * 1.2);
    } else {
        transitAmount = 0;
    }

    signingAmount = (long) ((signBonus / 100.0)
            * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount));

    advanceAmount = (long) ((advancePct / 100.0)
            * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount));

    if (mrbcFee) {
        feeAmount = (long) (0.05
                * (baseAmount + overheadAmount + transportAmount + transitAmount + supportAmount));
    } else {
        feeAmount = 0;
    }

    // only adjust the start date for travel if the start date is currently null
    boolean adjustStartDate = false;
    if (null == startDate) {
        startDate = c.getCalendar().getTime();
        adjustStartDate = true;
    }
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(startDate);
    if (adjustStartDate && null != c.getPlanet(planetId)) {
        int days = (int) Math.ceil(c.calculateJumpPath(c.getCurrentPlanet(), getPlanet())
                .getTotalTime(Utilities.getDateTimeDay(cal), c.getLocation().getTransitTime()));
        while (days > 0) {
            cal.add(Calendar.DAY_OF_YEAR, 1);
            days--;
        }
        startDate = cal.getTime();
    }
    int months = getLength();
    while (months > 0) {
        cal.add(Calendar.MONTH, 1);
        months--;
    }
    endDate = cal.getTime();
}

From source file:org.alfresco.opencmis.dictionary.AbstractTypeDefinitionWrapper.java

@SuppressWarnings("unchecked")
private <T> T convertValueFromString(String value, PropertyType datatype) {
    if (value == null) {
        return null;
    }//from  w  ww. jav a  2 s  . co m

    try {
        switch (datatype) {
        case BOOLEAN:
            return (T) Boolean.valueOf(value);
        case DATETIME:
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(ISO8601DateFormat.parse(value));
            return (T) cal;
        case DECIMAL:
            return (T) new BigDecimal(value);
        case HTML:
            return (T) value;
        case ID:
            return (T) value;
        case INTEGER:
            return (T) new BigInteger(value);
        case STRING:
            return (T) value;
        case URI:
            return (T) value;
        default:
            ;
        }
    } catch (Exception e) {
        logger.error("Failed to convert value " + value + " to " + datatype, e);
        return null;
    }

    throw new RuntimeException("Unknown datatype! Spec change?");
}

From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java

public void loadTextData(File file) {
    try {//ww  w. jav  a  2 s  .  c  o m
        RandomAccessFile in = new RandomAccessFile(file, "r");

        // Skip header
        in.readLine();
        in.readLine();
        in.readLine();

        // Skip Subject Information
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String startTimeInput = in.readLine();
        String commentsInput = in.readLine();

        String data = in.readLine();
        while (!data.startsWith("2) System Configuration")) {
            commentsInput += data;
            data = in.readLine();
        }
        // System configuration

        // in.readLine();
        in.readLine();
        String timeCounstantInput = in.readLine();
        String cameraGainInput = in.readLine();
        String exposureTimeInput = in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String resolutionInput = in.readLine();

        // Time Data
        in.readLine();
        String timeDataInput = in.readLine();
        String totalImagesInput = in.readLine();
        in.readLine();
        in.readLine();
        // in.readLine();
        // System.out.println(in.readLine());
        // in.readLine();

        // Parse important Size

        high = (new Scanner(resolutionInput.split(":")[1])).nextInt();
        wide = (new Scanner(resolutionInput.split(",")[1])).nextInt();
        int tot = 1;
        try {
            tot = (new Scanner(totalImagesInput.split(":")[1])).nextInt();
        } catch (Exception e) {

        }
        System.out.println(wide + "," + high);
        // Parse timeInformation
        SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss (dd/MM/yy)");
        Date startTime = null;
        try {
            startTime = format.parse(startTimeInput.split(": ")[1]);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String[] frameTimeData = timeDataInput.split("information:")[1].split(",");

        Date[] timeInfo = new Date[tot];
        for (int i = 0; i < frameTimeData.length - 1; i++) {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(startTime);
            String dat = (frameTimeData[i]);
            String[] timeVals = dat.split(":");

            int hour = Integer.parseInt(StringOperations.removeNonNumber(timeVals[0]));
            int min = Integer.parseInt(StringOperations.removeNonNumber(timeVals[1]));
            int sec = Integer.parseInt(StringOperations.removeNonNumber(timeVals[2]));
            int msec = Integer.parseInt(StringOperations.removeNonNumber(timeVals[3]));

            cal.add(Calendar.HOUR_OF_DAY, hour);
            cal.add(Calendar.MINUTE, min);
            cal.add(Calendar.SECOND, sec);
            cal.add(Calendar.MILLISECOND, msec);
            timeInfo[i] = cal.getTime();
        }

        // Parse Image Data
        /*
         * Close Random access file and switch to scanner first store pos
         * then move to correct point.
         */
        long pos = in.getFilePointer();
        in.close();

        FileInputStream fIn = new FileInputStream(file);
        fIn.skip(pos);

        BufferedInputStream bIn = new BufferedInputStream(fIn);
        Scanner sIn = new Scanner(bIn);

        short[][][] holder = new short[tot][wide][high];

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        StatusBarPanel stat = new StatusBarPanel();
        stat.setMaximum(high);
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(stat, BorderLayout.CENTER);
        f.setSize(200, 60);
        f.setVisible(true);

        for (int i = 0; i < tot; i++) {
            // Skip over the heading values
            stat.setStatusMessage("Loading " + i + " of " + tot);
            sIn.useDelimiter("\n");
            sIn.next();
            sIn.next();
            sIn.next();
            if (i != 0) {
                sIn.next();
            }
            sIn.reset();
            for (int y = 0; y < high; y++) {
                stat.setValue(y);
                sIn.nextInt();
                for (int x = 0; x < wide; x++) {
                    holder[i][x][y] = sIn.nextShort();
                }

            }
            addData(timeInfo[i], holder[i]);
        }

        // FrameFactroy.getFrame(new DynamicRangeImage(data[0]));
        // Start Image Data

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.jahia.services.importexport.FilesAclImportHandler.java

private boolean setPropertyField(ExtendedNodeType baseType, String localName, JCRNodeWrapper node,
        String propertyName, String value) throws RepositoryException {
    if (propertyName == null || "#skip".equals(propertyName)) {
        return false;
    }//from  www. j a  v  a  2  s .  com
    JCRNodeWrapper parent = node;
    String mixinType = null;
    if (propertyName.contains("|")) {
        mixinType = StringUtils.substringBefore(propertyName, "|");
        propertyName = StringUtils.substringAfter(propertyName, "|");
    }
    if (StringUtils.contains(propertyName, "/")) {
        String parentPath = StringUtils.substringBeforeLast(propertyName, "/");
        if (parent.hasNode(parentPath)) {
            parent = parent.getNode(parentPath);
        }
        propertyName = StringUtils.substringAfterLast(propertyName, "/");
    }
    parent = checkoutNode(parent);
    if (!StringUtils.isEmpty(mixinType) && !parent.isNodeType(mixinType)) {
        parent.addMixin(mixinType);
    }

    ExtendedPropertyDefinition propertyDefinition = null;
    propertyDefinition = parent.getApplicablePropertyDefinition(propertyName);
    if (propertyDefinition == null) {
        return false;

    }
    if (propertyDefinition.isProtected()) {
        // System.out.println("protected : " + propertyName);
        return false;
    }
    Node n = parent;

    // System.out.println("setting " + propertyName);

    if (value != null && value.length() != 0 && !value.equals("<empty>")) {
        switch (propertyDefinition.getRequiredType()) {
        case PropertyType.DATE:
            GregorianCalendar cal = new GregorianCalendar();
            try {
                DateFormat df = new SimpleDateFormat(ImportExportService.DATE_FORMAT);
                Date d = df.parse(value);
                cal.setTime(d);
                n.setProperty(propertyName, cal);
            } catch (java.text.ParseException e) {
                logger.error(e.getMessage(), e);
            }
            break;

        default:
            switch (propertyDefinition.getSelector()) {
            case SelectorType.CATEGORY: {
                String[] cats = Patterns.COMMA.split(value);
                List<Value> values = new ArrayList<Value>();
                for (int i = 0; i < cats.length; i++) {
                    String cat = cats[i];
                    Query q = session.getWorkspace().getQueryManager()
                            .createQuery("select * from [jnt:category] as cat where NAME(cat) = '"
                                    + JCRContentUtils.sqlEncode(cat) + "'", Query.JCR_SQL2);
                    NodeIterator ni = q.execute().getNodes();
                    if (ni.hasNext()) {
                        values.add(session.getValueFactory().createValue(ni.nextNode()));
                    }
                }
                n.setProperty(propertyName, values.toArray(new Value[values.size()]));
                break;
            }
            case SelectorType.RICHTEXT: {
                n.setProperty(propertyName, value);
                break;
            }
            default: {
                String[] vcs = propertyDefinition.getValueConstraints();
                List<String> constraints = Arrays.asList(vcs);
                if (!propertyDefinition.isMultiple()) {
                    if (value.startsWith("<jahia-resource")) {
                        value = ResourceBundleMarker.parseMarkerValue(value).getResourceKey();
                        if (value.startsWith(propertyDefinition.getResourceBundleKey())) {
                            value = value.substring(propertyDefinition.getResourceBundleKey().length() + 1);
                        }
                    }
                    value = baseType != null && mapping != null
                            ? mapping.getMappedPropertyValue(baseType, localName, value)
                            : value;
                    if (constraints.isEmpty() || constraints.contains(value)) {
                        try {
                            n.setProperty(propertyName, value);
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                } else {
                    String[] strings = Patterns.TRIPPLE_DOLLAR.split(value);
                    List<Value> values = new ArrayList<Value>();
                    for (int i = 0; i < strings.length; i++) {
                        String string = strings[i];

                        if (string.startsWith("<jahia-resource")) {
                            string = ResourceBundleMarker.parseMarkerValue(string).getResourceKey();
                            if (string.startsWith(propertyDefinition.getResourceBundleKey())) {
                                string = string
                                        .substring(propertyDefinition.getResourceBundleKey().length() + 1);
                            }
                        }
                        value = baseType != null ? mapping.getMappedPropertyValue(baseType, localName, value)
                                : value;
                        if (constraints.isEmpty() || constraints.contains(value)) {
                            values.add(new ValueImpl(string, propertyDefinition.getRequiredType()));
                        }
                    }
                    ;
                    n.setProperty(propertyName, values.toArray(new Value[values.size()]));
                }
                break;
            }
            }
        }
    } else {
        return false;
    }

    return true;
}

From source file:org.apache.unomi.services.services.ProfileServiceImpl.java

public Session loadSession(String sessionId, Date dateHint) {
    Session s = persistenceService.load(sessionId, dateHint, Session.class);
    if (s == null && dateHint != null) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(dateHint);
        if (gc.get(Calendar.DAY_OF_MONTH) == 1) {
            gc.add(Calendar.DAY_OF_MONTH, -1);
            s = persistenceService.load(sessionId, gc.getTime(), Session.class);
        }//from   w w w  .  j  av  a2 s  .c  o m
    }
    return s;
}

From source file:io.getlime.security.powerauth.soap.spring.client.PowerAuthServiceClient.java

/**
 * Convert date to XMLGregorianCalendar/*  w  w  w .  j a  v a2s  .  c om*/
 * @param date Date to be converted.
 * @return A new instance of {@link XMLGregorianCalendar}.
 * @throws DatatypeConfigurationException
 */
private XMLGregorianCalendar calendarWithDate(Date date) {
    try {
        GregorianCalendar c = new GregorianCalendar();
        c.setTime(date);
        return DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    } catch (DatatypeConfigurationException e) {
        // Unless there is a terrible configuration error, this should not happen
        e.printStackTrace();
    }
    return null;
}

From source file:org.socraticgrid.displayalert.DisplayAlertMessages.java

/**
 * Create one of the responses to be returned by getMessages
 * /*w  w  w  . ja v a 2  s  .c  o m*/
 * 
 * @param ticket AlertTicket
 * @param contact AlertContact record corresponding to ticket
 * @param isArch is the ticket archived or not
 * @param location location passed in request
 * @return response object to be added to return
 * @throws DatatypeConfigurationException 
 */
private GetMessageResponse createAlertResponse(AlertTicket ticket, AlertContact contact, boolean isArch,
        String location) throws DatatypeConfigurationException {
    GetMessagesResponseType.GetMessageResponse response = new GetMessagesResponseType.GetMessageResponse();

    response.setMessageType("Alert");

    //--------------------------
    // Set ARCHIVED attribute
    //--------------------------
    if (isArch) {
        response.setLocation("Archive");
    } else {
        response.setLocation(location);
    }

    //--------------------------
    // Set READ/UNREAD attribute
    //--------------------------
    if (checkRead(ticket, contact.getUserId())) {
        response.setMessageStatus("Read");
    } else {
        response.setMessageStatus("Unread");
    }

    //        System.out.println("===> TICKET ID: " + ticket.getTicketId()
    //                          +"     DESC: " + ticket.getDescription());

    //--------------------------
    response.setDescription(ticket.getDescription());
    response.setFrom(contact.getUserName());
    response.setTitle(ticket.getDescription());
    //--------------------------
    // Temporarily setting task % from DSA in ptFMPSSN column
    //--------------------------
    if (!CommonUtil.strNullorEmpty(ticket.getPtFMPSSN())) {
        try {
            response.setTasksComplete(Integer.parseInt(ticket.getPtFMPSSN()));
        } catch (NumberFormatException nfe) {
            response.setTasksComplete(0);
        }
    }

    //--------------------------
    // Set MSG DATE
    //--------------------------
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(ticket.getAlertTimestamp());
    XMLGregorianCalendar xgcDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
    response.setMessageDate(xgcDate);

    //--------------------------
    String msgId = ticket.getTicketId().toString();
    response.setMessageId(msgId);

    //--------------------------
    // Check the starred/flagged label in the status table
    //--------------------------
    for (AlertStatus status : ticket.getStatus()) {
        if (!CommonUtil.strNullorEmpty(contact.getUserId())) {
            if (contact.getUserId().equals(status.getUserId()) && status.isFlagged()) {
                response.getLabels().add("Starred");
            }
        }
    }
    //--------------------------
    response.setPriority(ticket.getPriority());
    response.setSuccessStatus(true);
    response.setFrom(ticket.getAlertOriginator());
    //response.setTasksComplete(ticket.getActionHistory().size());
    response.setTasksCount(ticket.getActionHistory().size());

    return response;
}

From source file:org.openvpms.esci.adapter.map.order.OrderMapperImpl.java

/**
 * Maps an <em>act.supplierOrder</em> to an UBL order.
 *
 * @param order the <em>act.supplierOrder</em> to map
 * @return the corresponding UBL order/*from  www.j  a  v a  2s  .  c o  m*/
 * @throws ESCIAdapterException      for mapping errors
 * @throws ArchetypeServiceException for any archetype service error
 */
public Order map(FinancialAct order) {
    Order result = new Order();
    Currency currency = getCurrency();

    UBLVersionIDType version = UBLHelper.initID(new UBLVersionIDType(), "2.0");
    IDType id = UBLHelper.createID(order.getId());
    CopyIndicatorType copyIndicator = getCopyIndicatorType(false);

    GregorianCalendar startTime = new GregorianCalendar();
    startTime.setTime(order.getActivityStartTime());
    IssueDateType issueDate = UBLHelper.createIssueDate(startTime, datatypeFactory);
    IssueTimeType issueTime = UBLHelper.createIssueTime(startTime, datatypeFactory);

    ActBean bean = factory.createActBean(order);
    Entity author = bean.getNodeParticipant("author");
    Party stockLocation = (Party) bean.getNodeParticipant("stockLocation");
    Party location = getLocation(stockLocation);

    Party supplier = (Party) bean.getNodeParticipant("supplier");
    EntityRelationship supplierStockLocation = supplierRules.getSupplierStockLocation(supplier, stockLocation);
    if (supplierStockLocation == null) {
        throw new ESCIAdapterException(ESCIAdapterMessages.ESCINotConfigured(supplier, stockLocation));
    }
    String contactName = (author != null) ? author.getName() : null;
    CustomerPartyType customerParty = getCustomer(contactName, location, stockLocation, supplierStockLocation);
    SupplierPartyType supplierParty = getSupplier(supplier);

    TaxTotalType taxTotal = getTaxTotal(order, currency);
    MonetaryTotalType total = getMonetaryTotal(order, currency);

    result.setUBLVersionID(version);
    result.setID(id);
    result.setCopyIndicator(copyIndicator);
    result.setIssueDate(issueDate);
    result.setIssueTime(issueTime);
    result.setBuyerCustomerParty(customerParty);
    result.setSellerSupplierParty(supplierParty);
    result.getTaxTotal().add(taxTotal);
    result.setAnticipatedMonetaryTotal(total);

    for (Act item : bean.getNodeActs("items")) {
        OrderLineType line = getOrderLine(item, supplier, currency);
        result.getOrderLine().add(line);
    }
    return result;
}

From source file:org.opendatakit.aggregate.externalservice.REDCapServer.java

@Override
protected void insertData(Submission submission, CallingContext cc) throws ODKExternalServiceException {

    try {//from w  w w  .ja va2 s  .c o  m
        // an empty map to hold our values
        String study_id = null;

        // create a hash to hold the blobs for later processing
        Map<String, BlobSubmissionType> blobs = new HashMap<String, BlobSubmissionType>();

        StringBuilder b = new StringBuilder();

        Map<FormElementModel, SubmissionValue> valuesMap = submission.getSubmissionValuesMap();

        for (FormElementModel element : valuesMap.keySet()) {
            SubmissionValue value = valuesMap.get(element);
            if (value == null) {
                continue;
            }
            if (element.isMetadata()) {
                // handle metadata specially
            } else {
                switch (element.getElementType()) {
                case METADATA:
                    // This keeps lint warnings down...
                    break;
                case STRING: {
                    StringSubmissionType str = (StringSubmissionType) value;
                    String strValue = str.getValue();
                    if (element.getElementName().equals("study_id")) {
                        // Piece of crap parser in REDCap requires study id to be first
                        // element
                        study_id = strValue;
                    } else if (strValue != null) {
                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");
                    }
                }
                    break;

                case JRDATETIME: {
                    JRDateTimeType dt = (JRDateTimeType) value;
                    Date dtValue = dt.getValue();

                    if (dtValue != null) {
                        GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
                        g.setTime(dtValue);

                        String strValue = String.format(FormatConsts.REDCAP_DATE_TIME_FORMAT_STRING,
                                g.get(Calendar.YEAR), g.get(Calendar.MONTH) + 1, g.get(Calendar.DAY_OF_MONTH),
                                g.get(Calendar.HOUR_OF_DAY), g.get(Calendar.MINUTE), g.get(Calendar.SECOND));

                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");

                    }
                }
                    break;

                case JRDATE: {
                    JRDateType dt = (JRDateType) value;
                    Date dtValue = dt.getValue();

                    if (dtValue != null) {
                        GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
                        g.setTime(dtValue);

                        String strValue = String.format(FormatConsts.REDCAP_DATE_ONLY_FORMAT_STRING,
                                g.get(Calendar.YEAR), g.get(Calendar.MONTH) + 1, g.get(Calendar.DAY_OF_MONTH));

                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");
                    }
                }
                    break;

                case JRTIME: {
                    JRTimeType dt = (JRTimeType) value;
                    Date dtValue = dt.getValue();

                    if (dtValue != null) {
                        GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
                        g.setTime(dtValue);

                        String strValue = String.format(FormatConsts.REDCAP_TIME_FORMAT_STRING,
                                g.get(Calendar.HOUR_OF_DAY), g.get(Calendar.MINUTE));

                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");
                    }
                }
                    break;

                case INTEGER: {
                    LongSubmissionType longVal = (LongSubmissionType) value;
                    if (longVal.getValue() != null) {
                        String strValue = longVal.getValue().toString();

                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");
                    }
                }
                    break;

                case DECIMAL: {
                    DecimalSubmissionType dec = (DecimalSubmissionType) value;
                    if (dec.getValue() != null) {
                        String strValue = dec.getValue().toString();

                        b.append("<").append(element.getElementName()).append(">")
                                .append(StringEscapeUtils.escapeXml10(strValue)).append("</")
                                .append(element.getElementName()).append(">");
                    }
                }
                    break;

                case GEOPOINT: {
                    // TODO: should not have gps_ prefix on tag...
                    String strippedElementName = element.getElementName().replace("gps_", "");
                    GeoPointSubmissionType submissionValue = (GeoPointSubmissionType) value;
                    GeoPoint coors = submissionValue.getValue();
                    if (coors.getLatitude() != null) {
                        b.append("<").append("gps_lat_" + strippedElementName).append(">")
                                .append(StringEscapeUtils.escapeXml10(coors.getLatitude().toString()))
                                .append("</").append("gps_lat_" + strippedElementName).append(">");

                        b.append("<").append("gps_lon_" + strippedElementName).append(">")
                                .append(StringEscapeUtils.escapeXml10(coors.getLongitude().toString()))
                                .append("</").append("gps_lon_" + strippedElementName).append(">");

                        b.append("<").append("gps_alt_" + strippedElementName).append(">")
                                .append(StringEscapeUtils.escapeXml10(coors.getAltitude().toString()))
                                .append("</").append("gps_alt_" + strippedElementName).append(">");

                        b.append("<").append("gps_acc_" + strippedElementName).append(">")
                                .append(StringEscapeUtils.escapeXml10(coors.getAccuracy().toString()))
                                .append("</").append("gps_acc_" + strippedElementName).append(">");
                    }
                }
                    break;

                case BINARY: {
                    String file_field = element.getElementName();
                    BlobSubmissionType blob_value = (BlobSubmissionType) value;
                    if (blob_value.getAttachmentCount(cc) == 1) {
                        blobs.put(file_field, blob_value);
                    }
                    // upload these after we have successfully imported the record
                }
                    break;

                case BOOLEAN: {
                    String strippedElementName = element.getElementName().replace("slct-", "");
                    BooleanSubmissionType bType = (BooleanSubmissionType) value;
                    if (bType.getValue() != null) {
                        b.append("<").append(strippedElementName + "___" + bType.getValue().toString())
                                .append(">").append(StringEscapeUtils.escapeXml10("1")).append("</")
                                .append(strippedElementName + "___" + bType.getValue().toString()).append(">");
                    }
                }
                    break;

                case SELECT1:
                case SELECTN: {
                    // TODO: it's not necessary to add (or remove) 'slct-' from
                    // the field name anymore
                    String formatElementName = element.getElementName().replace("slct-", "");
                    ChoiceSubmissionType choice = (ChoiceSubmissionType) value;
                    for (String choiceVal : choice.getValue()) {
                        b.append("<").append(formatElementName + "___" + choiceVal).append(">")
                                .append(StringEscapeUtils.escapeXml10("1")).append("</")
                                .append(formatElementName + "___" + choiceVal).append(">");
                    }
                }
                    break;

                case REPEAT: {
                    logger.warn("Unable to publish repeat groups to REDCap");
                    // REDCap does not handle repeat groups.
                }
                    break;

                case GROUP:
                    logger.warn("The GROUP submission type is not implemented");
                    break;

                }
            }
        }

        b.append("</item></records>");

        if (study_id == null) {
            throw new IllegalStateException("Form does not contain a study_id field -- cannot publish!");
        }

        String submissionsListString = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><records><item><study_id>"
                + StringEscapeUtils.escapeXml10(study_id) + "</study_id>" + b.toString();

        List<NameValuePair> eparams = new ArrayList<NameValuePair>();
        eparams.add(new BasicNameValuePair("token", getApiKey()));
        eparams.add(new BasicNameValuePair("content", "record"));
        eparams.add(new BasicNameValuePair("format", "xml"));
        eparams.add(new BasicNameValuePair("overwriteBehavior", "overwrite"));
        eparams.add(new BasicNameValuePair("data", submissionsListString));
        eparams.add(new BasicNameValuePair("returnContent", "ids"));
        eparams.add(new BasicNameValuePair("returnFormat", "xml"));

        HttpEntity postentity = new UrlEncodedFormEntity(eparams, UTF_CHARSET);

        submitPost("Publishing", postentity, null, cc);

        // send the files if they exist
        for (Map.Entry<String, BlobSubmissionType> e : blobs.entrySet()) {
            System.out.println("Processing media attachment....");
            BlobSubmissionType blob = e.getValue();
            submitFile(study_id, e.getKey(), blob, cc);
        }

    } catch (Exception e) {
        throw new ODKExternalServiceException(e);
    }

}

From source file:nl.b3p.gis.writers.B3pOgcSqlWriter.java

private String getSqlValue(Feature f, FeatureSchema fs, int i, boolean nullForEmptyNumber)
        throws ParseException {
    Object o = f.getAttribute(fs.getAttributeName(i));
    StringBuffer values = new StringBuffer();
    if (fs.getAttributeType(i).equals(AttributeType.GEOMETRY)) {
        values.append("GeomFromText(\'");
        values.append(f.getGeometry().toText());

        int geomSRID = f.getGeometry().getSRID();
        //int schemaSRID = fs.getCoordinateSystem().getEPSGCode();
        /*if (geomSRID>=0 && schemaSRID>=0 && geomSRID!=schemaSRID)
        throw new ParseException("SRID of geometry differs from EPSG code of feature schema!", i);
         *///ww w  .  j a  va 2  s . c  om
        if (geomSRID >= 0) {
            values.append("\', " + geomSRID);
        } /*else if (schemaSRID>=0){
          values.append("\', "+geomSRID);
          } */ else {
            values.append("\', 28992");
        }
        values.append(")");
    } else if (fs.getAttributeType(i).equals(AttributeType.DOUBLE)
            || fs.getAttributeType(i).equals(AttributeType.INTEGER)) {
        if ("".equals(o) || o == null) {
            if (nullForEmptyNumber) {
                values.append("null");
            } else {
                values.append("''");
            }
        } else {
            // check if value is a number!!!
            // else we get strange SQL syntax errors
            try {
                Double.parseDouble(o.toString());
            } catch (Exception e) {
                throw new IllegalArgumentException("The DOUBLE/INTEGER value is not valid: " + o);
            }
            values.append(o);
        }
    } else if (fs.getAttributeType(i).equals(AttributeType.STRING)) {
        if (o == null) {
            values.append(o);
        } else {
            String s = (String) o;
            s = s.replaceAll("'", "\'\'");
            values.append("\'");
            values.append(s);
            values.append("\'");
        }
    } else if (fs.getAttributeType(i).equals(AttributeType.DATE)) {
        if (o == null) {
            values.append(o);
        } else if (o instanceof Date) {
            Date d = (Date) o;
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(d);
            values.append("\'");
            values.append(new SimpleDateFormat("yyyy-MM-dd").format(d));
            values.append("\'");
        } else if (o instanceof String) {
            values.append("\'");
            if (!"''".equals(o)) {
                values.append(formatDate("dd-MM-yyyy", "HH:mm:ss", "yyyy-MM-dd", "HH:mm:ss", (String) o));
            }
            values.append("\'");
        } else {
            values.append("\'\'");
        }
    } else if (fs.getAttributeType(i).equals(AttributeType.OBJECT)) {
        if (o == null) {
            values.append(o);
        } else {
            values.append("\'");
            values.append(o);
            values.append("\'");
        }
    }
    return values.toString();
}