Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
ColumnarPad
Oct 15, 2008
Trying to write an Android app that connects to Amazon AWS SqlExpress acct.

This is the relevant code:

code:
...
    import java.sql.*;
    import net.sourceforge.jtds.jdbc.*;
    import net.sourceforge.jtds.jdbcx.*;

    public class MainAct extends Activity
        {
        TextView txtMsg;
        Button btnStart;
        Connection conn = null;

        @Override public void onCreate(Bundle savedInstanceState)
            {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            txtMsg= (TextView) findViewById(R.id.txtMsg);
            btnStart = (Button) findViewById(R.id.btnStart);

            btnStart.setOnClickListener(
                new View.OnClickListener()
                {
                @Override public void onClick(View v)
                    {
                    query2();
                    }
                }
                );
            }//End onCreate

        public void WaitForConnection(Connection AsyncConn)
            {
            conn = AsyncConn;
            }//End WaitForConnection

        public void query2()
            {

            try
                {
                String driver = "net.sourceforge.jtds.jdbc.Driver";
                Class.forName(driver).newInstance();

                new TestAsynch().execute();
                }

            catch (SQLException e)
                {
                txtMsg.append("Exception = " + e.getMessage());
                Log.w("Error connection", "" + e.getMessage());
                }

            catch (Exception e)
                {
                txtMsg.append("\nException = " + e.getMessage());
                Log.w("Error connection", "" + e.getMessage());
                }
            }//End query2

        //-----------------------------------------------------------------------
        class TestAsynch extends AsyncTask<Connection, Void, Connection>
            {

            protected void onPreExecute()
                {
                txtMsg.append("\nIn onPreExecute");
                Log.d("PreExecute", "On pre Execute......");
                }//End onPreExecute

            protected Connection doInBackground(Connection... arg0)
                {
                Log.d("DoInBackGround", "On doInBackground...");

                Connection conn = null;         

                String connString
                    = "jdbc:jtds:sqlserver://ecp-clientmgr.cycyg6emdsi3.us-east-1.rds.amazonaws.com:1433/XXXDBNameXXX;" +
                    "encrypt=false;user=XXXUserNameXXX;password=XXXXXX;instance=SQLEXPRESS;";

                try
                    {
                    conn = DriverManager.getConnection(connString);
                    }
                catch (SQLException e)
                    {
                    Log.w("Error connection", "" + e.getMessage());
                    }
                catch (Exception e)
                    {
                    Log.w("Error connection", "" + e.getMessage());
                    }

                return conn;            
                }//End doInBackground

            protected void onPostExecute(Connection result)
                {
                WaitForConnection(result);
                }//End onPostExecute
            }//End TestSynch
        }//End MainAct
All works correctly up to the call to 'conn = DriverManager.getConnection(connString);' in query2.

At that point it blows up somewhere in the attempt to make the connection with an 'unhandled exception'. The main thread completes correctly, and all the log messages and writes to the txtView on the main activity occur before the main finishes, but the thread on which the connection call is made blows up.

I can't figure out what the exception is and, therefore, can't catch it. I don't know what else to try.

One other thing that's strange, is that even though the SourceForge call 'Class.forName(driver).newInstance();' seems happy, the system reports that the imports 'net.sourceforge.jtds.jdbc.;' and 'import net.sourceforge.jtds.jdbcx.;' are both unused.

SO:
1). I've imported the drivers from SourceForge (The .jar is in the lib folder).
2). I've put the GetConnection call on a separate thread (not on the main).
3). I know for certain that the AWS SQLExpress setup works from my desktop with the Server url, login, and password I'm using, and it's lightning fast.
4). I've put the internet permission in the manifest.

I've read everything I can find but nobody has answered the question of how to do this end to end. Also, please don't tell me to use a web service or a php script. I am aware of the security concerns.

Thank you in advance for any help you can give me.

Adbot
ADBOT LOVES YOU

TheresaJayne
Jul 1, 2011

supermikhail posted:

I tried to be fancy with a search field the following way:
code:
    private void filterFieldFocusGained(java.awt.event.FocusEvent evt) {                                        
        if (searchTerm == null) {
            filterField.setText("");
        }
        filterField.setForeground(UIManager.getColor("TextField.foreground"));
    }                                       

    private void filterFieldFocusLost(java.awt.event.FocusEvent evt) {                                      
        if (searchTerm == null) {
            filterField.setText(EMPTY_SEARCH_MESSAGE);
            filterField.setForeground(UIManager.getColor("TextField.inactiveForeground"));
        }
    }
That is, when the field is empty, I put in a message indicating what it's for, but to avoid then searching for the message, I have the searchTerm variable. Now I have a problem that I can't paste the clipboard into the empty field from a popup menu (keyboard shortcuts work). I'm not sure how to approach this - maybe mouse events, or just scrap the message system and replace it with the regular popup hint. What do you goons think?

Hook into the onChange event as well as the focus event

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Max Facetime posted:

Would something like this work? I didn't try running it or anything...

Java code:
class EnumDeserializer<E extends Enum<E>> implements JsonDeserializer<Enum<E>> {
:words:

The problem with this is that Java wants me to declare E at instantiation time, which means that this deserializes a Enum, instead of every enum.

A coworker managed to cheat a solution into place that is (mostly) type-safe:

Java code:
public class EnumDeserializer implements JsonDeserializer<Enum<?>> {
    private static final Logger log = LoggerFactory.getLogger(EnumDeserializer.class);
 
    @Override
    public Enum<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return innerDeserialize(json, typeOfT);
    }

    private <E extends Enum<E>> Enum<E> innerDeserialize(JsonElement json, Type typeOfT) {
        try {
            @SuppressWarning("unchecked")
            final Class<E> clazz = (Class<E>) Class.forName(typeOfT.getTypeName());
            final String strValue = json.getAsString();
 
            // see if there is an exact match first
            final Optional<E> exactMatch = Enums.getIfPresent(clazz, strValue);
            if (exactMatch.isPresent()) {
                return exactMatch.get();
            }
 
            //if there is no exact match, return the first case-insensitive match
            for (Enum<E> e : clazz.getEnumConstants()) {
                if (strValue.equalsIgnoreCase(e.name())) {
                    return e;
                }
            }
        } catch (ClassNotFoundException | ClassCastException e) {
            log.error("Got an unexpected type; substituting null", e);
        }
 
        return null;
    }
}
:toot:

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."

TheresaJayne posted:

Hook into the onChange event as well as the focus event

You mean "onPropertyChange". I spent a while trying to find a ChangeListener hook. :downs: Now to figure out what exactly to put there. Thanks for your input.

Wait, apparently the only available property this way is "foreground". Hm.

Goddammit. So, what's happening is, if the field has focus, you bring up the popup, the field loses focus, you paste, the field probably adds text to the document, then immediately gains focus and loses all text as per my instructions. If it doesn't initially have focus, it simply adds text to the empty field message, and mucking about with the clipboard doesn't seem to help. I'm getting closer and closer to settling for a simple tooltip as an alternative for having unpredictable behavior.

supermikhail fucked around with this message at 10:58 on Jul 25, 2014

Max Facetime
Apr 18, 2009

Gravity Pike posted:

The problem with this is that Java wants me to declare E at instantiation time, which means that this deserializes a Enum, instead of every enum.

Yes, it needs some enum at instantiation time if you instantiate it like that, but the object won't know which type E is because the type gets erased. And since the class object of E isn't passed to the deserializer it isn't capable of enforcing just that enum type.

Or you could do
Java code:
Gson GSON = new GsonBuilder().registerTypeAdapter(Enum.class, new EnumDeserializer<>()).create();

// or

EnumDeserializer<?> enumDeserializer = new EnumDeserializer<>();
Gson GSON = new GsonBuilder().registerTypeAdapter(Enum.class, enumDeserializer).create();
I guess.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

ColumnarPad posted:

Trying to write an Android app that connects to Amazon AWS SqlExpress acct.

All works correctly up to the call to 'conn = DriverManager.getConnection(connString);' in query2.

At that point it blows up somewhere in the attempt to make the connection with an 'unhandled exception'. The main thread completes correctly, and all the log messages and writes to the txtView on the main activity occur before the main finishes, but the thread on which the connection call is made blows up.

I can't figure out what the exception is and, therefore, can't catch it. I don't know what else to try.

Can't you just catch generic Exception or even Throwable? Once you know what it is you can figure out how to deal with it properly.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

Kilson posted:

Can't you just catch generic Exception or even Throwable? Once you know what it is you can figure out how to deal with it properly.

Basically this. Additionally, unhandled exceptions get logged out to logcat by class name, along with the stack trace and any other relevant info that toString sees fit to provide.

Also, there's an Android thread :v:

Edmond Dantes
Sep 12, 2007

Reactor: Online
Sensors: Online
Weapons: Online

ALL SYSTEMS NOMINAL
I'm gonna have to do some work with Spring rather soon, and I've never touched it. Any recommended places to get started?

more like dICK
Feb 15, 2010

This is inevitable.
Spring in Action is a good book if you're willing to spend money. Otherwise the official docs are good, and as far as I can tell everyone who's ever used Spring has written a blog post about what they did with it. It's a very googleable subject.

Edmond Dantes
Sep 12, 2007

Reactor: Online
Sensors: Online
Weapons: Online

ALL SYSTEMS NOMINAL
Yeah, my plan was basically see what I needed to do and then just google it, but that's how I usually do things and I wanted to get a headstart this time. I'll take a look at the official docs for now, but I'll bookmark that book to get later; I haven't used Spring in any positions so far and I'm realizing (a bit late) that it's a tool I actually should have.

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

Kilson posted:

Unfortunately, the machine with the problems is not a machine I have access to, so I can't play around with it. I've looked at a couple VMs with similar allocations and haven't seen the problem there.
Can you get a GC log? If you're not already, run with


-XX:+PrintGC
-XX:+PrintGCDetails
-verbose:gc
-Xloggc:gc.log


and see how far it gets.

My prediction is that this is somehow happening in a full GC (which is O(size of the whole heap) as opposed to O(size of the live set), hence why you're seeing it happen when you increase the heap size), but it's not clear to me either why it's happening.

Dijkstracula fucked around with this message at 17:23 on Aug 4, 2014

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
Oh, man, this is too complicated. I'm trying to change a class without breaking serialization. Right now it has a private final ArrayList<String> and I want to make a wrapper class for that String, because that string actually means something. I thought I just introduce another ArrayList with the wrapper, and where I read the object I check which arrayList is null and switch'em. My main doubt is that I'd need to change the original ArrayList to not final, and I'm not sure that's allowed. Also they'd have to share the getter.

Anyway, do you think it's a good idea, and doable?

Workaday Wizard
Oct 23, 2009

by Pragmatica
Is there a way to get maven-style dependency management (automatic downloading of dependencies) while keeping my projects as an eclipse project?

I know eclipse has maven support but the thing I want to make requires multiple projects with dependencies and I simply don't know maven that well (is it me or is the learning curve for maven a wall?).
It's a personal hobby project.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Shinku ABOOKEN posted:

Is there a way to get maven-style dependency management (automatic downloading of dependencies) while keeping my projects as an eclipse project?

I know eclipse has maven support but the thing I want to make requires multiple projects with dependencies and I simply don't know maven that well (is it me or is the learning curve for maven a wall?).
It's a personal hobby project.

The parent project with child modules is very common, I think it would be worth your time to utilize it. Maven can definitely be a little funky, but in almost every case somebody has done exactly what you will try to do with it before, and their blog post about how to do it is only a Google search away.

This also has the advantage of not tying you to a particular IDE, since every Java IDE worth a drat has support for maven projects. I know it's just a personal hobby project and you're not likely to switch from Eclipse or have anybody else collaborate with you on it, but it's still useful to know how to do it, since your next project might not fit that same criteria.

Here's what my google search found: http://books.sonatype.com/mvnex-book/reference/multimodule-sect-simple-parent.html

HFX
Nov 29, 2004

fletcher posted:

The parent project with child modules is very common, I think it would be worth your time to utilize it. Maven can definitely be a little funky, but in almost every case somebody has done exactly what you will try to do with it before, and their blog post about how to do it is only a Google search away.

This also has the advantage of not tying you to a particular IDE, since every Java IDE worth a drat has support for maven projects. I know it's just a personal hobby project and you're not likely to switch from Eclipse or have anybody else collaborate with you on it, but it's still useful to know how to do it, since your next project might not fit that same criteria.

Here's what my google search found: http://books.sonatype.com/mvnex-book/reference/multimodule-sect-simple-parent.html

I wish that example had dependency management so more people would use dependency management. It is a great way to make sure everyone (in your child projects) are using the same versions of the same libraries. Thanks for this. Maybe I can show people this when they bug me about hwo to do something with Maven (which I mostly learned from Googling and trying.)

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Shinku ABOOKEN posted:

Is there a way to get maven-style dependency management (automatic downloading of dependencies) while keeping my projects as an eclipse project?

I know eclipse has maven support but the thing I want to make requires multiple projects with dependencies and I simply don't know maven that well (is it me or is the learning curve for maven a wall?).
It's a personal hobby project.

The biggest thing to know about multi module Maven configurations is that the parent POM is just like a template that your sub modules can extend. The parent POM itself extends from a default Super POM that already has some plugins configured for you by default.

You want to minimize the stuff you declare in the parent POM to things that are truly project wide i.e. Your projects license, it's source control and bug tracking urls, maybe an internal maven repository you use, your favorite logging library, maybe your db driver and finally versions for all the plugins you'll likely use in your submodules so that there aren't a mishmash of versions everywhere.

Then after that you just have to realize that your sub modules can declare dependencies on each other and when you build Maven will automatically create the right dependency graph (if you create a cycle then you have a bug and Maven will barf).

If you have more questions or just want to talk about Maven in general let me know over PM and we can Skype or something. I know how daunting Maven can be initially but the docs are pretty good, you just have to know what you're looking for.

Workaday Wizard
Oct 23, 2009

by Pragmatica
Thank you all.

I will try setting up maven on a dummy setup before applying it to my real setup.

Volguus
Mar 3, 2009

Shinku ABOOKEN posted:

Thank you all.

I will try setting up maven on a dummy setup before applying it to my real setup.

If you're really against maven, maybe Apache Ivy will be more to your taste. Ivy works with ant. http://ant.apache.org/ivy/ .
It's a bit more work to setup than maven, but more flexible.

Of course, other build systems (gradle, sbt) may be useful as well to study. Personal projects is the best way to learn about them.

TheresNoThyme
Nov 23, 2012

Edmond Dantes posted:

Yeah, my plan was basically see what I needed to do and then just google it, but that's how I usually do things and I wanted to get a headstart this time. I'll take a look at the official docs for now, but I'll bookmark that book to get later; I haven't used Spring in any positions so far and I'm realizing (a bit late) that it's a tool I actually should have.

Hopefully this is obvious to you but it really matters what version of spring you're planning to work with (IE a legacy project with 3.x, a new project with spring 4, etc...) and if you're planning to google for information you should be wary that a lot of old articles will tell you to do things that no longer make sense and in some cases, due to package refactoring or spring's hatred of deprecated code, just won't work. This is true even across some minor versions. Spring publishes project examples for a lot of their stuff which is usually a good place to start in my opinion.

Awesome framework though if you're willing to spend the time with it. I'm upgrading a bunch of java data services to use lombok + spring mvc + spring data + spring security and it's a little bit disturbing how good it looks.

n0manarmy
Mar 18, 2003

I'm building tests for a game that I'll probably never finish. I have a Player object that has 4 stats:

Tact, Speed, Passing, Toughness

The respective stats will determine the position of the player like so below:

Keeper - tact > speed > toughness > passing
Defender - toughness > speed > passing > tact
midfield - passing > speed > tact > toughness
striker - tact > speed > passing > toughness

The engine takes two teams and determines the lineup of 15 players out of 22, however I'm having a hard time determining how to best sort each of these objects to get the results. Each player is a Player object with an int for each stat.

I've played with the idea of doing a sorted Map and then base it from there. Or would it be best to build a class that handles a bunch of if statements to best determine the player position? Thoughts?

Edmond Dantes
Sep 12, 2007

Reactor: Online
Sensors: Online
Weapons: Online

ALL SYSTEMS NOMINAL

TheresNoThyme posted:

Hopefully this is obvious to you but it really matters what version of spring you're planning to work with (IE a legacy project with 3.x, a new project with spring 4, etc...) and if you're planning to google for information you should be wary that a lot of old articles will tell you to do things that no longer make sense and in some cases, due to package refactoring or spring's hatred of deprecated code, just won't work. This is true even across some minor versions. Spring publishes project examples for a lot of their stuff which is usually a good place to start in my opinion.

Awesome framework though if you're willing to spend the time with it. I'm upgrading a bunch of java data services to use lombok + spring mvc + spring data + spring security and it's a little bit disturbing how good it looks.

Yeah, noticed. :v:

I need to work on a little project as a job interview of sorts, basically develop a web service that gets some info from Weather Underground and then returns a JSON; that part, I have running.

My problem is that the next part involves deploying a simple html to tomcat (working with tomcat7), and have that webpage ping the webservice every minute or so and update itself. So far, so good, but I can't get tomcat to display the bloody thing. I'm a bit lost between the web.xml and the spring-servlet.xml, I either get the webservice running or the html; when I try to get both I either get a 404 on the html or a 500 error because I didn't declare a handler (which I did. I'm reading it right now!).

I'll get it eventually. I hope. :negative:

pigdog
Apr 23, 2004

by Smythe

n0manarmy posted:

I'm building tests for a game that I'll probably never finish. I have a Player object that has 4 stats:

Tact, Speed, Passing, Toughness

The respective stats will determine the position of the player like so below:

Keeper - tact > speed > toughness > passing
Defender - toughness > speed > passing > tact
midfield - passing > speed > tact > toughness
striker - tact > speed > passing > toughness

The engine takes two teams and determines the lineup of 15 players out of 22, however I'm having a hard time determining how to best sort each of these objects to get the results. Each player is a Player object with an int for each stat.

I've played with the idea of doing a sorted Map and then base it from there. Or would it be best to build a class that handles a bunch of if statements to best determine the player position? Thoughts?

If you mean comparing whether one striker is better than the other striker, then that could be a job for Comparable. You cannot really compare a keeper to a striker though, because there is no innate ordering between different types of objects. For picking a team you'd probably need to write a proper separate method.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

n0manarmy posted:

I'm building tests for a game that I'll probably never finish. I have a Player object that has 4 stats:

Tact, Speed, Passing, Toughness

The respective stats will determine the position of the player like so below:

Keeper - tact > speed > toughness > passing
Defender - toughness > speed > passing > tact
midfield - passing > speed > tact > toughness
striker - tact > speed > passing > toughness

The engine takes two teams and determines the lineup of 15 players out of 22, however I'm having a hard time determining how to best sort each of these objects to get the results. Each player is a Player object with an int for each stat.

I've played with the idea of doing a sorted Map and then base it from there. Or would it be best to build a class that handles a bunch of if statements to best determine the player position? Thoughts?

Is it meant to be extensible? And is every player a member of one of those groups?

I mean as it is, if you just want to determine which of those categories a player falls into you can just use a simple if block
Java code:
// check for keeper or striker
if (player.tact > player.speed) {
    if (player.toughness > player.passing) {
        return KEEPER;
    }
    else {
        return STRIKER;
    }
}
// must be a defender or midfield
else if (player.toughness > player.speed) {
    return DEFENDER;
}
else {
    // last statement works as a default position too
    return MIDFIELD;
}
But I kept that verbose because I feel like you're going to have to do a fair bit of extra logic, if only at the player generation stage (making sure you don't have equal values, ensuring every player's stats fit one of those recipes etc.)

You could put this position logic in the Player class itself though, since it's really about what the player is based on their attributes. Are you trying to select the best players for each position, like say the best two strikers out of the three you have? How involved is the comparison, do you have to weight the different attributes or can you just say 'highest tact is the winner'?

pigdog
Apr 23, 2004

by Smythe

baka kaba posted:

You could put this position logic in the Player class itself though, since it's really about what the player is based on their attributes. Are you trying to select the best players for each position, like say the best two strikers out of the three you have? How involved is the comparison, do you have to weight the different attributes or can you just say 'highest tact is the winner'?
I don't think that's the best idea; logically the Player object needn't necessarily know anything about drafting process. It deals with Player's fields yes, but not necessarily only them. Something like List<Player> lineup = selectionStrategy.draft(draftees); ought to work better in my opinion.

n0manarmy
Mar 18, 2003

pigdog posted:

I don't think that's the best idea; logically the Player object needn't necessarily know anything about drafting process. It deals with Player's fields yes, but not necessarily only them. Something like List<Player> lineup = selectionStrategy.draft(draftees); ought to work better in my opinion.

I'll put this in its own function. I ended up using a series of IF statements and assigning a value based on the result. Using their primary stat as the highest and decrementing from there: 8,4,2,1.

This is working so far, I'm going to take the results and iterate over the the results to see how a 1000 players turn out when randomly generated.

Side note:
I don't know how I could have done development without setting up tests first. If I had tried to hash this game out without building tests first and then implementing the code, it would have been a train wreck.

FieryBalrog
Apr 7, 2010
Grimey Drawer
I'm fairly new to Java so my knowledge is pretty limited. I'm working on a personal project where I'm trying out some of the techniques used in Guava for creating views/transformations of collections. I made a class called View to take an inputted collection as the backing iterable, and a transformation, and then present it as a read-only iterable. (not a collection, though I don't think it makes much of a difference for this question). Here is a quick example of using it...
code:
public class View<T> implements Iterable<T> {
    private final Iterable<T> view;

    public <F> View(final Iterable<? extends F> originalSet,
            final Function<? super F, ? extends T> transform) {
        this.view = Views.transformReadOnly(originalSet, transform);
    }
    //other constructors
}

public final class Views {
    private Views() { }

    public static <F, T> Iterable<T> transformReadOnly(final Iterable<F> fromIterable,
            final Function<? super F, ? extends T> function) {
        checkNotNull(fromIterable);
        checkNotNull(function);
      return new FluentIterable<T>() {
          @Override
          public Iterator<T> iterator() {
            return ViewIterators.transformReadOnly(fromIterable.iterator(), function);
          }
      };
    }
    //other static methods
}
code:
public class Node {
  public enum Change implements Function<Node, Coordinate> {
    TO_COORDINATE;
    @Override public Coordinate apply(Node node) {
      return new Coordinate(node);
    }
  }

  private HashSet<Node> neighborNodes = new HashSet<Node>();
  //various other members

  public View<Coordinate> viewNeighborCoordinates() {
    return new View<Coordinate>(neighborNodes, Change.TO_COORDINATE);
  }
}
now if some method wants to use viewNeighborCoordinates() of this node, and then later some other method also wants to viewNeighborCoordinates() of this node, it seems wasteful to always be returning new objects, right? I mean any number of things should be able to share reference to a view of the same backing iterable with the same transformation, since all they're doing is reading through it. Is there an established way of managing a shared pool of objects which can be "interned" like Strings are? Is it just having to make some sort of ViewFactory that stores a running list of views in use, and everytime someone wants a view, it checks to see if it already has that view and hands it out? (is that even more efficient)?

Also, the same applies to iterating through the View, I guess, since the transformation calls the constructor of the target type via the function application when doing the actual iteration (so each time it iterates it will create a bunch of new objects for viewing purposes). Is it worth managing that somehow?

FieryBalrog fucked around with this message at 23:58 on Aug 11, 2014

Safe and Secure!
Jun 14, 2008

OFFICIAL SA THREAD RUINER
SPRING 2013
I want to know how the JVM works, especially garbage collection. I've been going through the JVM spec, but it looks like the way garbage collection works depends on the specific implementation. So is there a single implementation I can take to be mostly canonical? Like, if I learn how Oracle's implementation works, and then maybe how the JVM used by Android works, then that's enough? What would I even want to Google here to find specific information on both of those implementations work?

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

Safe and Secure! posted:

I want to know how the JVM works, especially garbage collection. I've been going through the JVM spec, but it looks like the way garbage collection works depends on the specific implementation. So is there a single implementation I can take to be mostly canonical? Like, if I learn how Oracle's implementation works, and then maybe how the JVM used by Android works, then that's enough? What would I even want to Google here to find specific information on both of those implementations work?
Depending on how much language runtime knowledge you have, you might want to work up to OpenJDK-specific stuff by starting with the JRockit book, which does a great job of covering the fundamentals of stuff like JIT compilers, generational GCs, etc.

Sadly, there used to be a lot of great Sun blogs about OpenJDK internals but the Oracle rebranding means most URLs are dead ends. :( After the above, I'd actually recommend Charlie Hunt's Java performance book, as it's pretty tightly coupled to OpenJDK and gives a pretty solid informal description of the major GCs (the Parallel collector, CMS, and G1).

After that, frankly, the source is pretty readable and that's where I'd point you to next (modulo C2, the server compiler, which is straight-up :pcgaming:)

edit: forgot to mention that if you're interested in a denser, GC-specific read that isn't tied to any particular runtime, you can't go better than The Garbage Collection Handbook.

Was there anything in particular you were interested in? Up until recently I was paid to hack on OpenJDK so I can probably point you in the right direction if you can't find what you're after.

Dijkstracula fucked around with this message at 05:05 on Aug 11, 2014

Sedro
Dec 31, 2008

FieryBalrog posted:

I'm fairly new to Java so my knowledge is pretty limited. I'm working on a personal project where I'm trying out some of the techniques used in Guava for creating views/transformations of collections. I made a class called View to take an inputted collection as the backing iterable, and a transformation, and then present it as a read-only iterable. (not a collection, though I don't think it makes much of a difference for this question). Here is a quick example of using it...
Did you just implement "map", ie. this?
Java code:
public class Node {
  private HashSet<Node> neighborNodes = new HashSet<Node>();
  //various other members

  public View<Coordinate> viewNeighborCoordinates() {
    return neighborNodes.map(Coordinate::new);
  }
}

FieryBalrog
Apr 7, 2010
Grimey Drawer

Sedro posted:

Did you just implement "map", ie. this?
Java code:
public class Node {
  private HashSet<Node> neighborNodes = new HashSet<Node>();
  //various other members

  public View<Coordinate> viewNeighborCoordinates() {
    return neighborNodes.map(Coordinate::new);
  }
}

Um, I'm not sure what you mean. There isn't any method named "map" as far as I can tell for HashSet...? I've never seen that syntax before either, is this a java 8 thing? (I'm a SQL guy and i don't know anything about programming except the last 2 months of learning Java from scratch, so maybe I'm missing something...).

The basic idea is the same as the one in Guava's Iterables & Iterators libraries, except it's read-only (remove() throws unsupported operation exception from the Iterator) and I added other ways of transforming a backing iterable.

code:
    public <X, F> View(X agent, final Iterable<? extends F> originalSet,
            final BinaryFunction<? super X, ? super F, ? extends T> catalyzer) {
        this.view = Views.catalyzeReadOnly(agent, originalSet, catalyzer);
    }

    public View(final Iterable<? extends T> originalSet) {
        this.view = Views.flattenReadOnly(originalSet);
    }

FieryBalrog fucked around with this message at 00:06 on Aug 12, 2014

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

I mean there's nothing stopping you from keeping a backing store of "interned" objects, but I can't imagine the performance gains would outweigh just allocating the objects as need be, and it'll certainly be more costly w.r.t. your program's memory usage. Also, if your intent is that the elements in the view are immediately transformed again, then those allocated objects won't be long-lived - allocation is cheap but object tenuring is expensive, so I can't see trying to have a behind-the-scenes cache yielding you any benefit.

Of course, benchmark, benchmark, benchmark and prove me wrong :v:

IMlemon
Dec 29, 2008
Here's a simplified use case I'm implementing right now:

1. Http request is submitted by a user.
2. Login to a remote machine via ssh, submit a job which takes a decent amount of time. The result of this is a bunch of files that get uploaded to an ftp server.
3. Retrieve files from ftp server
4. Parse and transform the data before uploading it to the database.

I figured I'll use this chance to learn apache camel, because it seems it was made to solve problems like this. It's been going well, however I've hit a little bit of a problem in #3. I created a camel "route" that will watch a directory in the ftp server and grab everything. However, I'm worried that this is inefficient, since this job won't be triggered very often.

XML code:
<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
        <route id="start">
            <from uri="direct:start"/>
            <setBody>
                <constant>my-ssh-command&#10;</constant>
            </setBody>
            <to uri="ssh://whatever"/>

            <log message="${body}"/>
        </route>

        <route id="ftp-file-consumer">
            <from uri="ftp:whatever" />
            <to uri="bean:my_data_handler" />
        </route>
    </camelContext>
What I would like to do, is to start-up the "ftp-file-consumer" route after ssh command is invoked, let it poll the ftp server until files are found or it timeouts, whichever comes first. Unfortunately I'm having some trouble figuring out how to do this and I need this done yesterday. Am I being silly worrying about the potential ftp server overhead and should I just go with what I have now?

Volguus
Mar 3, 2009

IMlemon posted:

Here's a simplified use case I'm implementing right now:

1. Http request is submitted by a user.
2. Login to a remote machine via ssh, submit a job which takes a decent amount of time. The result of this is a bunch of files that get uploaded to an ftp server.
3. Retrieve files from ftp server
4. Parse and transform the data before uploading it to the database.

I figured I'll use this chance to learn apache camel, because it seems it was made to solve problems like this. It's been going well, however I've hit a little bit of a problem in #3. I created a camel "route" that will watch a directory in the ftp server and grab everything. However, I'm worried that this is inefficient, since this job won't be triggered very often.

XML code:
<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
        <route id="start">
            <from uri="direct:start"/>
            <setBody>
                <constant>my-ssh-command&#10;</constant>
            </setBody>
            <to uri="ssh://whatever"/>

            <log message="${body}"/>
        </route>

        <route id="ftp-file-consumer">
            <from uri="ftp:whatever" />
            <to uri="bean:my_data_handler" />
        </route>
    </camelContext>
What I would like to do, is to start-up the "ftp-file-consumer" route after ssh command is invoked, let it poll the ftp server until files are found or it timeouts, whichever comes first. Unfortunately I'm having some trouble figuring out how to do this and I need this done yesterday. Am I being silly worrying about the potential ftp server overhead and should I just go with what I have now?

Since this entire process is :wtf: ... i wouldn't worry about anything. If anyone would care in the slightest about performance or reliability a proper job results retrieval mechanism would be implemented.

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.
You can create dependencies between routes in Camel, no? So after the SSH is done, you'd post into some in-memory (or persistent) queue that task #3 then picks up and uses to trigger the FTP scan.

PiCroft
Jun 11, 2010

I'm sorry, did I break all your shit? I didn't know it was yours

e: nevermind, this will be better suited for the Android thread

Safe and Secure!
Jun 14, 2008

OFFICIAL SA THREAD RUINER
SPRING 2013

Dijkstracula posted:

Depending on how much language runtime knowledge you have, you might want to work up to OpenJDK-specific stuff by starting with the JRockit book, which does a great job of covering the fundamentals of stuff like JIT compilers, generational GCs, etc.

Sadly, there used to be a lot of great Sun blogs about OpenJDK internals but the Oracle rebranding means most URLs are dead ends. :( After the above, I'd actually recommend Charlie Hunt's Java performance book, as it's pretty tightly coupled to OpenJDK and gives a pretty solid informal description of the major GCs (the Parallel collector, CMS, and G1).

After that, frankly, the source is pretty readable and that's where I'd point you to next (modulo C2, the server compiler, which is straight-up :pcgaming:)

edit: forgot to mention that if you're interested in a denser, GC-specific read that isn't tied to any particular runtime, you can't go better than The Garbage Collection Handbook.

Was there anything in particular you were interested in? Up until recently I was paid to hack on OpenJDK so I can probably point you in the right direction if you can't find what you're after.

Thank you for this!

I don't have anything in particular that I want to know, I just feel that I don't understand my tools as much as I'd like to.

Workaday Wizard
Oct 23, 2009

by Pragmatica
I am considering using Groovy for a small project but I haven't used it before. What are the drawbacks of using Groovy other than tool support/IDE issues?

Do Groovy classes, objects, or methods have additional overhead compared to Java?

I am curious about the differences even if they won't matter to my project.

Volguus
Mar 3, 2009

Shinku ABOOKEN posted:

I am considering using Groovy for a small project but I haven't used it before. What are the drawbacks of using Groovy other than tool support/IDE issues?

Do Groovy classes, objects, or methods have additional overhead compared to Java?

I am curious about the differences even if they won't matter to my project.

I have used Grails few years back for some of my projects. The tool support/IDE was pretty great (using springsource grails plugin for Eclipse). Netbeans has Groovy support as well as far as I remember. As opposed to Scala, Groovy is much easier to learn.
The drawbacks of a Grails application was that it consumed quite a bit of more memory (and it was a fair bit slower) than just plain Java. The pros was that it was drat easy and fast to whip up a web application with it. Want it yesterday? Use Grails.

Saw a benchmark some time ago between Java, Groovy and Scala using a raytracer algorithm. Groovy was about 20 times slower than Java, Scala was about 1.5 times slower. Now, in Java 1.7 I believe they introduced a new opcode (invokedynamic) that people were saying that it will improve the performance of the languages built on top of the JVM. I haven't used it since 1.7 came out and I don't know enough about it to be able to say either way.

Volguus fucked around with this message at 14:29 on Aug 21, 2014

emanresu tnuocca
Sep 2, 2011

by Athanatos
Hey guys, I've got yet another stupid question.

I'm screwing around with Swing a bit, I was trying to create a very simple app that draws circles of different sizes, assigns them a random velocity and direction and just lets them bounce a bit.

http://codepaste.net/ruvug9

Generally it works, but there's some weird behavior when the balls collide with the JPanel's border, my code attempts to detect the collision and then just adds half a pi to the direction, I guess my math is wrong cause the balls don't always bounce back correctly, they often change directions several times before returning at roughly 180 degrees, where I'd expect them to always just add 90 degrees to their course... which admitedly doesn't make much sense.

Here's the relevant snippet
code:
			for (Circle fromArray : listOfCircles) {
				g.setColor(fromArray.circColor);
				if(fromArray.x > getWidth() - fromArray.radius || fromArray.y > getHeight() -fromArray.radius  || fromArray.x < 0 || fromArray.y < 0){
					fromArray.velDirecction = (fromArray.velDirecction - 0.5 * Math.PI);
					
				}
		
				g.fillOval(fromArray.x += Math.pow(fromArray.velocity * Math.sin(fromArray.velDirecction), 1), fromArray.y += Math.pow(fromArray.velocity * Math.cos(fromArray.velDirecction), 1), fromArray.radius,
						fromArray.radius);
			}
		
So, is it because I should check with an if statement whether the direction is positive or negative (I guess, greater than Pi or smaller than Pi?) and add or deduct half a pi accordingly? It's kind of stupid I know, I'd just like to know what I've hosed up.

Edit: oh and ignore that Math.Pow() thing, I realized that the sin and cos should be squared for the Pythagorean formula to maintain the amplitude of the vector but I messed it up a bit. wrong

emanresu tnuocca fucked around with this message at 13:15 on Aug 25, 2014

Adbot
ADBOT LOVES YOU

pigdog
Apr 23, 2004

by Smythe
I'm sure if you added some local variables with descriptive names to spell parts of the calculations out as if you'd describe it to a 5-year-old, you'd see what the problem is.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply