Android Open Source - dissertation-project File Joiner Backend






From Project

Back to project page dissertation-project.

License

The source code is released under:

MIT License

If you think the Android project dissertation-project listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.fyp.widerst.backend;
/* ww w.j  av a2s .  c o m*/
import static com.fyp.widerst.WiderstObjectifyService.ofy;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fyp.widerst.Constants;
import com.fyp.widerst.entity.DataPiece;
import com.fyp.widerst.entity.DataWhole;
import com.fyp.widerst.util.GcmHelper;
import com.google.appengine.api.LifecycleManager;
import com.google.appengine.api.LifecycleManager.ShutdownHook;
import com.google.appengine.api.blobstore.BlobstoreInputStream;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Work;

@SuppressWarnings("serial")
public class FileJoinerBackend extends HttpServlet {

    private static final Logger logger = Logger.getLogger(FileJoinerBackend.class.getName());

    /* Requires Instance-level access due to Transaction inner class */
    private DataWhole dataWhole = null;
    private Map<Key<DataPiece>, DataPiece> dataPieces;

    @Override
    /**
     * 
     */
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        setLifecycleManager();

        /* Query the DataWhole that requires re-structuring */
        final String dwKeyString = req.getParameter(Constants.DATAWHOLE_KEY_PARAM);

        if (null == dwKeyString) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            logger.log(Level.WARNING, "DataWhole Key is NULL!");
            return;
        }

        logger.log(Level.WARNING, "DataWhole Key is " + dwKeyString);

        Boolean transaction = ofy().transact(new Work<Boolean>() {
            @Override
            public Boolean run() {
                dataWhole = ofy().load().type(DataWhole.class).id(dwKeyString).get();
                if (null != dataWhole) {
                    if (null == dataWhole.getBlobKey()) {
                        if (dataWhole.getDataPieceKeyList().size() == dataWhole.getNumOfPieces()) {
                            return true;
                        }
                    } else {
                        return true;
                    }
                }
                logger.log(Level.SEVERE, "DataWhole NOT found!");
                return false;
            }
        });

        /* Check if an interrupt has been called */
        if (Thread.interrupted()) {
            return;
        }

        if (transaction) {
            if (structureFileAndPostToDb()) {
                GcmHelper.sendWholeCompletionNotification(dataWhole);
                resp.setStatus(HttpServletResponse.SC_OK);
            } else {
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    /**
     * @return
     * @throws IOException
     */
    private boolean structureFileAndPostToDb() throws IOException {

        /* Define the File API specific instances */
        BlobstoreService blobStoreService = BlobstoreServiceFactory.getBlobstoreService();
        FileService fileService = FileServiceFactory.getFileService();

        /* */
        final AppEngineFile blobFile = fileService.createNewBlobFile(dataWhole.getMimeType(), dataWhole.getFileName());

        /* */
        final FileWriteChannel writeChannel = fileService.openWriteChannel(blobFile, true);

        /* */
        Boolean transaction = ofy().transact(new Work<Boolean>() {
            @Override
            public Boolean run() {
                dataPieces = ofy().load().keys(dataWhole.getDataPieceKeyList());
                return dataPieces.size() > 0 ? true : false;
            }
        });

        if (transaction) {

            int length;
            byte[] buffer = new byte[1024000];

            for (int i = 1; i <= dataPieces.size(); i++) {

                Key<DataPiece> pieceKey = Key.create(Key.create(DataWhole.class, dataWhole.getKey()), DataPiece.class,
                        dataWhole.getKey() + i);

                DataPiece dataPiece = dataPieces.get(pieceKey);

                logger.log(Level.INFO, "DataPiece Blobkey is " + dataPiece.getBlobKey());
                BlobstoreInputStream blobStream = new BlobstoreInputStream(dataPiece.getBlobKey());

                while ((length = blobStream.read(buffer)) != -1) {
                    writeChannel.write(ByteBuffer.wrap(buffer, 0, length));
                }

                blobStream.close();
                blobStoreService.delete(dataPiece.getBlobKey());
            }

            writeChannel.closeFinally();

            dataWhole.setBlobKey(fileService.getBlobKey(blobFile));

            logger.log(Level.INFO, "New Blobkey is " + fileService.getBlobKey(blobFile));
            
            /* Remove the pieces once it has been successfully restructured */
            for (DataPiece piece : dataPieces.values()) {
                blobStoreService.delete(piece.getBlobKey());
            }

            Boolean dwTransaction = ofy().transact(new Work<Boolean>() {
                @Override
                public Boolean run() {
                    /* Persist the modified DataWhole */
                    dataWhole.setDataPieceKeyList(new ArrayList<Key<DataPiece>>());
                    ofy().save().entity(dataWhole).now();

                    /* Remove the DataWhole's children */
                    ofy().delete().entities(dataPieces.values()).now();

                    return true;
                }
            });

            return dwTransaction;
        }

        return false;

    }

    /**
     * 
     */
    private void setLifecycleManager() {
        /* Specify the lifecycle manager to be used */
        LifecycleManager.getInstance().setShutdownHook(new ShutdownHook() {
            @Override
            public void shutdown() {
                /*
                 * Calls interrupt on all threads within this instance.
                 * Therefore, periodic checks must be make to ensure this
                 * instance hasn't been told to shutdown.
                 */
                LifecycleManager.getInstance().interruptAllRequests();
            }
        });
    }
}




Java Source Code List

com.fyp.resilience.Constants.java
com.fyp.resilience.Flags.java
com.fyp.resilience.GCMIntentService.java
com.fyp.resilience.PreferenceConstants.java
com.fyp.resilience.ResilienceApplication.java
com.fyp.resilience.ResilienceController.java
com.fyp.resilience.activity.LicenceActivity.java
com.fyp.resilience.activity.ResilienceActivity.java
com.fyp.resilience.activity.SettingsActivity.java
com.fyp.resilience.adapter.ClientListAdapter.java
com.fyp.resilience.adapter.ConnectionListAdapter.java
com.fyp.resilience.adapter.FileListAdapter.java
com.fyp.resilience.connection.Connectable.java
com.fyp.resilience.connection.ServerDownloadConnectable.java
com.fyp.resilience.connection.ServerUploadConnectable.java
com.fyp.resilience.connection.UploadConnectable.java
com.fyp.resilience.connection.WifiDownloadConnectable.java
com.fyp.resilience.connection.WifiUploadConnectable.java
com.fyp.resilience.database.ResilienceDbHelper.java
com.fyp.resilience.database.ResilienceDbManager.java
com.fyp.resilience.database.model.DataPiece.java
com.fyp.resilience.database.model.DataWhole.java
com.fyp.resilience.event.ClientListChanged.java
com.fyp.resilience.event.ClientModified.java
com.fyp.resilience.event.ConnectionProgressChange.java
com.fyp.resilience.event.ConnectionStateChange.java
com.fyp.resilience.event.ConnectionsModified.java
com.fyp.resilience.event.PieceStateChange.java
com.fyp.resilience.event.ServerRegistrationChanged.java
com.fyp.resilience.event.ServerUploadFinished.java
com.fyp.resilience.event.WholeModified.java
com.fyp.resilience.event.WifiDownloadFinished.java
com.fyp.resilience.event.WifiUploadFinished.java
com.fyp.resilience.fragment.ClientsFragment.java
com.fyp.resilience.fragment.ConnectionsFragment.java
com.fyp.resilience.fragment.FilesFragment.java
com.fyp.resilience.interfaces.Messagable.java
com.fyp.resilience.interfaces.Partialable.java
com.fyp.resilience.proto.ProtoBuffSpecification.java
com.fyp.resilience.receiver.AbstractConnectivityBroadcastReceiver.java
com.fyp.resilience.receiver.BootReceiver.java
com.fyp.resilience.receiver.ConnectivityBroadcastReceiver.java
com.fyp.resilience.receiver.WiFiDirectBroadcastReceiver.java
com.fyp.resilience.register.RegisterRequestInitializer.java
com.fyp.resilience.register.RegisterRequest.java
com.fyp.resilience.register.RegisterScopes.java
com.fyp.resilience.register.Register.java
com.fyp.resilience.register.model.DeviceInfo.java
com.fyp.resilience.service.PieceUploadService.java
com.fyp.resilience.stream.PiecedRandomAccessFile.java
com.fyp.resilience.swarm.helper.NsdHelper.java
com.fyp.resilience.swarm.helper.SwarmHelperInterface.java
com.fyp.resilience.swarm.helper.WifiDirectSdHelper.java
com.fyp.resilience.swarm.model.SwarmClient.java
com.fyp.resilience.thread.ResilienceRunnable.java
com.fyp.resilience.thread.ResilienceThreadFactory.java
com.fyp.resilience.util.ConnectionUtils.java
com.fyp.resilience.util.Utils.java
com.fyp.resilience.view.ClientView.java
com.fyp.resilience.view.ConnectionView.java
com.fyp.resilience.view.FileView.java
com.fyp.resilience.view.PieceProgressIndicator.java
com.fyp.resilience.widerst.WiderstRequestInitializer.java
com.fyp.resilience.widerst.WiderstRequest.java
com.fyp.resilience.widerst.WiderstScopes.java
com.fyp.resilience.widerst.Widerst.java
com.fyp.resilience.widerst.model.DataPiecePartial.java
com.fyp.resilience.widerst.model.DataWholePartial.java
com.fyp.resilience.widerst.model.PostResponse.java
com.fyp.widerst.Constants.java
com.fyp.widerst.WiderstObjectifyService.java
com.fyp.widerst.backend.FileJoinerBackend.java
com.fyp.widerst.cron.CronJobServlet.java
com.fyp.widerst.endpoint.DataPieceEndpoint.java
com.fyp.widerst.endpoint.DeviceInfoEndpoint.java
com.fyp.widerst.entity.DataPiece.java
com.fyp.widerst.entity.DataWhole.java
com.fyp.widerst.entity.DeviceInfo.java
com.fyp.widerst.handler.BlobstoreUploadHandler.java
com.fyp.widerst.partial.DataPiecePartial.java
com.fyp.widerst.partial.DataWholePartial.java
com.fyp.widerst.response.PostResponse.java
com.fyp.widerst.servlet.WholeFileServer.java
com.fyp.widerst.util.DbHelper.java
com.fyp.widerst.util.GcmHelper.java