Changeset 10494


Ignore:
Timestamp:
Apr 19, 2011, 3:36:26 AM (13 years ago)
Author:
anthony43
Message:

addSimple ws api method added, with unit tests
http://piwigo.org/doc/doku.php?id=en:dev:webapi:pwg.images.addsimple
pom upgraded to 0.3.0-SNAPSHOT since this is a minor change, and also a dependency was added (httpmime)
SessionManagerImpl was modified to make available its httpclient.

Location:
extensions/jiwigo-ws-api
Files:
1 added
7 edited

Legend:

Unmodified
Added
Removed
  • extensions/jiwigo-ws-api/pom.xml

    r10091 r10494  
    33  <groupId>fr.mael.jiwigo</groupId>
    44  <artifactId>jiwigo-ws-api</artifactId>
    5   <version>0.2b</version>
     5  <version>0.3.0-SNAPSHOT</version>
    66  <dependencies>
    77
     
    3636                <scope>test</scope>
    3737        </dependency>
    38 
     38        <dependency>
     39                <groupId>org.apache.httpcomponents</groupId>
     40                <artifactId>httpmime</artifactId>
     41                <version>4.1.1</version>
     42                <type>jar</type>
     43                <scope>compile</scope>
     44        </dependency>
    3945  </dependencies>
    4046
  • extensions/jiwigo-ws-api/src/main/java/fr/mael/jiwigo/dao/ImageDao.java

    r9919 r10494  
    11package fr.mael.jiwigo.dao;
    22
     3import java.io.File;
    34import java.io.IOException;
    45import java.security.NoSuchAlgorithmException;
     
    6869    public List<Image> search(String searchString) throws IOException, ProxyAuthenticationException;
    6970
     71    /**
     72     * Uses the pwg.images.addsimple web API to add a new picture
     73     * http://piwigo.org/doc/doku.php?id=en:dev:webapi:pwg.images.addsimple
     74     *
     75     * @param file
     76     * @param category
     77     * @param title
     78     * @throws IOException
     79     */
     80    public void addSimple(File file, Integer category, String title) throws IOException;
     81
    7082}
  • extensions/jiwigo-ws-api/src/main/java/fr/mael/jiwigo/dao/impl/ImageDaoImpl.java

    r9919 r10494  
    11package fr.mael.jiwigo.dao.impl;
    22
     3import java.io.BufferedReader;
    34import java.io.File;
    45import java.io.IOException;
     6import java.io.InputStreamReader;
     7import java.net.HttpURLConnection;
    58import java.security.NoSuchAlgorithmException;
    69import java.util.ArrayList;
     
    811import java.util.List;
    912
     13import org.apache.http.HttpEntity;
     14import org.apache.http.HttpResponse;
     15import org.apache.http.client.methods.HttpPost;
     16import org.apache.http.entity.BufferedHttpEntity;
     17import org.apache.http.entity.mime.MultipartEntity;
     18import org.apache.http.entity.mime.content.FileBody;
     19import org.apache.http.entity.mime.content.StringBody;
    1020import org.slf4j.Logger;
    1121import org.slf4j.LoggerFactory;
     
    2333import fr.mael.jiwigo.transverse.exception.WrongChunkSizeException;
    2434import fr.mael.jiwigo.transverse.session.SessionManager;
     35import fr.mael.jiwigo.transverse.session.impl.SessionManagerImpl;
    2536import fr.mael.jiwigo.transverse.util.Tools;
    2637
     
    89100            Document doc = null;
    90101            if (categoryId != null) {
    91                 doc = sessionManager.executeReturnDocument(MethodsEnum.LISTER_IMAGES.getLabel(), "cat_id", String
    92                         .valueOf(categoryId));
     102                doc = sessionManager.executeReturnDocument(MethodsEnum.LISTER_IMAGES.getLabel(), "cat_id",
     103                        String.valueOf(categoryId));
    93104            } else {
    94105                doc = sessionManager.executeReturnDocument(MethodsEnum.LISTER_IMAGES.getLabel());
     
    133144        //sends the thumbnail and gets the result
    134145        Document reponseThumb = (sessionManager.executeReturnDocument("pwg.images.addChunk", "data", thumbnailBase64,
    135                 "type", "thumb", "position", "1", "original_sum", Tools.getMD5Checksum(image.getOriginale()
    136                         .getAbsolutePath())));
     146                "type", "thumb", "position", "1", "original_sum",
     147                Tools.getMD5Checksum(image.getOriginale().getAbsolutePath())));
    137148
    138149        //begin feature:0001827
     
    147158            String originaleBase64 = base64.encode(Tools.getBytesFromFile(fichierAEnvoyer));
    148159            Document reponseOriginale = (sessionManager.executeReturnDocument("pwg.images.addChunk", "data",
    149                     originaleBase64, "type", "file", "position", String.valueOf(i), "original_sum", Tools
    150                             .getMD5Checksum(image.getOriginale().getAbsolutePath())));
     160                    originaleBase64, "type", "file", "position", String.valueOf(i), "original_sum",
     161                    Tools.getMD5Checksum(image.getOriginale().getAbsolutePath())));
    151162            if (!Tools.checkOk(reponseOriginale)) {
    152163                echec = true;
     
    157168
    158169        //add the image in the database and get the result of the webservice
    159         Document reponseAjout = (sessionManager.executeReturnDocument("pwg.images.add", "file_sum", Tools
    160                 .getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum", Tools.getMD5Checksum(image
    161                 .getThumbnail().getCanonicalPath()), "position", "1", "original_sum", Tools.getMD5Checksum(image
    162                 .getOriginale().getAbsolutePath()), "categories", String.valueOf(image.getIdCategory()), "name", image
    163                 .getName(), "author", sessionManager.getLogin(), "level", image.getPrivacyLevel()));
     170        Document reponseAjout = (sessionManager.executeReturnDocument("pwg.images.add", "file_sum",
     171                Tools.getMD5Checksum(image.getOriginale().getAbsolutePath()), "thumbnail_sum",
     172                Tools.getMD5Checksum(image.getThumbnail().getCanonicalPath()), "position", "1", "original_sum",
     173                Tools.getMD5Checksum(image.getOriginale().getAbsolutePath()), "categories",
     174                String.valueOf(image.getIdCategory()), "name", image.getName(), "author", sessionManager.getLogin(),
     175                "level", image.getPrivacyLevel()));
    164176        LOG.debug("Response add : " + Tools.documentToString(reponseAjout));
    165177        //      System.out.println(Main.sessionManager.executerReturnString("pwg.images.add", "file_sum", Outil
     
    189201     */
    190202    public boolean addTags(Integer imageId, String tagId) throws IOException, ProxyAuthenticationException {
    191         Document doc = sessionManager.executeReturnDocument(MethodsEnum.SET_INFO.getLabel(), "image_id", String
    192                 .valueOf(imageId), "tag_ids", tagId);
     203        Document doc = sessionManager.executeReturnDocument(MethodsEnum.SET_INFO.getLabel(), "image_id",
     204                String.valueOf(imageId), "tag_ids", tagId);
    193205        try {
    194206            return Tools.checkOk(doc);
     
    260272    }
    261273
     274    public void addSimple(File file, Integer category, String title) throws IOException {
     275        HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl());
     276
     277        //      nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple"));
     278        //      for (int i = 0; i < parametres.length; i += 2) {
     279        //          nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1]));
     280        //      }
     281        //      method.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     282
     283        if (file != null) {
     284            MultipartEntity multipartEntity = new MultipartEntity();
     285
     286            //          String string = nameValuePairs.toString();
     287            // dirty fix to remove the enclosing entity{}
     288            //          String substring = string.substring(string.indexOf("{"),
     289            //                          string.lastIndexOf("}") + 1);
     290            multipartEntity.addPart("method", new StringBody("pwg.images.addSimple"));
     291            multipartEntity.addPart("category", new StringBody(category.toString()));
     292            multipartEntity.addPart("name", new StringBody(title));
     293
     294            //          StringBody contentBody = new StringBody(substring,
     295            //                          Charset.forName("UTF-8"));
     296            //          multipartEntity.addPart("entity", contentBody);
     297            FileBody fileBody = new FileBody(file);
     298            multipartEntity.addPart("image", fileBody);
     299            ((HttpPost) httpMethod).setEntity(multipartEntity);
     300        }
     301
     302        //      httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
     303        HttpResponse response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod);
     304        int responseStatusCode = response.getStatusLine().getStatusCode();
     305
     306        switch (responseStatusCode) {
     307        case HttpURLConnection.HTTP_CREATED:
     308            break;
     309        case HttpURLConnection.HTTP_OK:
     310            break;
     311        case HttpURLConnection.HTTP_BAD_REQUEST:
     312            throw new IOException("status code was : " + responseStatusCode);
     313        case HttpURLConnection.HTTP_FORBIDDEN:
     314            throw new IOException("status code was : " + responseStatusCode);
     315        case HttpURLConnection.HTTP_NOT_FOUND:
     316            throw new IOException("status code was : " + responseStatusCode);
     317        default:
     318            throw new IOException("status code was : " + responseStatusCode);
     319        }
     320
     321        HttpEntity resultEntity = response.getEntity();
     322        BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity);
     323
     324        BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
     325        String line;
     326        StringBuilder sb = new StringBuilder();
     327        try {
     328            while ((line = reader.readLine()) != null) {
     329                sb.append(line);
     330                sb.append("\n");
     331            }
     332        } finally {
     333            reader.close();
     334        }
     335        String stringResult = sb.toString();
     336
     337    }
     338
    262339    public SessionManager getSessionManager() {
    263340        return sessionManager;
     
    267344        this.sessionManager = sessionManager;
    268345    }
    269 
    270346}
  • extensions/jiwigo-ws-api/src/main/java/fr/mael/jiwigo/service/ImageService.java

    r9919 r10494  
    11package fr.mael.jiwigo.service;
    22
     3import java.io.File;
    34import java.io.IOException;
    45import java.security.NoSuchAlgorithmException;
     
    5960    public List<Image> search(String queryString) throws IOException, ProxyAuthenticationException;
    6061
     62    /**
     63     * Uses the pwg.images.addsimple web API to add a new picture
     64     * http://piwigo.org/doc/doku.php?id=en:dev:webapi:pwg.images.addsimple
     65     *
     66     * @param file
     67     * @param category
     68     * @param title
     69     * @throws IOException
     70     */
     71    public void addSimple(File file, Integer category, String title) throws IOException;
     72
    6173}
  • extensions/jiwigo-ws-api/src/main/java/fr/mael/jiwigo/service/impl/ImageServiceImpl.java

    r9919 r10494  
    9090            //the methode Outil.enrich will fail, but the procedure has to continue
    9191            try {
    92                 byte[] fichierEnrichi = Tools.enrich(bytesFichierOriginal, Tools.getBytesFromFile(new File(System
    93                         .getProperty("java.io.tmpdir")
    94                         + "/originale.jpg")));
     92                byte[] fichierEnrichi = Tools.enrich(bytesFichierOriginal,
     93                        Tools.getBytesFromFile(new File(System.getProperty("java.io.tmpdir") + "/originale.jpg")));
    9594                Tools.byteToFile(System.getProperty("java.io.tmpdir") + "/originale.jpg", fichierEnrichi);
    9695            } catch (Exception e) {
     
    145144    }
    146145
     146    public void addSimple(File file, Integer category, String title) throws IOException {
     147        dao.addSimple(file, category, title);
     148
     149    }
     150
    147151    public ImageDao getDao() {
    148152        return dao;
  • extensions/jiwigo-ws-api/src/main/java/fr/mael/jiwigo/transverse/session/impl/SessionManagerImpl.java

    r9919 r10494  
    327327    }
    328328
     329    public DefaultHttpClient getClient() {
     330        return client;
     331    }
     332
    329333}
  • extensions/jiwigo-ws-api/src/test/java/fr/mael/jiwigo/service/ServicesTest.java

    r10089 r10494  
    11package fr.mael.jiwigo.service;
     2
     3import java.io.File;
     4import java.io.IOException;
     5import java.util.List;
    26
    37import junit.framework.Assert;
     
    1721public class ServicesTest {
    1822
    19         private SessionManager sessionManager;
     23    private SessionManager sessionManager;
    2024
    21         @Before
    22         public void setUp() {
    23                 sessionManager = new SessionManagerImpl("mael", "motdepasse", "http://mael.piwigo.com", "Unit Test");
    24                 sessionManager.processLogin();
     25    @Before
     26    public void setUp() {
     27        sessionManager = new SessionManagerImpl("mael", "motdepasse", "http://mael.piwigo.com", "Unit Test");
     28        sessionManager.processLogin();
     29    }
     30
     31    @Test
     32    public void testCreer() throws Exception {
     33        Category cat = null;
     34        CategoryServiceImpl categoryService = new CategoryServiceImpl();
     35        CategoryDaoImpl categoryDao = new CategoryDaoImpl();
     36        categoryDao.setSessionManager(sessionManager);
     37        categoryService.setDao(categoryDao);
     38
     39        ImageServiceImpl imageService = new ImageServiceImpl();
     40        ImageDaoImpl imageDao = new ImageDaoImpl();
     41        imageDao.setSessionManager(sessionManager);
     42        imageService.setDao(imageDao);
     43        //we choose category number 3
     44        for (Category category : categoryService.list(true)) {
     45            if (category.getIdentifier().equals(3)) {
     46                cat = category;
     47                break;
     48            }
     49        }
     50        //we look for the first picture of category 3
     51        Image image = imageService.listByCategory(cat.getIdentifier(), true).get(0);
     52        Assert.assertEquals("test de test do not delete", cat.getName());
     53        Assert.assertEquals("20110329194915-0c0b3f36.jpg", image.getFile());
     54
     55    }
     56
     57    @Test
     58    public void addSimpleTest() {
     59
     60        // we prepare the service implementing add-simple
     61        ImageServiceImpl imageService = new ImageServiceImpl();
     62        ImageDaoImpl dao = new ImageDaoImpl();
     63        dao.setSessionManager(sessionManager);
     64        imageService.setDao(dao);
     65
     66        //we prepare the resource to send
     67        File imageFile = new File(this.getClass().getClassLoader().getResource("piwigo_org.png").getPath());
     68        //      File imageFile = new File("piwigo_org.png");
     69        Integer categoryTest = 98;
     70        String title = "title" + System.currentTimeMillis();
     71        try {
     72            imageService.addSimple(imageFile, categoryTest, title);
     73        } catch (IOException e) {
     74            Assert.fail("An exception was thrown while trying to send the pictures" + e.getMessage());
    2575        }
    2676
    27         @Test
    28         public void testCreer() throws Exception {
    29                 Category cat = null;
    30                 CategoryServiceImpl categoryService = new CategoryServiceImpl();
    31                 CategoryDaoImpl categoryDao = new CategoryDaoImpl();
    32                 categoryDao.setSessionManager(sessionManager);
    33                 categoryService.setDao(categoryDao);
     77        //the image should be sent, let's check if piwigo added it to the category.
     78        boolean found = false;
     79        List<Image> listByCategory;
     80        try {
     81            listByCategory = imageService.listByCategory(categoryTest, true);
     82            for (Image image : listByCategory) {
     83                if (image.getName().equals(title)) {
     84                    found = true;
     85                    break;
     86                }
     87            }
     88        } catch (Exception e) {
     89            Assert.fail("An exception was thrown while trying to fetch the pictures from category " + categoryTest
     90                    + "exception was : " + e.getMessage());
     91        }
     92        Assert.assertTrue("The picture just sent could not be found", found);
    3493
    35                 ImageServiceImpl imageService = new ImageServiceImpl();
    36                 ImageDaoImpl imageDao = new ImageDaoImpl();
    37                 imageDao.setSessionManager(sessionManager);
    38                 imageService.setDao(imageDao);
    39 
    40                 for (Category category : categoryService.list(true)) {
    41                         if (category.getIdentifier().equals(3)) {
    42                                 cat = category;
    43                                 break;
    44                         }
    45                 }
    46                 Image image = imageService.listByCategory(cat.getIdentifier(), true).get(0);
    47                 Assert.assertEquals("test de test do not delete", cat.getName());
    48                 Assert.assertEquals("20110329194915-0c0b3f36.jpg", image.getFile());
    49 
    50         }
     94    }
    5195}
Note: See TracChangeset for help on using the changeset viewer.