Accessing Hashmap values from another class

I have created 3 HashMaps in a Database class. And I want to check for a certain value in a hashmap before adding an item. So I want to check my Retailer HashMap for a specific value, and if that value exists, I add certain items.
I’m not sure how to call the hashmap from another class or how to code that loop, where am I going wrong?

My HashMap creation:

private static Map<Long, User> users = new HashMap<>();
private static Map<Long, Retailer> retailers = new HashMap<>();
private static Map<Long, Item> items = new HashMap<>(); 

My method to create an item/items:

public ItemService(){

    items.put(1l, new Item(1, "Black Suit Shoes", "Black" , "11"));
    items.put(2l, new Item(2, "Nike Runners", "Red" , "7"));
    items.put(3l, new Item(3, "Nike Sports Socks", "Yellow" , "4"));
}

I want to make sure a retailer with a specific Id exists, and if it does, then add these items.

Convert .APK to .CAP

I need to get .CAP file from .APK file. How will we do that conversion. is there any online or offline tools available to convert it. If anyone know about that. kindly let me know. Thank you in advance.

What is timerSeekBar in this java code an object or variable?What is findViewById,

I checked findViewById is a method so what is timerSeekBar, an object or a variable,got told its a variable but we are calling methods with it so it should’nt it be an object.Please explain why are we writing SeekBar before findViewById.

SeekBar -Class,findViewById- Method ?,timerSeekBar- variable or object?

SeekBar timerSeekBar = (SeekBar)findViewById(R.id.timerSeekBar);

timerSeekBar.setMax(600);
timerSeekBar.setProgress(30);

another eg-

TextView answerLabel = (TextView) findViewById(R.id.button1);

Image

JavaScript error: undefined, line 492: Component returned failure code:

I am new to selenium, and getting this below error.

Selenium 3.4.0 Firefox browser 47.0.2 geckodriver-v0.16.1-win64

Please help on this, Thanks in advance. 🙂

The below is testcode:
System.setProperty(“webdriver.gecko.driver”,”C:UsersUserDownloadsgeckodriver-v0.16.1-win64geckodriver.exe”);

    /*   DesiredCapabilities capabilities = DesiredCapabilities.firefox();
       capabilities.setCapability("marionette", false); // true getting : AddonManager is not initialized
       WebDriver driver = new FirefoxDriver(capabilities); */

    driver = new FirefoxDriver();
    vURL = "http://www.facebook.com";
    driver.navigate().to(vURL);

    driver.findElement(By.xpath("//*[@id='day']")).sendKeys("9");
    driver.quit();

JavaScript error: undefined, line 492: Component returned failure
code: 0x8000ffff (NS_ERROR_UNEXPECTED) [nsIPrefBranch.getCharPref]
JavaScript error: resource://gre/modules/AddonManager.jsm, line 2484:
NS_ERROR_NOT_INITIALIZED: AddonManager is not initialized Oct 11, 2017
3:43:19 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C

Keeping track of an object’s location in Firebase

When using Firebase to store and retrieve objects created by the user (for example: posts or comments), it becomes necessary to pass these objects around the application. But what is the suggested way to keep track of the associated DatabaseReference or the unique key from the database?

Example scenario

A simple to do list app allows the user to freely add, edit and remove items in their list. So when the user creates an item, something similar to the below would happen:

private Item storeItem(String title) {
    String key = mDatabase.child("items").push().getKey(); // Where do we keep this key?
    Item item = new Item(title);

    mDatabase.child("items").child(key).setValue(item);

    return item;
}

Where Item is this Java object:

public class Item {
    private String title;
    private String description;

    public Item() {}

    public Item(String title) {
        this.title = title;
    }

    // ...
}

Behind the scenes, this item is added to a RecyclerView, either by adding the returned Item to the adapter or when a ChildEventListener attached to the “items” reference is called.

The user then wishes to rename this new item or add text to the description field, so tapping on it in the RecyclerView starts a separate Activity which receives the passed Item and uses getters/setters to make changes.

Now, we’ll need to save these changes to the database, which we can do by calling setValue() again, as above. However, we didn’t store the key variable from storeItem() so we don’t know where this item is currently stored in the database.

So, where can we keep track of the created item’s key for later use to save changes back to the database?

Possible solutions

There are a number of different paths we could take here, but I’m looking for some guidance on the suggested method, as the Firebase documentation doesn’t mention this hurdle. I’ve outlined some examples rthat I can think of:

  • Store the key inside the object. We could add another field to the Item object to store the database key. So within the previous storeItem() method, the key variable is added to the Item constructor and stored in the database as a field.
  • Create a wrapper object. We could wrap the Item object in a container that has methods such as getItem() and getKey() or getDatabaseReference() and then pass this around the app instead of the Item itself.
  • Use the DataSnapshot instead. Once the item is created, wait until an attached listener receives it, then use and pass around the retrieved DataSnapshot, which has methods for getKey() and getRef().
  • Retrieve the object every time it is needed. Instead of passing the Java object Item around the app, we could retrieve it from the database every time it is needed, by using the key or DatabaseReference.

Wrapping up

Looking back on this huge question, it seems I might have overcomplicated it a little, but I wanted to be thorough in my explanation. I’m also hoping that it’s not purely opinion-based and there currently is some standard way to achieve this.

So I guess my question is: is there a standard method to handle and make changes to Java objects stored in Firebase?

org.springframework.context.NoSuchMessageException: No message found under code ” for locale ‘en’

I am using Spring MVC to develop one application to display error message i done changes in spring-servlet.xml like below

<bean id="messageSource"    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames" value="classpath:resources/ApplicationResources,/>
<property name="fallbackToSystemLocale" value="false"/> 
<property name="defaultEncoding" value="ISO-8859-1" />
</bean>

But still i am getting
No message found under code ” for locale ‘en’ exception,
can someone help me in this issue.

Pyspark throws Java gateway exception if I open a file before getting a SparkContext()

I am using pyspark on Jupyter Notebook with Spark 2.1.1 cluster running on IP “172.30.0.163:7077” (spark master IP)
I am able to create a SparkContext successfully.

But, I want to read spark_master_ip and spark.cores.max from a .properties file (instead of hard coding it). When I try to read my custom spark properties file in ‘myspark_config.properties‘ file (which I parse and read successfully), but I get the following Java gateway exception, when I try to create SparkContext().
Here is my code:

import pyspark
from pprint import pprint
from pyspark import SparkConf
def getproperties():
    """Get Spark configuration properties in python dictionary"""
    global properties
    properties = dict()
    with open('myspark_config.properties') as f:
        for line in f:
                if not line.startswith('#') and not line.startswith('n'):
                    tokens = line.split('=')
                    tokens[0] = tokens[0].strip()
                    tokens[1] = "=".join(tokens[1:])
                    properties[tokens[0]] = tokens[1].strip()

        f.close()
    pprint(properties)
    return(properties)
properties = getproperties()

conf = (SparkConf()
            .setMaster(properties["spark_master_url"])
            .setAppName("testApp")
            .set('spark.cores.max',properties["spark_app_cores"])
            .set('spark.executor.memory',properties["spark_app_memory"])
            .set('spark.dynamicAllocation.enabled','true')
            .set('spark.shuffle.service.enabled','true')

            )
# conf = (SparkConf()
#             .setMaster("spark://172.30.0.163:7077")
#             .setAppName("testApp")
#             .set('spark.cores.max',"2")
#             .set('spark.executor.memory',"2G")
#             .set('spark.dynamicAllocation.enabled','true')
#             .set('spark.shuffle.service.enabled','true')
#         )
sc = pyspark.SparkContext(conf=conf)

I do not get any exceptions and my code runs smoothly if I don’t read from file and hard code the spark master in SparkConf() (currently it is commented). “JAVA_HOME”,”SPARK_HOME” “PYTHONPATH” are set successfully and I am not using Anaconda. I am using Jupyter notebook on python 2.7 on ubuntu and spark-2.1.1

{'spark_app_cores': '"2"',
 'spark_app_memory': '"2G"',
 'spark_master_url': '"spark://172.30.0.163:7077"'}

Exception                                 Traceback (most recent call last)
<ipython-input-1-c893eaf079f2> in <module>()
     36 #             .set('spark.shuffle.service.enabled','true')
     37 #         )
---> 38 sc = pyspark.SparkContext(conf=conf)

/usr/local/spark/python/pyspark/context.py in __init__(self, master, appName, sparkHome, pyFiles, environment, batchSize, serializer, conf, gateway, jsc, profiler_cls)
    113         """
    114         self._callsite = first_spark_call() or CallSite(None, None, None)
--> 115         SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
    116         try:
    117             self._do_init(master, appName, sparkHome, pyFiles, environment, batchSize, serializer,

/usr/local/spark/python/pyspark/context.py in _ensure_initialized(cls, instance, gateway, conf)
    281         with SparkContext._lock:
    282             if not SparkContext._gateway:
--> 283                 SparkContext._gateway = gateway or launch_gateway(conf)
    284                 SparkContext._jvm = SparkContext._gateway.jvm
    285 

/usr/local/spark/python/pyspark/java_gateway.py in launch_gateway(conf)
     93                 callback_socket.close()
     94         if gateway_port is None:
---> 95             raise Exception("Java gateway process exited before sending the driver its port number")
     96 
     97         # In Windows, ensure the Java child processes do not linger after Python has exited.

Exception: Java gateway process exited before sending the driver its port number

I have looked through various links but found no solution:
pyspark java gateway error stackoverflow
Github issue on java Gateway

Regarding docx to pdf conversion error

When we are trying to convert the docx velocity template to pdf we are facing following error.

An error has occurred while generating the report. Check the template syntax

Error detail:org.apache.poi.xwpf.converter.core.XWPFConverterException: java.lang.ArrayIndexOutOfBoundsException: 3

We are using fr.opensagres.xdocreport.converter.docx.xwpf’, version: ‘1.0.5’ jar file. We have also test it with version 2.0.1 but facing the same issue.

‘fr.opensagres.xdocreport’ jar version is 1.0.6
‘fr.opensagres.xdocreport.template’ jar version is ‘2.0.0’

Find below sample template in which we are facing error.

«#set($sheetTitle=”Additional Elements”)»«#set($viewName=”Default”)»«#set($columns={})»«$!{columns.put(“DLARef”,”Matter Referenc»«$!{columns.put(“ACO”,”Assigned Case Owne»«$!{columns.put(“ACOEmail”,”ACO Email Add»«$!{columns.put(“Salutation1”,”Salutation»«$!{columns.put(“ForeName1”,”ForeName(s) »«$!{columns.put(“Surname1″,”Surname #1”)}»«$!{columns.put(“Salutation2”,”Salutation»«$!{columns.put(“ForeName2”,”ForeName(s) »«$!{columns.put(“Surname2″,”Surname #2”)}»«$!{columns.put(“Salutation3”,”Salutation»«$!{columns.put(“ForeName3”,”ForeName(s) »«$!{columns.put(“Surname3″,”Surname #3”)}»«$!{columns.put(“Salutation4”,”Salutation»«$!{columns.put(“ForeName4”,”ForeName(s) »«$!{columns.put(“Surname4″,”Surname #4”)}»«$!{columns.put(“Property”,”Property Addr»«$!{columns.put(“City”,”City or Town”)}»«$!{columns.put(“Postcode”,”Postcode”)}»«$!{columns.put(“CompanyName”,”Name of Co»«$!{columns.put(“SolicitorsName”,”Solicit»«$!{columns.put(“SolicitorsAddress”,”Soli»«$!{columns.put(“SolicitorsRef”,”Solicito»«$!{columns.put(“HOPBand”,”Relevant HOP B»«$!{columns.put(“ProposedPayment”,”Value »«#set($data=$utils.getSheetDocReportDataM»«#set($record=$data.values().iterator().n»

Rest Web Service (Post) in eclipse not working

I need to create a Web Service that uses the Post method.

The programs i am using is:
Plsql developer – This is my database that I want to post data to.
Eclipse – This is the java program I am using to code my web services with.
SoapUI – This is the program I am using to deploy my rest method.

I tried a few Post Methods and they have all failed me.

public class AgentDAO {


public List<Agent> selectAgents() throws SQLException {

    Connection dbConnection = null;
    PreparedStatement statement = null;

    List<Agent> agents = new ArrayList<Agent>();

    String selectTableSQL = "SELECT * from AGENTS";

    try {

        dbConnection = getDBConnection();
        statement = dbConnection.prepareStatement(selectTableSQL);


        System.out.println(selectTableSQL);

        // execute select SQL statement
        ResultSet rs = statement.executeQuery();

        while (rs.next()) {

            Agent agent = new Agent();
            agent.setAgentId(rs.getBigDecimal("AGENT_ID"));
            agent.setName(rs.getString("FNAME"));
            agent.setLastName(rs.getString("LNAME"));
            agent.setEmail(rs.getString("EMAIL"));
            agent.setDepartment(rs.getString("DEPARTMENT"));
            agent.setCountry(rs.getString("COUNTRY"));

            agents.add(agent);

        }

    } catch (SQLException e) {

        System.out.println(e.getMessage());


    } finally {

        if (statement != null) {
            statement.close();
        }

        if (dbConnection != null) {
            dbConnection.close();
        }

    }

    return agents;

}

public void updateAgent(Agent agent) throws SQLException {
    System.out.println("Method update");
    Connection dbConnection = null;
    PreparedStatement statement = null;
    String updateTableSQL = "UPDATE AGENTS" + " SET FNAME = ?, " + "  LNAME 
     = ?, " + "  DEPARTMENT = ?, "
            + "  EMAIL  = ?, " + "  COUNTRY = ? " + "  WHERE AGENT_ID = ?";

    try {

        dbConnection = getDBConnection();
        statement = dbConnection.prepareStatement(updateTableSQL);
        statement.setString(1, agent.getName());
        statement.setString(2, agent.getLastName());
        statement.setString(3, agent.getDepartment());
        statement.setString(4, agent.getEmail());
        statement.setString(5, agent.getCountry());
        statement.setBigDecimal(6, agent.getAgentId());


        System.out.println(updateTableSQL);
        // execute update SQL statement
        statement.executeUpdate();


    } catch (SQLException e) {

        System.out.println(e.getMessage());


    } finally {

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if (dbConnection != null) {
            try {
                dbConnection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

public void deleteAgent(Agent agent) throws SQLException {

    Connection dbConnection = null;
    PreparedStatement statement = null;

    String deleteTableSQL = "DELETE AGENTS WHERE AGENT_ID = ?";

    try {

        dbConnection = getDBConnection();
        statement = dbConnection.prepareStatement(deleteTableSQL);
        statement.setBigDecimal(1, agent.getAgentId());

        System.out.println(deleteTableSQL);

        // execute delete SQL statement
        statement.execute();

        System.out.println("Record is deleted from AGENTS table!");

    } catch (SQLException e) {

        System.out.println(e.getMessage());


    } finally {

        if (statement != null) {
            statement.close();
        }

        if (dbConnection != null) {
            dbConnection.close();
        }

    }

}

public void insertAgent(Agent agent) throws SQLException {

    Connection dbConnection = null;
    PreparedStatement statement = null;

    String insertTableSQL = "INSERT INTO AGENTS" + "(AGENT_ID, FNAME, LNAME, DEPARTMENT, EMAIL, COUNTRY) "
            + "VALUES" + "(?,?,?,?,?,?)";

    try {


        TimeZone testtime = TimeZone.getTimeZone("GMT+2");
        TimeZone.setDefault(testtime);
        dbConnection = getDBConnection();
        statement = dbConnection.prepareStatement(insertTableSQL);

        statement.setBigDecimal(1, agent.getAgentId());
        statement.setString(2, agent.getName());
        statement.setString(3, agent.getLastName());
        statement.setString(4, agent.getDepartment());
        statement.setString(5, agent.getEmail());
        statement.setString(6, agent.getCountry());


        System.out.println(insertTableSQL);

        // execute insert SQL statement

        statement.executeUpdate();
        // logger.info("AgentDAO - END");
        System.out.println("Record is inserted into AGENTS table!");

    } catch (SQLException e) {

        System.out.println(e.getMessage());


    } finally {

        if (statement != null) {
            statement.close();
        }

        if (dbConnection != null) {
            dbConnection.close();
        }

    }

}

private static Connection getDBConnection() {

    Connection dbConnection = null;

    try {

        Class.forName(DB_DRIVER);

    } catch (ClassNotFoundException e) {

        System.out.println(e.getMessage());

    }

    try {

        dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
        return dbConnection;

    } catch (SQLException e) {

        System.out.println(e.getMessage());


    }

    return dbConnection;

}

}

This is my code that selects, updates, deletes and adds data to my plsql database.

public class Agent {

private BigDecimal agentId;
private String name;
private String lastName;
private String department;
private String email;
private String country;

public BigDecimal getAgentId() {
    return agentId;
}
public void setAgentId(BigDecimal agentId) {
    this.agentId = agentId;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public String getDepartment() {
    return department;
}
public void setDepartment(String department) {
    this.department = department;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}
public String getCountry() {
    return country;
}
public void setCountry(String country) {
    this.country = country;
}

@Override
public String toString() {
    return "Agent [agentId=" + agentId + ", name=" + name + ", lastName=" + lastName + ", department=" + department
            + ", email=" + email + ", country=" + country + "]";
}

}

This is how my model looks like.
Now for the part where I am struggling. I have a get method that works really good but then….. the POST……….

@GET
@Produces(MediaType.APPLICATION_XML)

public List<Agent> selectAgents() throws SQLException {
    return agents.selectAgents();
}

@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public String insertAgent(Agent agent) {


     try {
        agents.insertAgent(agent);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

@GET
@Path("/{agentid}")
@Produces(MediaType.APPLICATION_XML)
public List<Agent> getAgent(@PathParam("agentid") BigDecimal id) {

    try {
        return agents.selectAgents();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

When I run my post method in SoapUI I get this error in the raw data file.

HTTP/1.1 400 Bad Request
Connection: close
Date: Wed, 11 Oct 2017 06:55:51 GMT
Content-Length: 11
Content-Type: text/html; charset=UTF-8
X-ORACLE-DMS-ECID: 4b097786-3b8a-40f3-83c6-c337eb9db63e-000042d8
X-ORACLE-DMS-RID: 0

Bad Request

So then I tried different POST methods for my different tables that I have and I got different errors.

@POST
@Produces(MediaType.APPLICATION_XML)
public String insertComment() {
    return "Post works!";
}

I wanted to see if I would actually get at least something back but then I got this back:

HTTP/1.1 500 Internal Server Error
Connection: close
Date: Wed, 11 Oct 2017 07:01:51 GMT
Content-Length: 15
Content-Type: text/html; charset=UTF-8
X-ORACLE-DMS-ECID: 4b097786-3b8a-40f3-83c6-c337eb9db63e-000042e0
X-ORACLE-DMS-RID: 0

Request failed.

Then I tried

@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response insertCustomer(Customer customer) throws URISyntaxException
{
    if(customer == null){
        return Response.status(400).entity(" Insert details !!").build();
    }

    if(customer.getFname() == null) {
        return Response.status(400).entity("Enter First name !!").build();
    }

    return Response.created(new 
  URI("/customerid"+customer.getCustId())).build();
  }

And I got the error

HTTP/1.1 415 Unsupported Media Type
Connection: close
Date: Wed, 11 Oct 2017 06:59:42 GMT
Content-Length: 22
Content-Type: text/html; charset=UTF-8
X-ORACLE-DMS-ECID: 4b097786-3b8a-40f3-83c6-c337eb9db63e-000042dd
X-ORACLE-DMS-RID: 0

Unsupported Media Type