From: <pa...@us...> - 2010-06-23 12:41:43
|
Revision: 20973 http://gallery.svn.sourceforge.net/gallery/?rev=20973&view=rev Author: paour Date: 2010-06-23 12:41:35 +0000 (Wed, 23 Jun 2010) Log Message: ----------- Working login, upload. Simplified, generified, broke of a lot of stuff. Still working on getting the list of albums... Modified Paths: -------------- trunk/gallery_remote/com/gallery/GalleryRemote/AlbumInspector.java trunk/gallery_remote/com/gallery/GalleryRemote/GalleryComm.java trunk/gallery_remote/com/gallery/GalleryRemote/GalleryComm3.java trunk/gallery_remote/com/gallery/GalleryRemote/GalleryCommTest.java trunk/gallery_remote/com/gallery/GalleryRemote/GalleryRemoteMainFrame.java trunk/gallery_remote/com/gallery/GalleryRemote/Log.java trunk/gallery_remote/com/gallery/GalleryRemote/MainFrame.java trunk/gallery_remote/com/gallery/GalleryRemote/PictureInspector.java trunk/gallery_remote/com/gallery/GalleryRemote/UploadProgress.java trunk/gallery_remote/com/gallery/GalleryRemote/model/Album.java trunk/gallery_remote/com/gallery/GalleryRemote/model/Gallery.java trunk/gallery_remote/com/gallery/GalleryRemote/model/GalleryItem.java trunk/gallery_remote/com/gallery/GalleryRemote/model/Picture.java trunk/gallery_remote/com/gallery/GalleryRemote/resources/GRResources.properties trunk/gallery_remote/com/gallery/GalleryRemote/resources/GRResources_ca.properties trunk/gallery_remote/com/gallery/GalleryRemote/util/ImageUtils.java trunk/gallery_remote/com/gallery/GalleryRemote/util/MacOSXAdapter.java trunk/gallery_remote/com/gallery/GalleryRemote/util/NaturalOrderComparator.java trunk/gallery_remote/com/gallery/GalleryRemote/util/OsShutdown.java Removed Paths: ------------- trunk/gallery_remote/HTTPClient/ trunk/gallery_remote/com/gallery/GalleryRemote/AuthorizePopup.java trunk/gallery_remote/sbconf/ Modified: trunk/gallery_remote/com/gallery/GalleryRemote/AlbumInspector.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/AlbumInspector.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/AlbumInspector.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -389,8 +389,8 @@ ignoreNextComboBoxChanged = true; jBeginning.setSelected(album.getAddToBeginning()); - jFetch.setEnabled(album.getGallery().getComm(mf.jStatusBar).hasCapability(mf.jStatusBar, GalleryCommCapabilities.CAPA_FETCH_ALBUM_IMAGES)); - jMove.setEnabled(album.getGallery().getComm(mf.jStatusBar).hasCapability(mf.jStatusBar, GalleryCommCapabilities.CAPA_MOVE_ALBUM)); + jFetch.setEnabled(album.getGallery().getComm().hasCapability(GalleryCommCapabilities.CAPA_FETCH_ALBUM_IMAGES)); + jMove.setEnabled(album.getGallery().getComm().hasCapability(GalleryCommCapabilities.CAPA_MOVE_ALBUM)); jSlideshow.setEnabled(album.getSize() > 0); } Deleted: trunk/gallery_remote/com/gallery/GalleryRemote/AuthorizePopup.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/AuthorizePopup.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/AuthorizePopup.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -1,248 +0,0 @@ -/* - * Donated code for Gallery Project - * Copyright abandonded by Stanley Knutson (St...@st...) - */ -package com.gallery.GalleryRemote; - -import HTTPClient.NVPair; -import com.gallery.GalleryRemote.util.GRI18n; -import com.gallery.GalleryRemote.util.DialogUtil; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -/** - * Do the authorization popup in a swing-compatible way. Built from the code in - * HTTPClient.DefaultAuthHandler - * - * @author Stanley Knutson - * @created Januray 3, 2003 - */ - -public class AuthorizePopup implements HTTPClient.AuthorizationPrompter { - private static BasicAuthBox inp = null; - public static final String MODULE = "AuthorizePopup"; - - public static String hackUsername = null; - public static String hackPassword = null; - - - /** - * Engage this class to be the authorization popup - */ - public static void enable() { - HTTPClient.DefaultAuthHandler.setAuthorizationPrompter - (new AuthorizePopup()); - } - - - /** - * the method called by DefaultAuthHandler. - * - * @param challenge Description of Parameter - * @param forProxy Description of Parameter - * @return the username/password pair - */ - public NVPair getUsernamePassword(HTTPClient.AuthorizationInfo challenge, - boolean forProxy) { - - // The HTTPClient library doesn't correctly accept setting auth params - // ahead of time (because it can't accept a realm of * - // so we have to do it this hackish way... - if (challenge.getScheme().equalsIgnoreCase("Basic") && hackUsername != null) { - return new NVPair(hackUsername, hackPassword); - } - - String line1; - String line2; - String line3; - - if (challenge.getScheme().equalsIgnoreCase("SOCKS5")) { - line1 = GRI18n.getString(MODULE, "enterUsrPwd"); - line2 = challenge.getHost(); - line3 = GRI18n.getString(MODULE, "authMthd"); - } else { - line1 = GRI18n.getString(MODULE, "enterUsrPwdRealm", new Object[] { challenge.getRealm() }); - line2 = GRI18n.getString(MODULE, "onHost", new Object[] { challenge.getHost() + ":" + - challenge.getPort()}); - line3 = GRI18n.getString(MODULE, "authScheme", new Object[] { challenge.getScheme() }); - } - - synchronized (getClass()) { - if (inp == null) { - inp = new BasicAuthBox(GalleryRemote._().getMainFrame()); - } - } - - return inp.getInput(line1, line2, line3, challenge.getScheme()); - } - - - /** - * This class implements a simple popup that request username and password - * used for the "basic" and "digest" authentication schemes. - * - * @author Ronald Tschalar - * @version 0.3-3 06/05/2001 - * @created February 2, 2003 - */ - private static class BasicAuthBox extends JDialog implements ActionListener { - private final static String title = GRI18n.getString(MODULE, "authreq"); - private JLabel line1, line2, line3; - private JTextField user, pass; - private int done; - private final static int OK = 1, CANCEL = 0; - - - /** - * Constructs the popup with two lines of text above the input fields - * - * @param container Description of Parameter - */ - BasicAuthBox(Frame container) { - super(container, title, true); - - addNotify(); - setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - - getContentPane().setLayout(new BorderLayout()); - - JPanel p = new JPanel(new GridLayout(3, 1)); - p.add(line1 = new JLabel()); - p.add(line2 = new JLabel()); - p.add(line3 = new JLabel()); - getContentPane().add("North", p); - - p = new JPanel(new GridLayout(2, 1)); - p.add(new JLabel(GRI18n.getString(MODULE, "username"))); - p.add(new JLabel(GRI18n.getString(MODULE, "passwd"))); - getContentPane().add("West", p); - p = new JPanel(new GridLayout(2, 1)); - p.add(user = new JTextField(30)); - p.add(pass = new JPasswordField(30)); - pass.addActionListener(this); - getContentPane().add("East", p); - - GridBagLayout gb = new GridBagLayout(); - p = new JPanel(gb); - GridBagConstraints constr = new GridBagConstraints(); - JPanel pp = new JPanel(); - p.add(pp); - constr.gridwidth = GridBagConstraints.REMAINDER; - gb.setConstraints(pp, constr); - constr.gridwidth = 1; - constr.weightx = 1.0; - - JButton b; - p.add(b = new JButton(GRI18n.getString("Common", "OK"))); - b.addActionListener(this); - b.setActionCommand("ok"); - getRootPane().setDefaultButton(b); - constr.weightx = 1.0; - gb.setConstraints(b, constr); - - p.add(b = new JButton(GRI18n.getString(MODULE, "clear"))); - b.addActionListener(this); - b.setActionCommand("clear"); - constr.weightx = 2.0; - gb.setConstraints(b, constr); - - p.add(b = new JButton(GRI18n.getString("Common", "Cancel"))); - b.addActionListener(this); - b.setActionCommand("cancel"); - constr.weightx = 1.0; - gb.setConstraints(b, constr); - - getContentPane().add("South", p); - - pack(); - } - - - /** - * the method called by SimpleAuthPopup. - * - * @param l1 Description of Parameter - * @param l2 Description of Parameter - * @param l3 Description of Parameter - * @param scheme Description of Parameter - * @return the username/password pair - */ - NVPair getInput(String l1, String l2, String l3, - String scheme) { - line1.setText(l1); - line2.setText(l2); - line3.setText(l3); - - line1.invalidate(); - line2.invalidate(); - line3.invalidate(); - - setResizable(true); - pack(); - setResizable(false); - // put popup at upper right of the parent frame (assuming we have one) - - DialogUtil.center(this, getOwner()); - - boolean user_focus = true; - if (scheme.equalsIgnoreCase("NTLM")) { - // prefill the user field with the username - try { - user.setText(System.getProperty("user.name", "")); - user_focus = false; - } catch (SecurityException se) { - } - } - - // This call to request focus probably does not do anything, but leave it in. - if (user_focus) { - user.requestFocus(); - } else { - pass.requestFocus(); - } - - // This is a modal dialog: the "show" method does not return - // until "hide" is called by close, cancel or ok action - show(); - - NVPair result = new NVPair(user.getText(), pass.getText()); - user.setText(""); - pass.setText(""); - - if (done == CANCEL) { - return null; - } else { - return result; - } - } - - /** - * Invoked when an action occurs. - */ - public void actionPerformed(ActionEvent e) { - if (e.getSource() == pass || "ok".equals(e.getActionCommand())) { - done = OK; - hide(); - } else if ("clear".equals(e.getActionCommand())) { - user.setText(""); - pass.setText(""); - user.requestFocus(); - } else if ("cancel".equals(e.getActionCommand())) { - done = CANCEL; - hide(); - } else if ("close".equals(e.getActionCommand())) { - } - } - - /*private class Close extends WindowAdapter { - public void windowClosing(WindowEvent we) { - new Cancel().actionPerformed(null); - } - }*/ - } -} Modified: trunk/gallery_remote/com/gallery/GalleryRemote/GalleryComm.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/GalleryComm.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/GalleryComm.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -61,55 +61,16 @@ private static final String MODULE = "GalComm"; int[] capabilities = null; - private static int lastRespCode = 0; + //private static int lastRespCode = 0; /** Flag to hold logged in status. Only need to log in once. */ - protected boolean isLoggedIn = false; - protected boolean triedLogin = false; + //protected boolean isLoggedIn = false; + //protected boolean triedLogin = false; DefaultHttpClient httpclient; Gallery g; StatusUpdate su; - /* ------------------------------------------------------------------------- - * STATIC INITIALIZATON - */ - - static { - /* Enable customized AuthorizePopup */ - AuthorizePopup.enable(); - - - // http://cvs.sourceforge.net/viewcvs.py/jameleon/jameleon/src/java/net/sf/jameleon/util/JsseSettings.java?rev=1.4&view=markup - // http://tp.its.yale.edu/pipermail/cas/2004-March/000348.html - // Create a trust manager that does not validate certificate chains - TrustManager[] trustAllCerts = new TrustManager[]{ - new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - Log.log(Log.LEVEL_INFO, MODULE, "TrustManager.getAcceptedIssuers"); - return new java.security.cert.X509Certificate[0]; - } - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - Log.log(Log.LEVEL_INFO, MODULE, "TrustManager.checkClientTrusted"); - } - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - Log.log(Log.LEVEL_INFO, MODULE, "TrustManager.checkServerTrusted"); - } - } - }; - - // Install the all-trusting trust manager - try { - SSLContext sc = SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); - } catch (Exception e) { - Log.logException(Log.LEVEL_ERROR, MODULE, e); - } - } - protected GalleryComm(Gallery g, StatusUpdate su) { if (g == null) { throw new IllegalArgumentException("Must supply a non-null gallery."); @@ -120,6 +81,7 @@ SingleClientConnManager cm = null; + // Set all-trusting SSL manager, if necessary if (g.getUrl().getProtocol().equals("https")) { try { SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); @@ -133,10 +95,12 @@ httpclient = new DefaultHttpClient(cm); + // Use default proxy (as defined by the JVM) ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpclient.setRoutePlanner(routePlanner); + // use GR User-Agent httpclient.removeRequestInterceptorByClass(RequestUserAgent.class); final String ua = g.getUserAgent(); httpclient.addRequestInterceptor(new HttpRequestInterceptor() { @@ -144,7 +108,10 @@ request.setHeader(HTTP.USER_AGENT, ua); } }); + } + public boolean checkAuth() { + throw new RuntimeException("This method is not available on this protocol"); } /** @@ -207,56 +174,36 @@ throw new RuntimeException("This method is not available on this protocol"); } - public void logOut() { - Log.log(Log.LEVEL_INFO, MODULE, "Logging out and clearing cookies"); - isLoggedIn = false; - httpclient.getCookieStore().clear(); - } +// public void logOut() { +// Log.log(Log.LEVEL_INFO, MODULE, "Logging out and clearing cookies"); +// //isLoggedIn = false; +// httpclient.getCookieStore().clear(); +// } - public boolean isLoggedIn() { - return isLoggedIn; - } +// public boolean isLoggedIn() { +// return isLoggedIn; +// } - public boolean hasCapability(StatusUpdate su, int capability) { - if (! isLoggedIn() && !triedLogin) { + public boolean hasCapability(int capability) { + /*if (! isLoggedIn() && !triedLogin) { login(su); } - return java.util.Arrays.binarySearch(capabilities, capability) >= 0; + return java.util.Arrays.binarySearch(capabilities, capability) >= 0;*/ + return true; } /** * Return true if the last communication attempt failed with authorization error */ - public static boolean wasAuthFailure() { - return lastRespCode == 401; - } +// public static boolean wasAuthFailure() { +// return lastRespCode == 401; +// } public static GalleryComm getCommInstance(StatusUpdate su, Gallery g) { return new GalleryComm3(g, su); } - public static void addUserInfo(URL url) { - String userInfo = url.getUserInfo(); - if (userInfo != null) { - StringTokenizer st = new StringTokenizer(userInfo, ":"); - if (st.countTokens() == 2) { - String username = st.nextToken(); - String password = st.nextToken(); - - Log.log(Log.LEVEL_TRACE, MODULE, "Added basic auth params: " + username + " - " + password); - - AuthorizePopup.hackUsername = username; - AuthorizePopup.hackPassword = password; - - return; - } - } - - AuthorizePopup.hackUsername = null; - AuthorizePopup.hackPassword = null; - } - /*private static boolean tryComm(StatusUpdate su, HttpClient mConnection, String urlPath, StringBuffer content) { try { HTTPResponse rsp; @@ -269,7 +216,7 @@ // handle 30x redirects // (and authorization failure) - int rspCode = rsp.getStatusCode(); // try actual communcation + int rspCode = rsp.getStatusCode(); // try actual communication lastRespCode = rspCode; if (rspCode >= 300 && rspCode < 400) { // retry, the library will have fixed the URL Modified: trunk/gallery_remote/com/gallery/GalleryRemote/GalleryComm3.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/GalleryComm3.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/GalleryComm3.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -2,6 +2,7 @@ import com.gallery.GalleryRemote.model.Gallery; import com.gallery.GalleryRemote.model.Album; +import com.gallery.GalleryRemote.model.Picture; import com.gallery.GalleryRemote.util.GRI18n; import com.gallery.GalleryRemote.util.NaturalOrderComparator; import com.gallery.GalleryRemote.util.UrlMessageDialog; @@ -10,13 +11,29 @@ import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.BufferedHttpEntity; +import org.apache.http.entity.FileEntity; +import org.apache.http.entity.mime.FormBodyPart; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntity; +import org.apache.http.entity.mime.content.ContentBody; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.entity.mime.content.StringBody; import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; import org.json.simple.parser.ContentHandler; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; import java.io.*; import java.net.URL; +import java.nio.charset.Charset; +import java.nio.charset.spi.CharsetProvider; import java.util.*; public class GalleryComm3 extends GalleryComm { @@ -32,6 +49,22 @@ doTask(new AlbumListTask(su), async); } + public void uploadFiles(StatusUpdate su, boolean async) { + UploadTask uploadTask = new UploadTask(su); + doTask(uploadTask, async); + } + + public boolean checkAuth() { + try { + sendRequest(g.getUrlString() + api + "item/1", "get", (HttpEntity) null); + } catch (IOException e) { + Log.logException(Log.LEVEL_CRITICAL, MODULE, e); + return false; + } + + return true; + } + /* ------------------------------------------------------------------------- * UTILITY METHODS */ @@ -58,6 +91,97 @@ Log.log(Log.LEVEL_TRACE, MODULE, message); } + public BufferedReader sendRequest(String url, String verb, List<NameValuePair> formparams) throws IOException { + if (formparams == null) { + return sendRequest(url, verb, (HttpEntity) null); + } + + UrlEncodedFormEntity entity = null; + try { + entity = new UrlEncodedFormEntity(formparams, "UTF-8"); + return sendRequest(url, verb, entity); + } catch (UnsupportedEncodingException e) { + Log.logException(Log.LEVEL_CRITICAL, MODULE, e); + return null; + } + } + + public BufferedReader sendRequest(String url, String verb, HttpEntity entity) throws IOException { + HttpPost post = new HttpPost(url); + + Log.log(Log.LEVEL_TRACE, "Sending request: " + post.getRequestLine().toString()); + + if (entity != null) { + post.setEntity(entity); + + if (!(entity instanceof MultipartEntity)) { + Log.log(Log.LEVEL_TRACE, "Parameters: " + EntityUtils.toString(entity)); + } + } + + post.setHeader("X-Gallery-Request-Method", verb); + + boolean usedCachedKey = true; + if (url.endsWith(api)) { + // we're trying to get the key already + usedCachedKey = false; + } else { + String key = g.getKey(); + if (key == null || key.length() == 0) { + // no cached key, perform login + key = getKey(); + usedCachedKey = false; + } + post.setHeader("X-Gallery-Request-Key", key); + } + + HttpResponse response = httpclient.execute(post); + + int status = response.getStatusLine().getStatusCode(); + Log.log(Log.LEVEL_TRACE, "HTTP status: " + status); + + HttpEntity responseEntity = response.getEntity(); + responseEntity = new BufferedHttpEntity(responseEntity); + Log.log(Log.LEVEL_TRACE, "HTTP response: " + EntityUtils.toString(responseEntity)); + + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(responseEntity.getContent())); + switch (status) { + case 200: + // everything cool + return bufferedReader; + + case 403: + // security exception + responseEntity.consumeContent(); + if (usedCachedKey) { + // assume they key was stale, reset it + g.setKey(null); + + return sendRequest(url, verb, entity); + } else { + g.logOut(); + throw new GR2Exception("Security exception"); + } + + default: + throw new GR2Exception("Unknown return HTTP status: " + status); + } + } + + public String getKey() throws IOException { + List<NameValuePair> formparams = new ArrayList<NameValuePair>(); + formparams.add(new BasicNameValuePair("user", g.getUsername())); + formparams.add(new BasicNameValuePair("password", g.getPassword())); + + BufferedReader r = sendRequest(g.getUrlString() + api, "post", formparams); + + String key = (String) JSONValue.parse(r); + + g.setKey(key); + + return key; + } + /* ------------------------------------------------------------------------- * INNER CLASSES */ @@ -90,119 +214,99 @@ } private void list() throws IOException { - HttpPost post = new HttpPost(g.getUrlString() + api + "item/1"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("type", "album")); formparams.add(new BasicNameValuePair("scope", "all")); - UrlEncodedFormEntity entity = null; - try { - entity = new UrlEncodedFormEntity(formparams, "UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - post.setEntity(entity); - post.setHeader("X-Gallery-Request-Method", "get"); - post.setHeader("X-Gallery-Request-Key", g.getKey()); - HttpResponse response = httpclient.execute(post); + BufferedReader entityReader = sendRequest(g.getUrlString() + api + "item/1", "get", formparams); - if (response.getStatusLine().getStatusCode() == 200) { - HttpEntity rentity = response.getEntity(); + JSONParser parser = new JSONParser(); + ListContentHandler lch = new ListContentHandler(); - JSONParser parser = new JSONParser(); - ListContentHandler lch = new ListContentHandler(); + HashMap<String,String> url2parentUrl = new HashMap<String,String>(); + HashMap<String,Album> url2album = new HashMap<String,Album>(); + ArrayList<Album> albums = new ArrayList<Album>(); - HashMap<String,String> url2parentUrl = new HashMap<String,String>(); - HashMap<String,Album> url2album = new HashMap<String,Album>(); - ArrayList<Album> albums = new ArrayList<Album>(); + try { + Album rootAlbum = g.createRootAlbum(); + rootAlbum.setUrl(g.getUrlString() + api + "item/1"); + rootAlbum.setSuppressEvents(true); + lch.setAlbum(rootAlbum); + parser.parse(entityReader, lch, true); + rootAlbum.setSuppressEvents(false); + // map album names to albums + url2album.put(rootAlbum.getUrl(), rootAlbum); + url2parentUrl.put(rootAlbum.getUrl(), lch.getParentUrl()); - try { - BufferedReader entityReader = new BufferedReader(new InputStreamReader(rentity.getContent())); - - Album rootAlbum = g.createRootAlbum(); - rootAlbum.setUrl(post.getURI().toString()); - rootAlbum.setSuppressEvents(true); - lch.setAlbum(rootAlbum); + while (!lch.isEnd()) { + Album a = g.newAlbum(); + a.setSuppressEvents(true); + lch.setAlbum(a); parser.parse(entityReader, lch, true); - rootAlbum.setSuppressEvents(false); - // map album names to albums - url2album.put(rootAlbum.getUrl(), rootAlbum); - url2parentUrl.put(rootAlbum.getUrl(), lch.getParentUrl()); + a.setSuppressEvents(false); - while (!lch.isEnd()) { - Album a = g.newAlbum(); - a.setSuppressEvents(true); - lch.setAlbum(a); - parser.parse(entityReader, lch, true); - a.setSuppressEvents(false); + albums.add(a); - albums.add(a); - - // map album names to albums - url2album.put(a.getUrl(), a); - url2parentUrl.put(a.getUrl(), lch.getParentUrl()); - } - } catch (ParseException e) { - Log.logException(Log.LEVEL_CRITICAL, MODULE, e); + // map album names to albums + url2album.put(a.getUrl(), a); + url2parentUrl.put(a.getUrl(), lch.getParentUrl()); } + } catch (ParseException e) { + Log.logException(Log.LEVEL_CRITICAL, MODULE, e); + } - Log.log(Log.LEVEL_TRACE, MODULE, "Created " + albums.size() + " albums"); + Log.log(Log.LEVEL_TRACE, MODULE, "Created " + albums.size() + " albums"); - // link albums to parents - for (Object o : url2parentUrl.keySet()) { - String name = (String) o; - String parentName = url2parentUrl.get(name); - Album child = url2album.get(name); - Album parent = url2album.get(parentName); + // link albums to parents + for (Object o : url2parentUrl.keySet()) { + String name = (String) o; + String parentName = url2parentUrl.get(name); + Album child = url2album.get(name); + Album parent = url2album.get(parentName); - if (child != null && parent != null) { - parent.add(child); - } + if (child != null && parent != null) { + parent.add(child); } + } - Log.log(Log.LEVEL_TRACE, MODULE, "Linked " + url2parentUrl.size() + " albums to their parents"); + Log.log(Log.LEVEL_TRACE, MODULE, "Linked " + url2parentUrl.size() + " albums to their parents"); - // reorder - Collections.sort(albums, new NaturalOrderComparator()); - Collections.reverse(albums); - ArrayList<Album> orderedAlbums = new ArrayList<Album>(); - int depth = 0; - while (!albums.isEmpty()) { - Iterator<Album> it = albums.iterator(); - while (it.hasNext()) { - Album a = it.next(); + // reorder + Collections.sort(albums, new NaturalOrderComparator<Album>()); + Collections.reverse(albums); + ArrayList<Album> orderedAlbums = new ArrayList<Album>(); + int depth = 0; + while (!albums.isEmpty()) { + Iterator<Album> it = albums.iterator(); + while (it.hasNext()) { + Album a = it.next(); - try { - if (a.getAlbumDepth() == depth) { - it.remove(); - a.sortSubAlbums(); + try { + if (a.getAlbumDepth() == depth) { + it.remove(); + a.sortSubAlbums(); - Album parentAlbum = a.getParentAlbum(); - if (parentAlbum == null) { - orderedAlbums.add(0, a); - } else { - int i = orderedAlbums.indexOf(parentAlbum); - orderedAlbums.add(i + 1, a); - } + Album parentAlbum = a.getParentAlbum(); + if (parentAlbum == null) { + orderedAlbums.add(0, a); + } else { + int i = orderedAlbums.indexOf(parentAlbum); + orderedAlbums.add(i + 1, a); } - } catch (IllegalArgumentException e) { - it.remove(); - Log.log(Log.LEVEL_TRACE, MODULE, "Gallery server album list is corrupted: " + - "album " + a.getName() + " has a bad containment hierarchy."); } + } catch (IllegalArgumentException e) { + it.remove(); + Log.log(Log.LEVEL_TRACE, MODULE, "Gallery server album list is corrupted: " + + "album " + a.getName() + " has a bad containment hierarchy."); } - - depth++; } - Log.log(Log.LEVEL_TRACE, MODULE, "Ordered " + orderedAlbums.size() + " albums"); + depth++; + } - status(su, StatusUpdate.LEVEL_BACKGROUND, GRI18n.getString(MODULE, "ftchdAlbms")); + Log.log(Log.LEVEL_TRACE, MODULE, "Ordered " + orderedAlbums.size() + " albums"); - //g.setAlbumList(orderedAlbums); - } else { - throw new GR2Exception("Connection error: " + response.getStatusLine().toString()); - } + status(su, StatusUpdate.LEVEL_BACKGROUND, GRI18n.getString(MODULE, "ftchdAlbms")); } private class ListContentHandler implements ContentHandler { @@ -287,6 +391,181 @@ } } + class UploadTask extends GalleryTask { + //MyTransferListener transferListener; + + UploadTask(StatusUpdate su) { + super(su); + } + + void runTask() { + ArrayList<Picture> pictures = g.getAllUploadablePictures(); + + // get total file size + long totalSize = 0; + Iterator<Picture> iter = pictures.iterator(); + while (iter.hasNext()) { + Picture p = iter.next(); + totalSize += p.getFileSize(); + } + +// transferListener = new MyTransferListener(su); +// transferListener.sizeAllFiles = totalSize; +// transferListener.numberAllFiles = pictures.size(); + + su.startProgress(StatusUpdate.LEVEL_UPLOAD_ALL, 0, 100, GRI18n.getString(MODULE, "upPic"), false); + + if (su instanceof UploadProgress) { + ((UploadProgress) su).setCancelListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + su.updateProgressStatus(StatusUpdate.LEVEL_UPLOAD_ALL, GRI18n.getString(MODULE, "upStop")); + su.setUndetermined(StatusUpdate.LEVEL_UPLOAD_ALL, true); + interrupt(); + long startTime = System.currentTimeMillis(); + + while (!terminated && System.currentTimeMillis() < startTime + 10000) { + try { + Thread.sleep(1000); + } catch (InterruptedException e1) { + } + } + + if (!terminated) { + Log.log(Log.LEVEL_ERROR, "Thread would not terminate properly: killing it"); + thread.stop(); + + // since we killed the thread, it's not going to clean up after itself + cleanUp(); + } + + ((UploadProgress) su).done(); + } + }); + } + + // upload each file, one at a time + boolean allGood = true; + //int uploadedCount = 0; + iter = pictures.iterator(); + while (iter.hasNext() /*&& allGood*/ && !interrupt) { + Picture p = iter.next(); + + /*Object[] params = { + p.toString(), + new Integer((uploadedCount + 1)), + new Integer(pictures.size()), + new Integer((int) ((transferListener.sizeFilesDone + transferListener.sizeThisFile) / 1024 / 1024)), + new Integer((int) (transferListener.sizeAllFiles / 1024 / 1024)), + transferListener.getProjectedTimeLeft() + }; + su.updateProgressStatus(StatusUpdate.LEVEL_UPLOAD_ALL, GRI18n.getString(MODULE, "upStatus", params));*/ + + allGood = uploadPicture(p); + + //su.updateProgressValue(StatusUpdate.LEVEL_UPLOAD_ALL, ++uploadedCount); + + if (allGood) { + p.getParentAlbum().removePicture(p); + } + } + + if (allGood) { + su.stopProgress(StatusUpdate.LEVEL_UPLOAD_ALL, GRI18n.getString(MODULE, "upComplete")); + + if (su instanceof UploadProgress) { + if (((UploadProgress) su).isShutdown()) { + GalleryRemote._().getCore().shutdown(true); + } + } + + g.setDirty(false); + + GalleryRemote._().getCore().flushMemory(); + } else { + su.stopProgress(StatusUpdate.LEVEL_UPLOAD_ALL, GRI18n.getString(MODULE, "upFailed")); + } + } + + boolean uploadPicture(Picture p) { + try { + //transferListener.currentFile = p.toString(); + + status(su, StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "upPrep")); + + MultipartEntity entity = new MultipartEntity(); + + Charset utf8 = Charset.forName("UTF-8"); + JSONObject jsonEntity = new JSONObject(); + jsonEntity.put("type", "photo"); + if (p.getName() != null) + jsonEntity.put("name", p.getName()); + if (p.getTitle() != null) + jsonEntity.put("title", p.getTitle()); + if (p.getDescription() != null) + jsonEntity.put("description", p.getDescription()); + entity.addPart("entity", new StringBody(jsonEntity.toJSONString(), utf8)); + + ContentBody body = new FileBody(p.getUploadSource()); + entity.addPart("file", body); + + BufferedReader r = sendRequest(p.getParentAlbum().getUrl(), "post", entity); + + String url = ((JSONObject) JSONValue.parse(r)).get("url").toString(); + status(su, StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "upSucc")); + p.setUrl(url); + + Log.log(Log.LEVEL_INFO, "Uploaded " + p.getUploadSource().toString() + " to " + url); + + return true; + // set auto-rotate only if we do the rotation in GR, otherwise we'd be overriding the server setting +// if (p.getAngle() != 0) { +// opts[5] = new NVPair("auto_rotate", "no"); +// } + + // set up extra fields +// if (p.getExtraFieldsMap() != null && p.getExtraFieldsMap().size() > 0) { +// ArrayList optsList = new ArrayList(Arrays.asList(opts)); +// +// Iterator it = p.getExtraFieldsMap().keySet().iterator(); +// while (it.hasNext()) { +// String name = (String) it.next(); +// String value = p.getExtraField(name); +// +// optsList.add(new NVPair("extrafield." + name, value, utf8?"UTF-8":null)); +// } +// } +// +// opts = (NVPair[]) optsList.toArray(opts); +// } + + // load and validate the response +// Properties props = requestResponse(hdrs, data, g.getGalleryUrl(scriptName), true, su, this, transferListener); +// if (props.getProperty("status").equals(GR_STAT_SUCCESS)) { +// status(su, StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "upSucc")); +// String newItemName = props.getProperty("item_name"); +// if (newItemName != null) { +// su.doneUploading(newItemName, picture); +// } +// return true; +// } else { +// Object[] params = {props.getProperty("status_text")}; +// error(su, GRI18n.getString(MODULE, "upErr", params)); +// return false; +// } + } catch (GR2Exception gr2e) { + Log.logException(Log.LEVEL_ERROR, MODULE, gr2e); + Object[] params = {gr2e.getMessage()}; + error(su, p.toString() + ": " + GRI18n.getString(MODULE, "error", params)); + } catch (IOException ioe) { + Log.logException(Log.LEVEL_ERROR, MODULE, ioe); + Object[] params = {ioe.toString()}; + error(su, p.toString() + ": " + GRI18n.getString(MODULE, "error", params)); + } + + return false; + } + } + /** * This class serves as the base class for each GalleryComm task. */ @@ -326,4 +605,99 @@ abstract void runTask(); } + + /*class MyTransferListener implements TransferListener { + StatusUpdate su; + java.text.DecimalFormat df = new java.text.DecimalFormat("##,##0"); + java.text.DecimalFormat ff = new java.text.DecimalFormat("##,##0.0"); + + String currentFile; + + long sizeAllFiles; + long transferredFilesDone = 0; + long transferredThisFile = 0; + + int numberAllFiles; + int numberFilesDone = 0; + + long timeStarted = 0; + double kbPerSecond = 0; + + MyTransferListener(StatusUpdate su) { + this.su = su; + } + + public void dataTransferred(int transferredThisFile, int sizeThisFile, double kbPerSecond) { + this.transferredThisFile = transferredThisFile; + + Object[] params = { + df.format(transferredThisFile / 1024), + df.format(sizeThisFile / 1024), + ff.format(kbPerSecond / 1024.0)}; + + su.updateProgressStatus(StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "trnsfrStat", params)); + su.updateProgressValue(StatusUpdate.LEVEL_UPLOAD_ONE, transferredThisFile); + + params = new Object[] { + currentFile, + numberFilesDone + 1, + numberAllFiles, + (int) ((transferredFilesDone + transferredThisFile) / 1024 / 1024), + (int) (sizeAllFiles / 1024 / 1024), + getProjectedTimeLeft() + }; + su.updateProgressStatus(StatusUpdate.LEVEL_UPLOAD_ALL, GRI18n.getString(MODULE, "upStatus", params)); + su.updateProgressValue(StatusUpdate.LEVEL_UPLOAD_ALL, (int) ((transferredFilesDone + transferredThisFile) * 100 / sizeAllFiles)); + } + + public void transferStart(int sizeThisFile) { + this.transferredThisFile = sizeThisFile; + if (timeStarted == 0) { + timeStarted = System.currentTimeMillis(); + } + + su.updateProgressValue(StatusUpdate.LEVEL_UPLOAD_ONE, 0, sizeThisFile); + } + + public void transferEnd(int sizeThisFile) { + transferredFilesDone += sizeThisFile; + this.transferredThisFile = 0; + numberFilesDone++; + + su.updateProgressStatus(StatusUpdate.LEVEL_UPLOAD_ONE, GRI18n.getString(MODULE, "upCompSrvrProc")); + su.setUndetermined(StatusUpdate.LEVEL_UPLOAD_ONE, true); + } + + public String getProjectedTimeLeft() { + int secondsLeft = getProjectedSecondsLeft(); + + if (secondsLeft == -1) { + return ""; + } else if (secondsLeft >= 120) { + Object[] params = { secondsLeft / 60 }; + return GRI18n.getString(MODULE, "minutesLeft", params); + } else { + Object[] params = { secondsLeft }; + return GRI18n.getString(MODULE, "secondsLeft", params); + } + } + + public int getProjectedSecondsLeft() { + long timeNow = System.currentTimeMillis(); + + if (timeStarted == 0 || timeNow - timeStarted < 500) { + // just starting, unknown average speed + return -1; + } + + // average the current speed and the speed since start + double denom = (kbPerSecond + ((transferredFilesDone + transferredThisFile) / (timeNow - timeStarted) * 1000)) / 2; + + if (denom == 0) { + return -1; + } + + return (int) ((sizeAllFiles - transferredFilesDone - transferredThisFile) / denom); + } + }*/ } Modified: trunk/gallery_remote/com/gallery/GalleryRemote/GalleryCommTest.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/GalleryCommTest.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/GalleryCommTest.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -1,11 +1,17 @@ package com.gallery.GalleryRemote; +import com.gallery.GalleryRemote.model.Album; import com.gallery.GalleryRemote.model.Gallery; +import com.gallery.GalleryRemote.model.Picture; +import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; -import java.net.URL; +import java.io.File; +import static org.junit.Assert.*; + /** * Created by IntelliJ IDEA. * User: paour @@ -14,22 +20,88 @@ */ public class GalleryCommTest { public static final String MODULE = "CommTest"; + private Gallery g; + private StatusUpdate su; + private GalleryComm comm; @Test - public void testFetchAlbums() throws Exception { - StatusUpdate su = new StatusUpdateAdapter(); - Gallery g = new Gallery(su); - g.setUrlString("http://localhost/~paour/gallery3/"); + public void testFetchAlbums() { Log.log(Log.LEVEL_INFO, MODULE, "Starting fetchAlbums"); - GalleryComm comm = GalleryComm.getCommInstance(su, g); + comm.fetchAlbums(su, false); + } + + @Test + public void testFetchAlbumsBadKey() { Log.log(Log.LEVEL_INFO, MODULE, "Starting fetchAlbums"); + g.setKey("badkey"); comm.fetchAlbums(su, false); } - @Before - public void setup() { + @Test + public void testCheckAuthBadKey() { + g.setKey("badkey"); + g.setUsername("admin"); + g.setPassword("admin"); + assertTrue(comm.checkAuth()); + } + + @Test + public void testGetKey() { + g.setKey(""); + g.setUsername("admin"); + g.setPassword("admin"); + assertTrue(comm.checkAuth()); + } + + @Test + public void testGetKeyBadPass() { + g.setKey(""); + g.setUsername("admin"); + g.setPassword("adminfalse"); + assertFalse(comm.checkAuth()); + } + + @Test + public void testUploadFiles() { + comm.fetchAlbums(su, false); + + Album a = g.getRootAlbum(); + Picture p = new Picture(g, new File("Voeux2010.jpg")); + a.addPicture(p); + assertNull(p.getUrl()); + comm.uploadFiles(su, false); + assertNotNull(p.getUrl()); + } + @Test + public void testUploadFilesToRoot() { + Album a = new Album(g); + a.setUrl(g.getUrlString() + "index.php/rest/item/1"); + Picture p = new Picture(g, new File("Voeux2010.jpg")); + a.addPicture(p); + g.setRoot(a); + assertNull(p.getUrl()); + comm.uploadFiles(su, false); + assertNotNull(p.getUrl()); + } + + @BeforeClass + public static void setupAll() { GalleryRemote.createInstance("com.gallery.GalleryRemote.GalleryRemoteMainFrame", null); GalleryRemote._().initializeGR(); } + + @Before + public void setup() { + su = new StatusUpdateAdapter(); + g = new Gallery(su); + g.setUrlString("http://localhost/~paour/gallery3/"); + g.setKey("7c507344c89daeeb9c2c645d2d4b73b7"); + comm = GalleryComm.getCommInstance(su, g); + } + + @AfterClass + public static void shutdownAll() { + Log.shutdown(); + } } Modified: trunk/gallery_remote/com/gallery/GalleryRemote/GalleryRemoteMainFrame.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/GalleryRemoteMainFrame.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/GalleryRemoteMainFrame.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -46,8 +46,8 @@ if (created && OsShutdown.isUnix()) { try { Class c = GalleryRemote.secureClassForName("com.gallery.GalleryRemote.PrivateShutdown"); - Method m = c.getMethod("exec", null); - m.invoke(null, new Object[] { "chmod -R go-rwx " + f.getPath().replaceAll(" ", "\\ ") }); + Method m = c.getMethod("exec"); + m.invoke(null, "chmod -R go-rwx " + f.getPath().replaceAll(" ", "\\ ")); } catch (Throwable e) { Log.logException(Log.LEVEL_ERROR, MODULE, e); } Modified: trunk/gallery_remote/com/gallery/GalleryRemote/Log.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/Log.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/Log.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -53,9 +53,9 @@ static Log singleton = new Log(); static boolean started = false; - List logLines = Collections.synchronizedList(new LinkedList()); + List<String> logLines = Collections.synchronizedList(new LinkedList<String>()); boolean running = false; - List moduleList = null; + List<String> moduleList = null; private Log() {} @@ -150,7 +150,7 @@ singleton.loggerThread.join(); } catch (InterruptedException ee) { System.err.println("Logger thread killed"); - } catch (Throwable t) {} + } catch (Throwable ignored) {} started = false; singleton = new Log(); @@ -171,7 +171,7 @@ while (running) { Thread.sleep(sleepInterval); while (!logLines.isEmpty()) { - String s = (String) logLines.remove(0); + String s = logLines.remove(0); writer.write(s); writer.newLine(); @@ -214,10 +214,10 @@ try { String modules = System.getenv("GR_LOG_MODULES"); - if (modules != null) { - singleton.moduleList = Arrays.asList(modules.split(",")); - } - } catch (Throwable e) {} + if (modules != null) { + singleton.moduleList = Arrays.asList(modules.split(",")); + } + } catch (Throwable ignored) {} singleton.loggerThread = new Thread(singleton); singleton.loggerThread.setPriority(threadPriority); Modified: trunk/gallery_remote/com/gallery/GalleryRemote/MainFrame.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/MainFrame.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/MainFrame.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -296,7 +296,7 @@ GalleryComm comm = g.getComm(jStatusBar); // may have tried to connect and failed - if (comm != null && !GalleryComm.wasAuthFailure()) { + if (comm != null && comm.checkAuth()) { fetchAlbums(); } @@ -474,11 +474,11 @@ jMenuItemSave.setEnabled(false); jMenuItemSaveAs.setEnabled(false); }*/ -Log.log(Log.LEVEL_TRACE, currentGallery + " - " + currentGallery.getUsername() + " - " + currentGallery.hasComm() + " - " + currentGallery.getComm(jStatusBar).isLoggedIn()); +Log.log(Log.LEVEL_TRACE, currentGallery + " - " + currentGallery.getUsername() + " - " + currentGallery.hasComm()); if (currentGallery != null && currentGallery.getUsername() != null && currentGallery.hasComm() - && currentGallery.getComm(jStatusBar).isLoggedIn()) { + && currentGallery.getRoot() != null) { jLoginButton.setText(GRI18n.getString(MODULE, "Log_out")); } else { jLoginButton.setText(GRI18n.getString(MODULE, "Log_in")); @@ -495,8 +495,8 @@ jPictureInspector.setEnabled(enabled); jPicturesList.setEnabled(enabled && currentAlbum.getCanEdit()); jNewAlbumButton.setEnabled(!inProgress && currentGallery != null && currentGallery.hasComm() - && currentGallery.getComm(jStatusBar).isLoggedIn() - && currentGallery.getComm(jStatusBar).hasCapability(jStatusBar, GalleryCommCapabilities.CAPA_NEW_ALBUM) + && currentGallery.getRoot() != null + && currentGallery.getComm().hasCapability(GalleryCommCapabilities.CAPA_NEW_ALBUM) && currentAlbum != null && currentAlbum.getCanEdit()); // change image displayed @@ -531,13 +531,13 @@ int selN = jPicturesList.getSelectedIndices().length; if (sel == -1) { - Object[] params = {new Integer(currentAlbum.sizePictures()), - new Integer((int) (currentAlbum.getPictureFileSize() / 1024))}; + Object[] params = {currentAlbum.sizePictures(), + (int) (currentAlbum.getPictureFileSize() / 1024)}; jStatusBar.setStatus(GRI18n.getString(MODULE, "statusBarNoSel", params)); } else { - Object[] params = {new Integer(selN), + Object[] params = {selN, GRI18n.getString(MODULE, (selN == 1) ? "oneSel" : "manySel"), - new Integer((int) Album.getObjectFileSize(jPicturesList.getSelectedValues()) / 1024)}; + (int) Album.getObjectFileSize(jPicturesList.getSelectedValues()) / 1024}; jStatusBar.setStatus(GRI18n.getString(MODULE, "statusBarSel", params)); } @@ -1400,7 +1400,7 @@ showAboutBox(); } else if (command.equals("Fetch")) { if (getCurrentGallery().hasComm() - && getCurrentGallery().getComm(jStatusBar).isLoggedIn()) { + && getCurrentGallery().getRoot() != null) { // todo: save // We're currently logged in, but we might be dirty // so ask the user if it's OK to log out. @@ -1428,7 +1428,7 @@ GalleryComm comm = getCurrentGallery().getComm(jStatusBar); // may have tried to connect and failed - if (comm != null && !GalleryComm.wasAuthFailure()) { + if (comm != null && comm.checkAuth()) { fetchAlbums(); } } @@ -2002,7 +2002,10 @@ } public void flushMemory() { - thumbnailCache.flushMemory(); + if (thumbnailCache != null) + thumbnailCache.flushMemory(); + + if (previewFrame != null && previewFrame.loader != null) previewFrame.loader.flushMemory(); for (int i = 0; i < galleries.getSize(); i++) { Modified: trunk/gallery_remote/com/gallery/GalleryRemote/PictureInspector.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/PictureInspector.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/PictureInspector.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -397,7 +397,7 @@ jPath.setText(p.getSource().getParent()); } jAlbum.setText(p.getParentAlbum().getTitle()); - if (p.getParentAlbum().getGallery().getComm(mf.jStatusBar).hasCapability(mf.jStatusBar, GalleryCommCapabilities.CAPA_UPLOAD_CAPTION)) { + if (p.getParentAlbum().getGallery().getComm().hasCapability(GalleryCommCapabilities.CAPA_UPLOAD_CAPTION)) { jCaption.setText(p.getDescription()); jCaption.setEditable(true); jCaption.setBackground(UIManager.getColor("TextField.background")); Modified: trunk/gallery_remote/com/gallery/GalleryRemote/UploadProgress.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/UploadProgress.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/UploadProgress.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -111,8 +111,8 @@ try { Class osShutdown = GalleryRemote.secureClassForName("com.gallery.GalleryRemote.util.OsShutdown"); - Method canShutdown = osShutdown.getMethod("canShutdown", null); - if (((Boolean) canShutdown.invoke(null, null)).booleanValue()) { + Method canShutdown = osShutdown.getMethod("canShutdown"); + if ((Boolean) canShutdown.invoke(null)) { jPanel2.add(jShutdown, null); } } catch (Exception e) { Modified: trunk/gallery_remote/com/gallery/GalleryRemote/model/Album.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/model/Album.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/model/Album.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -52,7 +52,7 @@ /* ------------------------------------------------------------------------- * LOCAL STORAGE */ - ArrayList pictures = new ArrayList(); + ArrayList<Picture> pictures = new ArrayList<Picture>(); /* ------------------------------------------------------------------------- @@ -62,9 +62,9 @@ //ArrayList subAlbums = new ArrayList(); //Album parent; // parent Album - String title = GRI18n.getString(MODULE, "title"); + //String title = GRI18n.getString(MODULE, "title"); String name; - ArrayList extraFields; + ArrayList<String> extraFields; String summary; Boolean overrideResize = null; @@ -81,8 +81,8 @@ transient private Integer albumDepth; transient private boolean suppressEvents = false; - public static List extraFieldsNoShow = Arrays.asList(new String[]{"Capture date", "Upload date", "Description"}); - public static List extraFieldsNoShowG2 = Arrays.asList(new String[]{"Capture date", "Upload date"}); + public static List extraFieldsNoShow = Arrays.asList("Capture date", "Upload date", "Description"); + public static List extraFieldsNoShowG2 = Arrays.asList("Capture date", "Upload date"); public Album(Gallery gallery) { @@ -95,7 +95,7 @@ * Retrieves the album properties from the server. */ public void fetchAlbumProperties(StatusUpdate su) { - if (!hasFetchedInfo && getGallery().getComm(su).hasCapability(su, GalleryCommCapabilities.CAPA_ALBUM_INFO)) { + if (!hasFetchedInfo && getGallery().getComm().hasCapability(GalleryCommCapabilities.CAPA_ALBUM_INFO)) { if (su == null) { su = new StatusUpdateAdapter() { }; @@ -115,7 +115,7 @@ } public void fetchAlbumImages(StatusUpdate su, boolean recursive, int maxPictures, boolean random) { - if (getGallery().getComm(su).hasCapability(su, GalleryCommCapabilities.CAPA_FETCH_ALBUM_IMAGES)) { + if (getGallery().getComm().hasCapability(GalleryCommCapabilities.CAPA_FETCH_ALBUM_IMAGES)) { if (su == null) { su = new StatusUpdateAdapter() { }; @@ -145,7 +145,7 @@ } public void moveAlbumTo(StatusUpdate su, Album newParent) { - if (getGallery().getComm(su).hasCapability(su, GalleryCommCapabilities.CAPA_MOVE_ALBUM)) { + if (getGallery().getComm().hasCapability(GalleryCommCapabilities.CAPA_MOVE_ALBUM)) { if (su == null) { su = new StatusUpdateAdapter() { }; @@ -209,7 +209,7 @@ * * @return The pictures value */ - public Iterator getPictures() { + public Iterator<Picture> getPictures() { return pictures.iterator(); } @@ -247,7 +247,7 @@ * * @param files the files to create the pictures from */ - public ArrayList addPictures(File[] files) { + public ArrayList<Picture> addPictures(File[] files) { return addPictures(files, -1); } @@ -257,8 +257,8 @@ * @param files the files to create the pictures from * @param index the index in the list at which to begin adding */ - public ArrayList addPictures(File[] files, int index) { - List expandedFiles = Arrays.asList(files); + public ArrayList<Picture> addPictures(File[] files, int index) { + List<File> expandedFiles = Arrays.asList(files); Log.log(Log.LEVEL_TRACE, MODULE, "addPictures: " + expandedFiles); @@ -270,11 +270,9 @@ Log.log(Log.LEVEL_TRACE, MODULE, "addPictures (expanded): " + expandedFiles); - ArrayList pictures = new ArrayList(expandedFiles.size()); + ArrayList<Picture> pictures = new ArrayList<Picture>(expandedFiles.size()); - for (Iterator it = expandedFiles.iterator(); it.hasNext();) { - File f = (File) it.next(); - + for (File f : expandedFiles) { Picture p = new Picture(gallery, f); p.setParent(this); if (index == -1) { @@ -294,13 +292,12 @@ /** * Adds picturesA to the album */ - public void addPictures(List picturesL) { + public void addPictures(List<Picture> picturesL) { addPictures(picturesL, -1); } - public void addPictures(List picturesL, int index) { - for (Iterator it = picturesL.iterator(); it.hasNext();) { - Picture p = (Picture) it.next(); + public void addPictures(List<Picture> picturesL, int index) { + for (Picture p : picturesL) { p.setParent(this); if (index == -1) { pictures.add(p); @@ -341,7 +338,7 @@ } public void sortPicturesAlphabetically() { - Collections.sort(pictures, new NaturalOrderComparator()); + Collections.sort(pictures, new NaturalOrderComparator<Picture>()); fireContentsChanged(this, 0, pictures.size() - 1); } @@ -350,14 +347,11 @@ * date, then fall to the bottom. */ public void sortPicturesCreated() { - Collections.sort(pictures, new Comparator() { + Collections.sort(pictures, new Comparator<Picture>() { - public int compare(Object o1, Object o2) { + public int compare(Picture p1, Picture p2) { Date d1 = null, d2 = null; - Picture p1 = (Picture) o1; - Picture p2 = (Picture) o2; - if (p1.getExifData() != null) { d1 = p1.getExifData().getCreationDate(); } @@ -385,7 +379,7 @@ public void sortSubAlbums() { if (children != null) { - Collections.sort(children, new NaturalOrderComparator()); + Collections.sort(children, new NaturalOrderComparator<Album>()); } fireContentsChanged(this, 0, pictures.size() - 1); @@ -531,25 +525,16 @@ } /** - * Gets the title attribute of the Album object - * - * @return The title - */ - public String getTitle() { - return title; - } - - /** * Gets the aggregated file size of all the pictures in the album * * @return The file size (bytes) */ public long getPictureFileSize() { if (pictureFileSize == null) { - pictureFileSize = new Long(getPictureFileSize((Picture[]) pictures.toArray(new Picture[0]))); + pictureFileSize = getPictureFileSize((Picture[]) pictures.toArray(new Picture[0])); } - return pictureFileSize.longValue(); + return pictureFileSize; } /** @@ -572,8 +557,8 @@ public static long getObjectFileSize(Object[] pictures) { long total = 0; - for (int i = 0; i < pictures.length; i++) { - total += ((Picture) pictures[i]).getFileSize(); + for (Object picture : pictures) { + total += ((Picture) picture).getFileSize(); } return total; @@ -585,7 +570,7 @@ ret.append(title); if (pictures.size() != 0) { - ret.append(" (" + pictures.size() + ")"); + ret.append(" (").append(pictures.size()).append(")"); } // using canEdit here, since that's the only operation we perform @@ -647,13 +632,13 @@ super.setParent(a); }*/ - public ArrayList getExtraFields() { + public ArrayList<String> getExtraFields() { return extraFields; } public void setExtraFieldsString(String extraFieldsString) { if (extraFieldsString != null && extraFieldsString.length() > 0) { - extraFields = new ArrayList(); + extraFields = new ArrayList<String>(); StringTokenizer st = new StringTokenizer(extraFieldsString, ","); List noShow = null; if (getGallery().getGalleryVersion() == 1) { @@ -681,15 +666,14 @@ this.summary = summary; } - public ArrayList getPicturesList() { + public ArrayList<Picture> getPicturesList() { return pictures; } - ArrayList getUploadablePicturesList() { - ArrayList uploadable = new ArrayList(); + ArrayList<Picture> getUploadablePicturesList() { + ArrayList<Picture> uploadable = new ArrayList<Picture>(); - for (Iterator it = pictures.iterator(); it.hasNext();) { - Picture picture = (Picture) it.next(); + for (Picture picture : pictures) { if (!picture.isOnline()) { uploadable.add(picture); } @@ -698,11 +682,11 @@ return uploadable; } - void setPicturesList(ArrayList pictures) { + void setPicturesList(ArrayList<Picture> pictures) { this.pictures = pictures; - for (Iterator e = pictures.iterator(); e.hasNext();) { - ((Picture) e.next()).setParent(this); + for (Picture picture : pictures) { + picture.setParent(this); } fireContentsChanged(this, 0, pictures.size() - 1); @@ -710,10 +694,10 @@ public int getAlbumDepth() throws IllegalArgumentException { if (albumDepth == null) { - albumDepth = new Integer(depthHelper(0)); + albumDepth = depthHelper(0); } - return albumDepth.intValue(); + return albumDepth; } int depthHelper(int depth) throws IllegalArgumentException { @@ -811,7 +795,7 @@ public boolean getResize() { if (overrideResize != null) { - return overrideResize.booleanValue(); + return overrideResize; } else { return GalleryRemote._().properties.getBooleanProperty(RESIZE_BEFORE_UPLOAD); } @@ -819,7 +803,7 @@ public boolean getResizeDefault() { if (overrideResizeDefault != null) { - return overrideResizeDefault.booleanValue(); + return overrideResizeDefault; } else { return GalleryRemote._().properties.getIntDimensionProperty(RESIZE_TO) == 0; } @@ -835,7 +819,7 @@ public boolean getAddToBeginning() { if (overrideAddToBeginning != null) { - return overrideAddToBeginning.booleanValue(); + return overrideAddToBeginning; } else { // todo return false; Modified: trunk/gallery_remote/com/gallery/GalleryRemote/model/Gallery.java =================================================================== --- trunk/gallery_remote/com/gallery/GalleryRemote/model/Gallery.java 2010-06-18 15:37:31 UTC (rev 20972) +++ trunk/gallery_remote/com/gallery/GalleryRemote/model/Gallery.java 2010-06-23 12:41:35 UTC (rev 20973) @@ -155,7 +155,7 @@ } public void incrementViewCount(Picture p, StatusUpdate su) { - if (getComm(su).hasCapability(su, GalleryCommCapabilities.CAPA_INCREMENT_VIEW_COUNT)) { + if (getComm().hasCapability(GalleryCommCapabilities.CAPA_INCREMENT_VIEW_COUNT)) { Log.log(Log.LEVEL_INFO, MODULE, "Incrementing viewCount on " + p.toString()); getComm(su).incrementViewCount(su, p); @@ -163,9 +163,9 @@ } public void logOut() { - if (comm != null) { - comm.logOut(); - } + //if (comm != null) { + // comm.logOut(); + //} comm = null; setRoot(null); @@ -193,23 +193,20 @@ return (new File(defaultFilePath.toString())); } - public ArrayList getAllPictures() { + public ArrayList<Picture> getAllPictures() { return getAllPictures(false); } - public ArrayList getAllUploadablePictures() { + public ArrayList<Picture> getAllUploadablePictures() { return getAllPictures(true); } - public ArrayList getAllPictures(boolean onlyUploadable) { - ArrayList pictures = new ArrayList(); - ArrayList albumList = getFlatAlbumList(); + public ArrayList<Picture> getAllPictures(boolean onlyUploadable) { + ArrayList<Picture> pictures = new ArrayList<Picture>(); + ArrayList<Album> albumList = getFlatAlbumList(); if (albumList != null) { - Iterator i = albumList.iterator(); - while (i.hasNext()) { - Album a = (Album) i.next(); - + for (Album a : albumList) { if (onlyUploadable) { pictures.addAll(a.getUploadablePicturesList()); } else { @@ -389,8 +386,9 @@ } public void setKey(String key) { - if (!key.equals(this.key)) { - + if (key == null) { + this.key = null; + } else if (!key.equals(this.key)) { this.key = key; logOut(); @@ -594,20 +592,21 @@ return comm; } + public GalleryComm getComm() { + return comm; + } + public boolean hasComm() { return comm != null; } public Album getAlbumByName(String name) { - ArrayList albumList = getFlatAlbumList(); + ArrayList<Album> albumList = getFlatAlbumList(); if (albumList == null || name == null) { return null; } - Iterator it = albumList.iterator(); - while (it.hasNext()) ... [truncated message content] |