Example usage for org.json.simple JSONObject keySet

List of usage examples for org.json.simple JSONObject keySet

Introduction

In this page you can find the example usage for org.json.simple JSONObject keySet.

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:org.dia.kafka.solr.consumer.SolrKafkaConsumer.java

/**
 * Converts ISATools messages into Solr documents
 *
 * @param jsonObject//w  w w.j a  v  a  2s .co m
 * @return
 */
private SolrInputDocument convertIsaMsgSolr(JSONObject jsonObject) {
    System.out.format("[%s] Processing msg from %s\n", this.getClass().getSimpleName(), DataSource.ISATOOLS);
    final SolrInputDocument inputDoc = new SolrInputDocument();
    jsonObject.remove(SOURCE_TAG);
    Iterator<?> keys = jsonObject.keySet().iterator();
    List<String> invNames = new ArrayList<String>();
    List<String> invMid = new ArrayList<String>();
    List<String> invLastNames = new ArrayList<String>();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        String cleanKey = updateCommentPreffix(key);
        if (!ISA_IGNORED_SET.contains(cleanKey)) {
            if (cleanKey.equals("DA_Number")) {
                inputDoc.addField("id", jsonObject.get(key));
            } else if (cleanKey.equals("Study_Person_First_Name")) { // dealing with investigators' names
                invNames.add(jsonObject.get(key).toString());
            } else if (cleanKey.equals("Study_Person_Mid_Initials")) {
                invMid.add(jsonObject.get(key).toString());
            } else if (cleanKey.equals("Description")) {
                invLastNames.add(jsonObject.get(key).toString());
            } else if (cleanKey.equals("Tags")) {
                inputDoc.addField("Study_Tags", jsonObject.get(key));
            } else if (cleanKey.equals("Created_with_configuration")) {
                inputDoc.addField("Created_With_Configuration", jsonObject.get(key));
            } else {//if (!key.startsWith("_")){
                inputDoc.addField(cleanKey, jsonObject.get(key));
            }
        }
    }
    JSONArray jsonArray = new JSONArray();
    for (int cnt = 0; cnt < invLastNames.size(); cnt++) {
        StringBuilder sb = new StringBuilder();
        sb.append(invNames.get(cnt) != null ? invNames.get(cnt) : "").append(" ");
        sb.append(invMid.get(cnt) != null ? invMid.get(cnt) : "").append(" ");
        sb.append(invLastNames.get(cnt) != null ? invLastNames.get(cnt) : "");
        jsonArray.add(sb.toString());
    }
    if (!jsonArray.isEmpty())
        inputDoc.addField("Investigator", jsonArray.toJSONString());
    return inputDoc;
}

From source file:org.dia.kafka.solr.consumer.SolrKafkaConsumer.java

/**
 * Converts OODT messages into Solr documents
 * {@code {"TargetName":["target"],"FileLocation":["\/data\/archive\/035131.pdf"],"ProjectName":["project"],"DataAssetGroupName":["data asset"],"Compound":["compound"],"Investigator":["investigator"],"ProductStructure":["Flat"],"MimeType":["application\/octet-stream","application\/pdf","application","pdf"],"AssetType":["Processed"],"CAS.ProductName":["035131.pdf"],"CAS.ProductReceivedTime":["2015-06-09T08:31:11.749-07:00"],"Filename":["035131.pdf"],"DataSource":"OODT","SampleType":["type"],"AssayPurpose":["assay"],"Vendor":["vendor"],"CAS.ProductId":["8ed237e5-0ebc-11e5-8684-d7284d57b93d"],"ProductType":["Processed"],"ProjectDesciption":["description"],"ProductName":["DA0000023,Processed,035131.pdf"],"ExperimentType":["experiment1"],"DataAssetGroupNumber":["DA0000023"],"Department":["dep"],"Platform":["aplatform"]}}
 *
 * @param jsonObject/*  w w w.  ja v  a 2 s.  c  om*/
 * @return
 */
private SolrInputDocument convertOodtMsgSolr(JSONObject jsonObject) {
    System.out.format("[%s] Processing msg from %s\n", this.getClass().getSimpleName(), DataSource.OODT);
    final SolrInputDocument inputDoc = new SolrInputDocument();
    jsonObject.remove(SOURCE_TAG);

    Iterator<?> keys = jsonObject.keySet().iterator();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        if (!Constants.OODT_IGNORED_SET.contains(key)) {
            if (key.equals("DataAssetGroupNumber")) {
                inputDoc.addField("id", jsonObject.get(key));
            } else if (key.equals("ProjectDesciption")) {
                inputDoc.addField("Study_Description", jsonObject.get(key));
            } else if (key.equals("ProjectName")) {
                inputDoc.addField("Study_Title", jsonObject.get(key));
            } else {//if (!key.startsWith("_")){
                inputDoc.addField(key, jsonObject.get(key));
            }
        }
    }
    return inputDoc;
}

From source file:org.dia.kafka.solr.consumer.SolrKafkaConsumer.java

/**
 * {@code/*from w ww. j a  v  a  2s .  c o  m*/
 * {"studies":[
 * {
 * "ParticipantAliasSourceProperty" : "null",
 * "ParticipantAliasProperty" : "null",
 * "Description" : "Some Description",
 * "EndDate" : "null",
 * "_labkeyurl_Label" : "/labkey/project/Project Name/start.view?",
 * "AssayPlan" : "null",
 * "Grant" : "Some Foundation",
 * "StartDate" : "Tue Jan 01 00:00:00 EST 2008",
 * "Investigator" : "Some PI, PhD",
 * "ParticipantAliasDatasetId" : "null",
 * "Label" : "Interactive Example - Study",
 * "Species" : "null",
 * "Container" : "6f743c1b-9506-1032-b9bf-51af32c4d069",
 * "_labkeyurl_Container" : "/labkey/project/Study Name/begin.view?",
 * }
 * ]
 * }
 * }
 *
 * @param jsonObject
 * @return
 * @throws IOException
 */
private SolrInputDocument convertLabkeyMsgSolr(JSONObject jsonObject) {
    System.out.format("[%s] Processing msg from %s\n", this.getClass().getSimpleName(), DataSource.LABKEY);
    final SolrInputDocument inputDoc = new SolrInputDocument();
    jsonObject.remove(SOURCE_TAG);
    Iterator<?> keys = jsonObject.keySet().iterator();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        if (key.equals("Container")) {
            inputDoc.addField("id", jsonObject.get(key));
        } else if (key.equals("Description")) {
            inputDoc.addField("Study_Description", jsonObject.get(key));
        } else if (key.equals("_labkeyurl_Container")) {
            inputDoc.addField("Labkeyurl_Container", jsonObject.get(key));
        } else if (key.equals("_labkeyurl_Label")) {
            inputDoc.addField("Labkeyurl_Label", jsonObject.get(key));
        } else if (key.equals("Investigator")) {
            inputDoc.addField("Investigator", StringUtils.split(jsonObject.get(key).toString(), ";"));
        } else if (key.equals("Grant")) {
            inputDoc.addField("Study_Grant_Number", jsonObject.get(key));
        } else {
            inputDoc.addField(key, jsonObject.get(key).toString());
        }
    }

    return inputDoc;
}

From source file:org.eclipse.cdt.boost.build.core.internal.model.Event.java

private Event(String event) {
    JSONObject responseObj = (JSONObject) JSONValue.parse(event);
    if ("event".equals(responseObj.get("type"))) {
        fEventType = (String) responseObj.get("event");
        fActionKind = (String) responseObj.get("kind");
        fActionName = (String) responseObj.get("action-name");
        fToken = responseObj.get("token");
        fContent = (String) responseObj.get("message");
        if (fContent == null)
            fContent = (String) responseObj.get("output");
        Object tmp = responseObj.get("exit-status");
        if (tmp != null)
            fExitStatus = (Long) tmp;
        tmp = responseObj.get("success");
        if (tmp != null)
            fSuccess = Boolean.parseBoolean(((String) tmp));
        fSources = (List<String>) responseObj.get("sources");
        fTargets = (List<String>) responseObj.get("targets");
        JSONObject properties = (JSONObject) responseObj.get("properties");
        if (properties != null) {
            fProperties = new HashMap<String, List<String>>();
            for (Object property : properties.keySet()) {
                Object val = properties.get(property);
                List<String> vals = null;
                if (val instanceof String) {
                    vals = new ArrayList<>();
                    vals.add((String) val);
                } else if (val instanceof JSONArray) {
                    vals = (JSONArray) val;
                }/*from  ww w .j  a va 2  s  . c  om*/
                fProperties.put((String) property, vals);
            }
        }
    }
}

From source file:org.exoplatform.addons.es.search.ElasticSearchServiceConnector.java

protected Collection<SearchResult> buildResult(String jsonResponse, SearchContext context) {

    LOG.debug("Search Query response from ES : {} ", jsonResponse);

    Collection<SearchResult> results = new ArrayList<>();
    JSONParser parser = new JSONParser();

    Map json;/*from ww w  . ja va  2  s.  c om*/
    try {
        json = (Map) parser.parse(jsonResponse);
    } catch (ParseException e) {
        throw new ElasticSearchException("Unable to parse JSON response", e);
    }

    //TODO check if response is successful
    JSONObject jsonResult = (JSONObject) json.get("hits");
    JSONArray jsonHits = (JSONArray) jsonResult.get("hits");

    for (Object jsonHit : jsonHits) {
        JSONObject hitSource = (JSONObject) ((JSONObject) jsonHit).get("_source");
        String title = getTitleFromJsonResult(hitSource);
        String url = getUrlFromJsonResult(hitSource, context);
        Long lastUpdatedDate = (Long) hitSource.get("lastUpdatedDate");
        if (lastUpdatedDate == null)
            lastUpdatedDate = new Date().getTime();
        Double score = (Double) ((JSONObject) jsonHit).get("_score");
        //Get the excerpt
        JSONObject hitHighlight = (JSONObject) ((JSONObject) jsonHit).get("highlight");
        Iterator<?> keys = hitHighlight.keySet().iterator();
        StringBuilder excerpt = new StringBuilder();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            JSONArray highlights = (JSONArray) hitHighlight.get(key);
            for (Object highlight : highlights) {
                excerpt.append("... ").append(highlight);
            }
        }

        LOG.debug("Excerpt extract from ES response : " + excerpt.toString());

        results.add(new SearchResult(url, title, excerpt.toString(), null, img, lastUpdatedDate,
                //score must not be null as "track_scores" is part of the query
                score.longValue()));
    }

    return results;

}

From source file:org.exoplatform.portal.jdbc.service.JDBCModelStorageImpl.java

@SuppressWarnings("unchecked")
private ApplicationData buildWindow(WindowEntity windowEntity) {
    ApplicationType<?> appType = convert(windowEntity.getAppType());
    PersistentApplicationState<?> state = new PersistentApplicationState(windowEntity.getId());

    Map<String, String> properties = new HashMap<String, String>();
    try {//from   w w w.ja v a 2 s.c om
        JSONParser parser = new JSONParser();
        JSONObject jProp = (JSONObject) parser.parse(windowEntity.getProperties());
        for (Object key : jProp.keySet()) {
            properties.put(key.toString(), jProp.get(key).toString());
        }
    } catch (Exception ex) {
        log.error(ex);
    }

    List<PermissionEntity> access = permissionDAO.getPermissions(windowEntity.getId(),
            org.exoplatform.portal.jdbc.entity.PermissionEntity.TYPE.ACCESS);

    return new ApplicationData(windowEntity.getId(), null, appType, state, windowEntity.getId(),
            windowEntity.getTitle(), windowEntity.getIcon(), windowEntity.getDescription(),
            windowEntity.isShowInfoBar(), windowEntity.isShowApplicationState(),
            windowEntity.isShowApplicationMode(), windowEntity.getTheme(), windowEntity.getWidth(),
            windowEntity.getHeight(), properties, buildPermission(access));
}

From source file:org.exoplatform.portal.jdbc.service.JDBCModelStorageImpl.java

private PortalData buildPortalData(SiteEntity entity) throws Exception {
    if (entity == null) {
        return null;
    }//from   w w w  .ja  v a2 s.c o  m
    //
    JSONParser parser = new JSONParser();
    JSONArray siteBody = (JSONArray) parser.parse(entity.getSiteBody());
    List<ComponentData> children = buildChildren(siteBody);
    ContainerData rootContainer = null;
    if (children.size() > 0) {
        rootContainer = (ContainerData) children.get(0);
    } else {
        throw new IllegalStateException("site doens't has root container layout");
    }

    List<PermissionEntity> access = permissionDAO.getPermissions(entity.getId(),
            org.exoplatform.portal.jdbc.entity.PermissionEntity.TYPE.ACCESS);
    List<PermissionEntity> edit = permissionDAO.getPermissions(entity.getId(),
            org.exoplatform.portal.jdbc.entity.PermissionEntity.TYPE.EDIT);
    String editPer = edit.size() > 0 ? edit.get(0).getPermission() : null;

    List<RedirectData> redirects = Collections.emptyList();

    Map<String, String> properties = new HashMap<String, String>();
    try {
        if (entity.getProperties() != null) {
            JSONObject jProp = (JSONObject) parser.parse(entity.getProperties());
            for (Object key : jProp.keySet()) {
                properties.put(key.toString(), jProp.get(key).toString());
            }
        }
    } catch (Exception ex) {
        log.error(ex);
    }

    return new PortalData(entity.getId(), entity.getName(), entity.getSiteType().getName(), entity.getLocale(),
            entity.getLabel(), entity.getDescription(), buildPermission(access), editPer,
            Collections.unmodifiableMap(properties), entity.getSkin(), rootContainer, redirects);
}

From source file:org.exoplatform.wiki.jpa.search.WikiElasticSearchServiceConnector.java

protected List<SearchResult> buildWikiResult(String jsonResponse) {

    List<SearchResult> wikiResults = new ArrayList<>();

    JSONParser parser = new JSONParser();

    Map json;//  w  w  w .  j  a  v  a2s. c o  m
    try {
        json = (Map) parser.parse(jsonResponse);
    } catch (ParseException e) {
        throw new ElasticSearchException("Unable to parse JSON response", e);
    }

    JSONObject jsonResult = (JSONObject) json.get("hits");
    JSONArray jsonHits = (JSONArray) jsonResult.get("hits");

    for (Object jsonHit : jsonHits) {

        long score = ((Double) ((JSONObject) jsonHit).get("_score")).longValue();

        JSONObject hitSource = (JSONObject) ((JSONObject) jsonHit).get("_source");

        String title = (String) hitSource.get("title");
        String url = (String) hitSource.get("url");

        String wikiType = (String) hitSource.get("wikiType");
        String wikiOwner = (String) hitSource.get("wikiOwner");

        Calendar createdDate = Calendar.getInstance();
        createdDate.setTimeInMillis(Long.parseLong((String) hitSource.get("createdDate")));
        Calendar updatedDate = Calendar.getInstance();
        updatedDate.setTimeInMillis(Long.parseLong((String) hitSource.get("updatedDate")));

        SearchResultType type = SearchResultType.PAGE;
        String pageName = (String) hitSource.get("name");
        String attachmentName = null;

        //Result can be an attachment
        if (((JSONObject) jsonHit).get("_type").equals("wiki-attachment")) {
            pageName = (String) hitSource.get("pageName");
            attachmentName = (String) hitSource.get("name");
        }

        //Get the excerpt
        JSONObject hitHighlight = (JSONObject) ((JSONObject) jsonHit).get("highlight");
        Iterator<?> keys = hitHighlight.keySet().iterator();
        StringBuilder excerpt = new StringBuilder();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            JSONArray highlights = (JSONArray) hitHighlight.get(key);
            for (Object highlight : highlights) {
                excerpt.append("... ").append(highlight);
            }
        }

        //Create the wiki serch result
        SearchResult wikiSearchResult = new SearchResult();
        wikiSearchResult.setWikiType(wikiType);
        wikiSearchResult.setWikiOwner(wikiOwner);
        wikiSearchResult.setPageName(pageName);
        wikiSearchResult.setAttachmentName(attachmentName);
        wikiSearchResult.setExcerpt(excerpt.toString());
        wikiSearchResult.setTitle(title);
        wikiSearchResult.setType(type);
        wikiSearchResult.setCreatedDate(createdDate);
        wikiSearchResult.setUpdatedDate(updatedDate);
        wikiSearchResult.setUrl(url);
        wikiSearchResult.setScore(score);

        //Add the wiki search result to the list of search results
        wikiResults.add(wikiSearchResult);

    }

    return wikiResults;

}

From source file:org.finra.herd.service.impl.Ec2OnDemandPricingUpdateServiceImpl.java

/**
 * {@inheritDoc}/*w w  w  .j a  va 2s .  c  om*/
 * <p/>
 * This implementation executes non-transactionally, suspends the current transaction if one exists.
 */
@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public List<Ec2OnDemandPricing> getEc2OnDemandPricing(String ec2PricingListUrl) {
    // Create a list of EC2 on-demand pricing entries.
    List<Ec2OnDemandPricing> ec2OnDemandPricingEntries = new ArrayList<>();

    // Get JSON object from the specified URL.
    JSONObject jsonObject = urlHelper.parseJsonObjectFromUrl(ec2PricingListUrl);

    // Get products from the JSON object.
    JSONObject products = jsonHelper.getKeyValue(jsonObject, JSON_KEY_NAME_PRODUCTS, JSONObject.class);

    // Create a set to validate uniqueness of EC2 on-demand pricing keys.
    Set<Ec2OnDemandPricingKey> uniqueEc2OnDemandPricingKeys = new HashSet<>();

    // Process all products.
    for (Object key : products.keySet()) {
        JSONObject current = jsonHelper.getKeyValue(products, key, JSONObject.class);
        String sku = jsonHelper.getKeyValue(current, JSON_KEY_NAME_SKU, String.class);
        JSONObject attributes = jsonHelper.getKeyValue(current, JSON_KEY_NAME_ATTRIBUTES, JSONObject.class);

        Object location = attributes.get(JSON_ATTRIBUTE_NAME_LOCATION);
        Object operatingSystem = attributes.get(JSON_ATTRIBUTE_NAME_OPERATING_SYSTEM);
        Object instanceType = attributes.get(JSON_ATTRIBUTE_NAME_INSTANCE_TYPE);
        Object tenancy = attributes.get(JSON_ATTRIBUTE_NAME_TENANCY);
        Object usageType = attributes.get(JSON_ATTRIBUTE_NAME_USAGE_TYPE);
        Object preInstalledSoftware = attributes.get(JSON_ATTRIBUTE_NAME_PRE_INSTALLED_SOFTWARE);

        // Validate the parameters and create an EC2 on-demand pricing entry.
        Ec2OnDemandPricing ec2OnDemandPricing = createEc2OnDemandPricingEntry(sku, location, operatingSystem,
                instanceType, tenancy, usageType, preInstalledSoftware);

        // Check if this EC2 on-demand pricing entry got created (the relative parameters passed validation checks).
        if (ec2OnDemandPricing != null) {
            // Get the EC2 on-demand pricing key.
            Ec2OnDemandPricingKey ec2OnDemandPricingKey = ec2OnDemandPricing.getEc2OnDemandPricingKey();

            // Validate that this key is unique.
            if (!uniqueEc2OnDemandPricingKeys.add(ec2OnDemandPricingKey)) {
                throw new IllegalArgumentException(String.format(
                        "Found duplicate EC2 on-demand pricing entry for \"%s\" AWS region and \"%s\" EC2 instance type.",
                        ec2OnDemandPricingKey.getRegionName(), ec2OnDemandPricingKey.getInstanceType()));
            }

            // Add this EC2 on-demand pricing entry to the result list.
            ec2OnDemandPricingEntries.add(ec2OnDemandPricing);
        }
    }

    // Continue the processing only when the result list is not empty.
    if (CollectionUtils.isNotEmpty(ec2OnDemandPricingEntries)) {
        // Get terms from the JSON object.
        JSONObject terms = jsonHelper.getKeyValue(jsonObject, JSON_KEY_NAME_TERMS, JSONObject.class);

        // Get on-demand information from the terms.
        JSONObject onDemand = jsonHelper.getKeyValue(terms, JSON_KEY_NAME_ON_DEMAND, JSONObject.class);

        // Populate pricing information.
        for (Ec2OnDemandPricing ec2OnDemandPricing : ec2OnDemandPricingEntries) {
            String sku = ec2OnDemandPricing.getSku();
            JSONObject current = jsonHelper.getKeyValue(onDemand, sku, JSONObject.class);
            JSONObject pricingWrapper = jsonHelper.getKeyValue(current, sku + JSON_SKU_WRAPPER_SUFFIX,
                    JSONObject.class);
            JSONObject priceDimensions = jsonHelper.getKeyValue(pricingWrapper, JSON_KEY_NAME_PRICE_DIMENSIONS,
                    JSONObject.class);
            JSONObject innerPricingWrapper = jsonHelper.getKeyValue(priceDimensions,
                    sku + JSON_SKU_WRAPPER_SUFFIX + JSON_PRICE_DIMENSIONS_WRAPPER_SUFFIX, JSONObject.class);
            JSONObject pricePerUnit = jsonHelper.getKeyValue(innerPricingWrapper, JSON_KEY_NAME_PRICE_PER_UNIT,
                    JSONObject.class);
            String pricePerUnitValue = jsonHelper.getKeyValue(pricePerUnit, JSON_PRICE_PER_UNIT_WRAPPER,
                    String.class);

            try {
                ec2OnDemandPricing.setPricePerHour(new BigDecimal(pricePerUnitValue));
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException(String.format("Failed to convert \"%s\" value to %s.",
                        pricePerUnitValue, BigDecimal.class.getName()), e);
            }
        }
    }

    return ec2OnDemandPricingEntries;
}

From source file:org.gathe.verge.uno.ODT2PDFConverter.java

public void run() {

    System.setProperty("javax.net.ssl.trustStore", "/opt/myKeystore");
    System.setProperty("javax.net.ssl.trustStorePassword", "keys$%");

    FileInputStream is = null;/*from  w w  w.  j a  v a 2 s .com*/
    try {
        XComponentContext xComponentContext = Bootstrap.bootstrap();
        //       XComponentContext xComponentContext = BootstrapSocketConnector.bootstrap(oooExeFolder);
        XMultiComponentFactory xMCF = xComponentContext.getServiceManager();

        HashMap<String, ArrayList<HashMap<String, String>>> data = new HashMap<>();
        HashMap<String, String> fields = new HashMap<>();

        String json = this.getParameters(); //"{\"lastname\":\"\",\"firstname\":\"\",\"middlename\":\"\",\"table-ege\":[{\"subject\":\"Physics\",\"Score\":\"100\"},{\"subject\":\"Chemistry\",\"Score\":\"95\"}]}";

        JSONParser parser = new JSONParser();
        System.out.println(json);
        JSONObject jsonObj = (JSONObject) parser.parse(json);
        for (Object jsonKey : jsonObj.keySet()) {
            if (("" + jsonKey).startsWith("table-")) {
                ArrayList<HashMap<String, String>> tableContent = new ArrayList<>();
                String tableName = ("" + jsonKey).substring(6);
                JSONArray arr = (JSONArray) jsonObj.get(jsonKey);
                HashMap<String, String> row;
                for (int c = 0; c < arr.size(); c++) {
                    row = new HashMap<>();
                    JSONObject jobj = (JSONObject) arr.get(c);
                    for (Object rowKey : jobj.keySet()) {
                        String rowKeyStr = "" + rowKey;
                        String rowValue = "" + jobj.get(rowKey);
                        row.put(rowKeyStr.toUpperCase(), rowValue);
                    }
                    tableContent.add(row);
                }
                data.put(tableName.toUpperCase(), tableContent);
            } else {
                String jsonValue = "" + jsonObj.get(jsonKey);
                fields.put(("" + jsonKey).toUpperCase(), jsonValue);
                System.out.println(jsonKey + ":" + jsonValue);
            }
        }

        //load file
        Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xComponentContext);
        XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class,
                oDesktop);
        String url = this.getTemplateName();//"file:///devel/LOConnector/declaration_bachelor.odt";

        PropertyValue[] loadProperties = new PropertyValue[1];
        //        loadProperties[0] = new PropertyValue();
        //        loadProperties[0].Name = "Hidden";
        //        loadProperties[0].Value = new Boolean(false);
        loadProperties[0] = new PropertyValue();
        loadProperties[0].Name = "ReadOnly";
        loadProperties[0].Value = new Boolean(false);
        Object document = xCompLoader.loadComponentFromURL(url, "_blank", 0, loadProperties);

        XTextDocument xTextDocument = UnoRuntime.queryInterface(XTextDocument.class, document);

        XTextFieldsSupplier fieldsSupplier = UnoRuntime.queryInterface(XTextFieldsSupplier.class, document);
        //        
        XNameAccess xNameAccess = fieldsSupplier.getTextFieldMasters();
        for (String element : fields.keySet()) {
            if (element.startsWith("#"))
                continue;
            System.out.println(element);
            String value = fields.get(element);
            System.out.println(value);
            if (value != null) {
                String name = "com.sun.star.text.FieldMaster.User." + element.toUpperCase();
                if (xNameAccess.hasByName(name)) {
                    Object fieldObj = xNameAccess.getByName(name);
                    XPropertySet field = UnoRuntime.queryInterface(XPropertySet.class, fieldObj);
                    String oldValue = field.getPropertyValue("Content").toString();
                    System.out.println(oldValue);
                    if (oldValue.startsWith("#")) {
                        if (value.equalsIgnoreCase("true")) {
                            value = "1";
                        }
                        if (value.equalsIgnoreCase("false")) {
                            value = "0";
                        }
                        String[] values = oldValue.substring(1).split("/");
                        boolean flag = false;
                        for (String value2 : values) {
                            String[] entry = value2.split("=");
                            if (entry.length == 1) {
                                String[] entry2 = new String[2];
                                entry2[0] = entry[0];
                                entry2[1] = "";
                                entry = entry2;
                            }
                            System.out.println("Comparing " + entry[0] + " : " + entry[1] + " with " + value);
                            if (Integer.parseInt(entry[0]) == Integer.parseInt(value)) {
                                flag = true;
                                value = entry[1];
                                break;
                            }
                        }
                        if (!flag)
                            value = "<??>";
                    }
                    field.setPropertyValue("Content", value);
                }
            }
        }

        XTextTablesSupplier tablesSupplier = UnoRuntime.queryInterface(XTextTablesSupplier.class, document);

        //fill the tables
        XNameAccess allTables = tablesSupplier.getTextTables();
        for (String tableName : data.keySet()) {
            if (!allTables.hasByName(tableName)) {
                continue;
            }
            Object retrievedTableObj = allTables.getByName(tableName);
            ArrayList<HashMap<String, String>> dataSubset = data.get(tableName);

            if (dataSubset.size() == 0) {
                //remove empty table
                XTextDocument textDocument = UnoRuntime.queryInterface(XTextDocument.class, document);
                XText text = textDocument.getText();
                XTextContent tableContentText = UnoRuntime.queryInterface(XTextContent.class,
                        retrievedTableObj);
                text.removeTextContent(tableContentText);
                continue;
            }
            XTextTable retrievedTable = UnoRuntime.queryInterface(XTextTable.class, retrievedTableObj);
            XCellRange retrievedTableCells = UnoRuntime.queryInterface(XCellRange.class, retrievedTableObj);
            int rowsCount = retrievedTable.getRows().getCount();
            int colsCount = retrievedTable.getColumns().getCount();

            ArrayList<String> rowNumbers = new ArrayList<String>();
            ArrayList<HashMap<String, String>> fieldsLocations = new ArrayList<HashMap<String, String>>();
            ArrayList<String> rowLength = new ArrayList<String>();

            //get row numbers with referenced fields
            int maxRow = 0;
            int maxLen = 0;
            for (int row = 0; row < rowsCount; row++) {
                boolean found = false;
                HashMap<String, String> fieldsAtRow = new HashMap<String, String>();
                int col = 0;
                for (col = 0; col < colsCount; col++) {
                    System.out.println("Reading cell " + col + ":" + row);
                    try {
                        XCell cell = retrievedTableCells.getCellByPosition(col, row);
                        XText cellText = UnoRuntime.queryInterface(XText.class, cell);
                        String val = cellText.getString();
                        if (val.startsWith("#")) {
                            fieldsAtRow.put("" + col, val.substring(1));
                            found = true;
                        }
                    } catch (Exception e) {
                        break;
                    }
                }
                if (found) {
                    rowNumbers.add("" + row);
                    fieldsLocations.add(fieldsAtRow);
                    rowLength.add("" + col);
                    if (row > maxRow)
                        maxRow = row;
                    if (col > maxLen)
                        maxLen = col;
                }
            }
            maxRow++;

            XController xController = xTextDocument.getCurrentController();
            XTransferableSupplier xTransferableSupplier = UnoRuntime.queryInterface(XTransferableSupplier.class,
                    xController);

            //Fill the table below the bottom line
            int tableRow = maxRow;
            for (HashMap<String, String> dataRow : dataSubset) {
                //                    if (tableRow != 0) {
                System.out.println("Adding row " + maxRow);
                retrievedTable.getRows().insertByIndex(maxRow, 1);
                maxRow++;
            }

            for (HashMap<String, String> dataRow : dataSubset) {
                //merging cells
                System.out.println("Datarow: " + dataRow);
                int rowId = 0;
                if (dataRow.containsKey("%"))
                    rowId = Integer.parseInt("" + dataRow.get("%"));
                int rowLen = Integer.parseInt(rowLength.get(rowId));
                if (dataRow.containsKey("$")) {
                    System.out.println("MERGING CELLS");
                    int left = maxLen;
                    int positionX = 0;
                    int positionY = tableRow;
                    String[] dataRowSize = dataRow.get("$").split(",");
                    int newLen = 0;
                    for (String dataRowSizeElement : dataRowSize) {
                        System.out.println("PROCESSING: " + dataRowSizeElement);
                        int horSpan;
                        if (dataRowSizeElement.equals("*"))
                            horSpan = left;
                        else
                            horSpan = Integer.parseInt(dataRowSizeElement);
                        String startAddress = String.valueOf(Character.toChars(positionX + 65))
                                + (positionY + 1);
                        XTextTableCursor textTableCursor = retrievedTable.createCursorByCellName(startAddress);
                        if (horSpan > 1)
                            textTableCursor.goRight((short) (horSpan - 1), true);
                        textTableCursor.mergeRange();
                        left -= horSpan;
                        newLen++;
                        if (left <= 0)
                            break;
                    }
                    rowLen = newLen;
                }

                System.out.println("Extracting range for 0:" + rowNumbers.get(rowId) + ":" + (rowLen - 1) + ":"
                        + rowNumbers.get(rowId));
                XCellRange templateRow = retrievedTableCells.getCellRangeByPosition(0,
                        Integer.parseInt(rowNumbers.get(rowId)), rowLen - 1,
                        Integer.parseInt(rowNumbers.get(rowId)));
                XSelectionSupplier xSelectionSupplier = UnoRuntime.queryInterface(XSelectionSupplier.class,
                        xController);
                xSelectionSupplier.select(templateRow);
                XTransferable transferable = xTransferableSupplier.getTransferable();
                System.out.println("Getting cellRange 0:" + tableRow + ":" + (rowLen - 1) + ":" + tableRow);
                XCellRange newRow = retrievedTableCells.getCellRangeByPosition(0, tableRow, rowLen - 1,
                        tableRow);
                xSelectionSupplier.select(newRow);
                xTransferableSupplier.insertTransferable(transferable);
                //                    }
                for (int tableCol = 0; tableCol < rowLen; tableCol++) {

                    HashMap<String, String> rowMetadata = fieldsLocations.get(rowId);
                    if (rowMetadata.containsKey("" + tableCol)) {
                        String fieldId = rowMetadata.get("" + tableCol);
                        String dataItem = dataRow.get(fieldId);
                        System.out.println("Retrieving cell:" + tableCol + ":" + tableRow);
                        XCell cell = retrievedTableCells.getCellByPosition(tableCol, tableRow);
                        System.out.println(
                                "Setting to cell " + tableCol + ":" + tableRow + " value: " + dataItem);
                        XText cellText = UnoRuntime.queryInterface(XText.class, cell);
                        cellText.setString(dataItem);
                    }
                }
                //                    if (tableRow != 0) {
                tableRow++;
                //                    }
            }
            for (int i = rowNumbers.size() - 1; i >= 0; i--) {
                retrievedTable.getRows().removeByIndex(Integer.parseInt(rowNumbers.get(i)), 1);
            }
        }

        //show/hide frames
        XTextFramesSupplier framesSupplier = UnoRuntime.queryInterface(XTextFramesSupplier.class, document);
        XNameAccess frames = framesSupplier.getTextFrames();
        XTextDocument textDocument = UnoRuntime.queryInterface(XTextDocument.class, document);
        XText text = textDocument.getText();
        for (String fieldName : fields.keySet()) {
            if (!fieldName.startsWith("#")) {
                continue;
            }
            String fieldName2 = fieldName.substring(1);
            String value = fields.get(fieldName);
            if (frames.hasByName(fieldName2)) {
                System.out.println("Checking frame " + fieldName2);
                if (value.trim().equalsIgnoreCase("0")) {
                    System.out.println("Hiding");
                    Object frameContent = frames.getByName(fieldName2);
                    XTextContent frameContentText = UnoRuntime.queryInterface(XTextContent.class, frameContent);
                    text.removeTextContent(frameContentText);
                }
            }
        }

        //update graphic objects
        XTextGraphicObjectsSupplier goSupplier = UnoRuntime.queryInterface(XTextGraphicObjectsSupplier.class,
                document);
        XNameAccess graphicsObjects = goSupplier.getGraphicObjects();
        for (String objName : fields.keySet()) {
            if (!objName.startsWith("@"))
                continue;
            String value = fields.get(objName); //encoded binary image
            byte[] imageData = DatatypeConverter.parseBase64Binary(value);
            File temp = File.createTempFile("image", ".jpg", new File("/tmp"));
            FileOutputStream fos = null;
            fos = new FileOutputStream(temp);
            fos.write(imageData);
            fos.flush();
            fos.close();
            String newURL = temp.getCanonicalPath();
            String goName = objName.substring(1);
            if (graphicsObjects.hasByName(goName)) {
                XPropertySet graphicObject = UnoRuntime.queryInterface(XPropertySet.class,
                        graphicsObjects.getByName(goName));
                graphicObject.setPropertyValue("GraphicURL", "file://" + newURL);
            }
        }

        //transform file

        //save file
        String sSaveURL = "file:///tmp/" + this.getSessionID() + ".pdf";

        XStorable xStorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, document);
        PropertyValue[] propertyValue = new PropertyValue[2];
        propertyValue[0] = new PropertyValue();
        propertyValue[0].Name = "Overwrite";
        propertyValue[0].Value = new Boolean(true);
        propertyValue[1] = new PropertyValue();
        propertyValue[1].Name = "FilterName";
        propertyValue[1].Value = "writer_pdf_Export";

        xStorable.storeToURL(sSaveURL, propertyValue);
        XComponent component = (XComponent) UnoRuntime.queryInterface(XComponent.class, document);
        component.dispose();

        byte[] key = this.getSessionID().getBytes("utf-8");
        File file = new File("/tmp/" + this.getSessionID() + ".pdf");
        is = new FileInputStream(file);
        long length = file.length();

        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        System.out.println("Here");
        jedis.set(key, bytes);
        jedis.expire(key, 30 * 60); //30 minutes to expire
        is.close();
        file.delete();

        //            String url2 = this.getCallbackURL();
        //            if (url2.trim().length()!=0) {
        //              url2 = url2.replace("~SESSION~", this.getSessionID());
        //              URL urlx;
        //              try {
        //                  urlx = new URL(url2);
        //                  urlx.openStream();
        //              } catch (IOException ex) {
        //                  Logger.getLogger(ODT2PDFConverter.class.getName()).log(Level.SEVERE, null, ex);
        //              }
        //            }
        //        XCloseable xCloseable = (XCloseable) UnoRuntime.queryInterface(XCloseable.class, document);
        //        if (xCloseable!=null) {
        //            xCloseable.close(false);
        //        }

    } catch (IOException | Exception | ParseException | BootstrapException ex) {
        Logger.getLogger(ODT2PDFConverter.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(ODT2PDFConverter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}