Insert a document JSON from URL in mongodb with java

I’m new in MongoDb and I have to upload a file in MongoDB with a java program.
I tried to write something but I do not know if it’s the right way.
Can someone help me?
My difficulty is that the json file I have to upload is in a link address.
can mongodb read and upload the document to a database through java language?
I load the code below.
Thank you.

import java.io.IOException;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;


public class mongodb {

public static void main (String args []) throws IOException {

    MongoClient mongo = null;
    MongoDatabase db = null;

    try {
        /**** Connect to MongoDB ****/
        mongo = new MongoClient("localhost", 27017);

        /**** Get database ****/
        db = mongo.getDatabase("db_plant");

        System.out.println("Successfully connected to database");           
    } catch (Exception e) {
        System.err.println( e.getClass().getName() + ": " + e.getMessage() );
    }

    DBCollection collection = db.getCollection("plants");

    final String URL = "https://www.plants.usda.gov/java/downloadData?fileName=plantlst.txt&static=true";
    String json = getTextFromUrl(URL);

    DBObject dbObject = (DBObject)JSON.parse(json);
    collection.insert(dbObject);

    DBCursor cursorDocJSON = collection.find();
    while (cursorDocJSON).hasNext() {
        System.out.println(cursorDocJSON).next();
    }
    collection.remove(new BasicDBObject();
}

private static String getTextFromUrl(String uRL) {
    // TODO Auto-generated method stub
    return null;
}

}

Grey screen when using Windows, but JFrames are fine

This test code making use of JFrames works as intended (will close after 10 secs).

// **** Imports ****
import java.awt.*;
import javax.swing.JFrame;




public class TestDisplay extends JFrame {

// **** Constructor ****

public static void main(String[] args)
{
    DisplayMode dm = 
            new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);

    TestDisplay td = new TestDisplay();
    td.run(dm);
}

// **** Methods ****

public void run(DisplayMode dm)
{
    getContentPane().setBackground(Color.PINK);
    setForeground(Color.WHITE);
    setFont(new Font("Arial", Font.PLAIN, 24));

    Screen s = new Screen();
    try{
        s.setFullScreen(dm, this);
        try{
            Thread.sleep(10000); // Delay before restoring screen (10 secs)
        }catch(Exception ex){}

    }finally{s.restoreScreen();}

}

public void paint(Graphics g) // JFrame calls paint method automatically
{
    super.paint(g);

    if(g instanceof Graphics2D)
    {
        System.out.println("It is Graphics2D");

        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint // Turn on antialiasing for text
    (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    g.drawString("This will be really cool", 200, 200);
}

}

However, when using Windows my grey screen problem persists.
In the TestDisplay > paint method, I encountered the same problem if I removed the “super.paint(g);” line.
These are the following blocks that comprise my code that does not render correctly, but it runs correctly. (Press ESC to close the window)

KeyTest class:

// **** Imports ****
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyTest extends Core implements KeyListener{

// **** Variables ****
private String mess = "";


// **** Constructor ****
public static void main(String[] args)
{
    new KeyTest().run();
}

// **** Methods ****

//init also call init from superclass
public void init()
{
    super.init();
    Window w = s.getFullScreenWindow();
    w.setFocusTraversalKeysEnabled(false); //make wierd buttons not wierd
    w.addKeyListener(this);
    mess = "Press escape to exit!";
}

//key pressed
public void keyPressed(KeyEvent e)
{
    int keyCode = e.getKeyCode();
    if(keyCode == KeyEvent.VK_ESCAPE)
    {
        stop();
    }
    else
    {
        mess = "Pressed : " + KeyEvent.getKeyText(keyCode);
        e.consume(); //prevents button combinations (ex. alt + F = get file)
    }
}

//key released
public void keyReleased(KeyEvent e)
{
    int keyCode = e.getKeyCode();
    mess = "Released : " + KeyEvent.getKeyText(keyCode);
    e.consume(); //prevents button combinations (ex. alt + F = get file)
}

//last method from interface
public void keyTyped(KeyEvent e)
{
    e.consume();
}

//draw 
public synchronized void draw(Graphics2D g)
{
    Window w = s.getFullScreenWindow();

    g.setColor(w.getBackground());
    g.fillRect(0, 0, s.getWidth(), s.getHeight());
    g.drawString(mess, 30, 30);

}
}

Core abstract class:

// **** Imports ****
import java.awt.*;
import javax.swing.*;

public abstract class Core {

// **** Variables ****
private static final DisplayMode[] modes1 = 
{
    new DisplayMode(1920, 1080, 64, 0),
    new DisplayMode(1920, 1080, 32, 0),
    new DisplayMode(800, 600, 32, 0),
    new DisplayMode(800, 600, 24, 0),
    new DisplayMode(800, 600, 26, 0),
    new DisplayMode(640, 480, 32, 0),
    new DisplayMode(640, 480, 24, 0),
    new DisplayMode(640, 480, 16, 0),
};

private boolean running;
protected ScreenManager s;

// **** Constructor ****

// **** Methods ****

//Stop method
public void stop()
{
    running = false;
}

//call init and gameloop
public void run()
{
    try{
        init();
        gameLoop();
    }finally{s.restoreScreen();}

}

//set to full screen
public void init(){
    s = new ScreenManager();
    DisplayMode dm = s.findFirstCompatibleMode(modes1);
    s.setFullScreen(dm);
    Window w = s.getFullScreenWindow();
    w.setFont(new Font("Arial", Font.PLAIN, 20));
    w.setForeground(Color.RED);
    w.setForeground(Color.WHITE);
    running = true;
}

//main gameloop
public void gameLoop()
{
    long startTime = System.currentTimeMillis();
    long cTime = startTime;

    while(running)
    {
        long timePassed = System.currentTimeMillis();
        cTime = cTime + timePassed;

        update(timePassed);

        Graphics2D g = s.getGraphics();
        draw(g);
        g.dispose();
        s.update();

        try{
            Thread.sleep(20);
        }catch(Exception ex){}
    }
}

//update animation
public void update(long timePassed){}

//draws to the screen
public abstract void draw(Graphics2D g);
}

ScreenManager class:

// **** Imports ****
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;


public class ScreenManager {

// **** Variables ****

private GraphicsDevice vc;

// **** Constructor ****

public ScreenManager()
{
    //give vc access to monitor screen
    GraphicsEnvironment e = 
            GraphicsEnvironment.getLocalGraphicsEnvironment();
    vc = e.getDefaultScreenDevice();
}

// **** Methods ****

// ____ Handle Display Modes ____

//get all compatible display modes
public DisplayMode[] getCompatibleDiplayModes(){
    return vc.getDisplayModes();
}

//compares display modes passed into vc and checks for a match
public DisplayMode findFirstCompatibleMode(DisplayMode modes[])
{
    DisplayMode goodModes[] = vc.getDisplayModes();
    for(int x=0; x<modes.length;x++)
    {
        for(int y=0;y<goodModes.length;y++)
        {
            if(displayModesMatch(modes[x], goodModes[y]))
            {
                return modes[x];
            }
        }
    }
    return null;
}

//get current display mode
public DisplayMode getCurrentDisplayMode()
{
    return vc.getDisplayMode();
}

//check if two modes match
public boolean displayModesMatch(DisplayMode m1, DisplayMode m2)
{
    //test if resolution match (if not match, false)
    if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight())
    {
        return false;
    }
    //test if bit depth match ((if not match, false)
    if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI 
            && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI
            && m1.getBitDepth() != m2.getBitDepth())
    {
        return false;
    }
    //test if refresh rate match (if not match, false)
    if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN
            && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN
            && m1.getRefreshRate() != m2.getRefreshRate())
    {
        return false;
    }

    return true;
}

// ____ Handle Graphics ____

//make jframe full screen
public void setFullScreen(DisplayMode dm)
{
    //Frame f = new Frame();
    JFrame f = new JFrame();

    f.setUndecorated(true);
    f.setIgnoreRepaint(true);
    f.setResizable(false);
    vc.setFullScreenWindow(f);

    if(dm != null && vc.isDisplayChangeSupported())
    {
        try{
            vc.setDisplayMode(dm);
        }catch(Exception ex){}
    }
    f.createBufferStrategy(2);
}

// ??? important magic ???
public Graphics2D getGraphics(){
    Window w = vc.getFullScreenWindow();
    if ( w != null)
    {
        BufferStrategy s = w.getBufferStrategy();
        return (Graphics2D)s.getDrawGraphics();
    }
    else
    {
        return null;
    }
}

//updates display
public void update()
{
    Window w = vc.getFullScreenWindow();
    if(w != null)
    {
        BufferStrategy s = w.getBufferStrategy();

        //only display new frame when it is ready
        if(!s.contentsLost())
        {
            s.show();
        }
    }
}

//returns full screen window
public Window getFullScreenWindow()
{
    return vc.getFullScreenWindow();
}

//get Width of window
public int getWidth()
{
    Window w = vc.getFullScreenWindow();
    if(w != null)
    {
        return w.getWidth();
    }
    else
    {
        return 0;
    }
}

//get Height of window
public int getHeight()
{
    Window w = vc.getFullScreenWindow();
    if(w != null)
    {
        return w.getHeight();
    }
    else
    {
        return 0;
    }
}

//get out of fullscreen
public void restoreScreen()
{
    Window w = vc.getFullScreenWindow();
    if (w != null)
    {
        w.dispose();
    }
    vc.setFullScreenWindow(null);
}

//create image compatible with monitor (width, height, transparency)
public BufferedImage createCompatibleImage(int w, int h, int t)
{
    Window win = vc.getFullScreenWindow();
    if(win != null)
    {
        GraphicsConfiguration gc = win.getGraphicsConfiguration();
        return gc.createCompatibleImage(w, h, t);
    }
    return null;
}


}

I would greatly appreciate any ideas you guys might have about solving this.

Android – Button changes backgroundimage for new activity

I want my Button to open a new activity using an intent.
This I already implemented and it works.

My problem is setting the backgroundimage for this new activity.

For example:

  • When button1 got pressed the new activity opens with image1 as
    background.
  • When button2 got pressed the new activity opens with image2 as
    background.

    Would be very nice if someone would know the javacode to implement this feature or where I could find it.

Thank you very much!
Taka

Why is the CDI bean not detected only if it is public?

This one is puzzling me. I created a minimal JAX-RS application based on JavaEE7 running on Wildfly 10.1.

@ApplicationPath("")
public class JAXRSConfiguration extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        return new HashSet<Class<?>>(Arrays.asList(Resource.class));
    }
}

The resource injects a single dummy stateless bean:

@Path("")
public class Resource {

    @Inject
    Manager manager;

    @GET
    @Path("/go")
    public void go() {
        manager.call();
    }
}

This is the bean:

@Stateless
public class Manager {

    @PostConstruct
    private void init() {
        System.out.println("POST CONSTRUCT ");
    }

    void call() {
        System.out.println("called ");
    }
}

Using the browser to execute the GET causes the following error:

org.jboss.resteasy.spi.UnhandledException: org.jboss.weld.exceptions.WeldException: Class org.jboss.weld.util.reflection.Reflections can not access a member of class com.a.b.Manager with modifiers ""

Can post full stack trace but all the Caused By messages are the same.

I searched for this error and it happens when the injected bean is not public, but mine is. I decided to try to remove the public to see what it will complain about and… it works. The bean is injected, any injections it might have are injected, the post construct method is called and all the prints are printed.

This is in complete contrast to Does ejb stateless class has to be public?. What’s going on here?

PCollection to PCollection for BigQuery insertion

I am new to google dataflow. I am trying to get a json from pubsub and put that message in to a list. Then I want to insert that list to a Bigquery raw. I was able to get the message from the pubsub. But not inserting that list in to the Bigquery raw.

Here is my code:

public class PipelineStreamingE {

/** A DoFn that map the message to raws. */
static class JsontoRaws extends DoFn<String, List<EData>> {
@Override
public void processElement(ProcessContext c) {

      c.output(new EDataMapper().mapToERow(c.element()));

 }
}

/**
  * Converts strings into BigQuery rows.
 */
 static class EToRowConverter extends DoFn<List<EData>, TableRow> {
  /**
   * In this example, put the whole string into single BigQuery field.
   */
  @Override
  public void processElement(ProcessContext c) {
    c.output(new 
   TableRow().set("patientID",c.element().Patientid)
  .set("TimeStamp",c.element().timestamp));
  }

  static TableSchema getSchema() {
  return new TableSchema().setFields(new ArrayList<TableFieldSchema>() {
        // Compose the list of TableFieldSchema from tableSchema.
        {
          add(new TableFieldSchema().setName("patientID").setType("INT"));
          add(new 
   TableFieldSchema().setName("TimeStamp").setType("TIMESTAMP"));
         // add(new 
    TableFieldSchema().setName("TimeStamp").setType("TIMESTAMP"));
        }
   });
  }
 }

/**
* Options supported by {@link StreamingWordExtract}.
*
* <p>Inherits standard configuration options.
*/
private interface StreamingWordExtractOptions
  extends ExamplePubsubTopicOptions, ExampleBigQueryTableOptions {
  @Description("Input file to inject to Pub/Sub topic")
 @Default.String("")
 String getInputFile();
 void setInputFile(String value);
 }


public static void main(String[] args) throws IOException {
  StreamingWordExtractOptions options = 
  PipelineOptionsFactory.fromArgs(args)
    .withValidation()
    .as(StreamingWordExtractOptions.class);
 options.setStreaming(true);

 options.setRunner(DataflowPipelineRunner.class);

options.setBigQuerySchema(EToRowConverter.getSchema());
DataflowExampleUtils dataflowUtils = new DataflowExampleUtils(options);
dataflowUtils.setup();

Pipeline pipeline = Pipeline.create(options);

String tableSpec = new StringBuilder()
    .append(options.getProject()).append(":")
    .append(options.getBigQueryDataset()).append(".")
    .append(options.getBigQueryTable())
    .toString();
pipeline
    .apply(PubsubIO.Read.topic("projects/xxx/topics/xxx"))
    .apply(ParDo.of(new JsontoRaws()))

    .apply(ParDo.of(new EToRowConverter()))
    .apply(BigQueryIO.Write.to(tableSpec)
        .withSchema(EToRowConverter.getSchema()));

PipelineResult result = pipeline.run();

if (!options.getInputFile().isEmpty()) {
  // Inject the data into the Pub/Sub topic with a Dataflow batch pipeline.
  dataflowUtils.runInjectorPipeline(options.getInputFile(), options.getPubsubTopic());
}

// dataflowUtils will try to cancel the pipeline and the injector before the program exists.
dataflowUtils.waitToFinish(result);
 }

}

I am having a trouble in class EToRowConverter. I’m probably just forgetting something basic, so I hope you guys can help me with this …

Android glow effect on 40+ textview objects

I am trying to figure out the best way to reproduce a glow effect around text view object. The best glow comes from using a 9ppatch image from http://inloop.github.io/shadow4android/ . The problem is i need to display 40+ textview objects on screen at a time. Is it advisable to use a 9patch image for them ? . I have tried making a XML drawable for background to reproduce a shadow effect but it does not look as natural as the 9 patch image( it has sharp breaks when the padding changes opacity) something like this –

<!-- Drop Shadow Stack -->
<item>
    <shape>
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#107575FF" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape>
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#207575FF" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape>
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#307575FF" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape>
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#407575FF" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape>
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp"/>

        <solid android:color="#507575FF" />

        <corners android:radius="3dp" />
    </shape>
</item>

<!-- Background -->
<item>
    <shape>
        <solid android:color="#7575FF" />

        <corners android:radius="3dp" />
    </shape>
</item>

java spring boot fetch values from db before starting up

I am new to java and spring boot (ard 1 month exp).
Can anyone tell me how can i load data from memory before starting the application.

Example:

I have info in db say gender

TABLE : gender
F : Female
M : Male

TABLE : COUNTRY
1 : US
2 : UK
3 : RUSSIA

So before application start i want this data shoulw be fetched from db and load to my application.

I am using java + sprint boot + JPA

I have deployed my WAR in JBOSS environment but on login i`m getting this error

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 407 in the jsp file: /jsp/administration/MainMenuHorizontal.jsp
The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files
404:
405: //This is for displaying the footer data
406: //strFooterData.append(“”).append(objMenu.getMenuName());
407: strFooterData.append(“”).append(objMenu.getMenuName());
408: /*
409: * First adding to an arraylist coz fist the TD needs to be equally distributed
410: * so cant know the number in the begining itself

Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:446)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:362)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:607)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:312)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:326)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:253)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1063)
org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:263)
org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:386)
org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:318)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:229)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
note The full stack trace of the root cause is available in the JBoss Web/3.0.0-CR2 logs.

How can I combine the Annotation and Content Layers of PDF?

I used this command in combining the annotation and content layers of pdf. Here’s the command:

gs -dSAFER -dBATCH -dNOPAUSE -dNOCACHE -sDEVICE=pdfwrite 
    -sColorConversionStrategy=/LeaveColorUnchanged  
    -dAutoFilterColorImages=true 
    -dAutoFilterGrayImages=true 
    -dDownsampleMonoImages=true 
    -dDownsampleGrayImages=true 
    -dDownsampleColorImages=true 
    -sOutputFile=document_flat.pdf document_original.pdf

I got that idea above from this link.

Is there another way to combine the content and annotation layers of pdf or what they called flattening of pdf?

How to integrate Python code with UIMA framework

I am considering 3 methods to integrate Python code with UIMA framework.

  1. UIMACPP. It is suggested by UIMA official document. But I noticed that it was only test in python 2.4 while my code is written in python 2.7.
  2. Jython. As my code import extensions written in C (e.g. NumPy), this interpreter seems not work. I also found JyNI, but some people suggest that it is not mature enough to support NumPy as long as it is still in alpha-state….
  3. REST API. Create a light-weight REST API over Python code. Then call the REST API in the UIMA annotator. I am wondering how to submit the input to the API and how to call the API to collect the out put via UIMA annotator.