Created
June 19, 2015 18:26
-
-
Save jdc18/c6c8689e269e655581cb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.RandomAccessFile; | |
import java.nio.file.Files; | |
import java.nio.file.Paths; | |
import java.util.Date; | |
import javax.ejb.EJB; | |
import javax.servlet.ServletException; | |
import javax.servlet.http.HttpServlet; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
import javax.ws.rs.core.Context; | |
import org.apache.commons.io.FilenameUtils; | |
import org.jboss.resteasy.spi.HttpRequest; | |
import org.keycloak.KeycloakSecurityContext; | |
import org.keycloak.representations.AccessToken; | |
import ec.com.unika.dao.ArchivoDao; | |
import ec.com.unika.enums.EstadoArchivo; | |
import ec.com.unika.enums.TipoArchivo; | |
import ec.com.unika.js.upload.FlowInfo; | |
import ec.com.unika.js.upload.FlowInfoStorage; | |
import ec.com.unika.js.upload.HttpUtils; | |
import ec.com.unika.model.Archivo; | |
import ec.com.unika.model.Usuario; | |
/** | |
* | |
* This is a servlet demo, for using Flow.js to upload files. | |
* | |
* by fanxu123 | |
*/ | |
public class UploadServlet extends HttpServlet { | |
private static final long serialVersionUID = 1L; | |
// TODO poner esto en un archivo de configuracions | |
public static final String UPLOAD_DIR = "/home/jdc/tmp"; | |
// TODO poner archivos permitidos aca | |
@EJB | |
ArchivoDao archivoDao; | |
@Context | |
private HttpRequest httpRequest; | |
protected void doPost(HttpServletRequest request, | |
HttpServletResponse response) throws ServletException, IOException { | |
/*KeycloakSecurityContext securityContext = (KeycloakSecurityContext) httpRequest | |
.getAttribute(KeycloakSecurityContext.class.getName()); | |
AccessToken accessToken = securityContext.getToken(); | |
System.out | |
.println(String | |
.format("User '%s' with email '%s' made request to CustomerService REST endpoint", | |
accessToken.getPreferredUsername(), | |
accessToken.getEmail()));*/ | |
// | |
int flowChunkNumber = getflowChunkNumber(request); | |
FlowInfo info = getFlowInfo(request); | |
RandomAccessFile raf = new RandomAccessFile(info.flowFilePath, "rw"); | |
// Seek to position | |
raf.seek((flowChunkNumber - 1) * info.flowChunkSize); | |
// Save to file | |
InputStream is = request.getInputStream(); | |
long readed = 0; | |
long content_length = request.getContentLength(); | |
byte[] bytes = new byte[1024 * 100]; | |
while (readed < content_length) { | |
int r = is.read(bytes); | |
if (r < 0) { | |
break; | |
} | |
raf.write(bytes, 0, r); | |
readed += r; | |
} | |
raf.close(); | |
// Mark as uploaded. | |
info.uploadedChunks.add(new FlowInfo.flowChunkNumber(flowChunkNumber)); | |
String archivoFinal = info.checkIfUploadFinished(); | |
if (archivoFinal != null) { // Check if all chunks uploaded, and | |
// change filename | |
FlowInfoStorage.getInstance().remove(info); | |
response.getWriter().print("All finished."); | |
// Si esta terminado grabar con estado de subido | |
// TODO obtener la ID del usuario, quitar esto del codigo | |
Usuario usuario = new Usuario(); | |
// user.setId(3L); | |
/* | |
* Archivo archivo = new Archivo(); | |
* archivo.setEstadoArchivo(EstadoArchivo.SERVIDOR); Date | |
* fechaActual = new Date(); archivo.setFechaSubida(fechaActual); | |
* archivo.setUsuario(usuario); // System.out.println(); File file = | |
* new File(archivoFinal); String mimeType = | |
* Files.probeContentType(Paths.get(file .getAbsolutePath())); | |
* | |
* archivo.setMimeType(mimeType); archivo.setTamano(file.length()); | |
* archivo.setTitulo(info.flowFilename); | |
* archivo.setExtension(FilenameUtils.getExtension(archivoFinal)); | |
* archivo.setDirectorio(file.getParent()); | |
* archivo.setPath(archivoFinal); | |
* | |
* // TODO que vea el tipo de archivo | |
* archivo.setTipoArchivo(TipoArchivo.IMAGEN); | |
* | |
* //Todo bien Grabamos FUCKING A archivoDao.create(archivo); | |
*/ | |
} else { | |
response.getWriter().print("Upload"); | |
} | |
} | |
protected void doGet(HttpServletRequest request, | |
HttpServletResponse response) throws ServletException, IOException { | |
int flowChunkNumber = getflowChunkNumber(request); | |
FlowInfo info = getFlowInfo(request); | |
// System.out.println("flowChunkNumber: "+FlowInfo.flowChunkNumber(flowChunkNumber)); | |
Object fcn = new FlowInfo.flowChunkNumber(flowChunkNumber); | |
// System.out.println("aaaa "+info.f); | |
if (info.uploadedChunks.contains(fcn)) { | |
System.out.println("Do Get arriba"); | |
response.getWriter().print("Uploaded."); // This Chunk has been | |
// Uploaded. | |
} else { | |
System.out.println("Do Get se cago"); | |
response.setStatus(HttpServletResponse.SC_NOT_FOUND); | |
} | |
} | |
private int getflowChunkNumber(HttpServletRequest request) { | |
return HttpUtils.toInt(request.getParameter("flowChunkNumber"), -1); | |
} | |
private FlowInfo getFlowInfo(HttpServletRequest request) | |
throws ServletException { | |
/* | |
* TODO obtener usuario con el token, seguridades De prueba vamos a | |
* subir con el id 3 | |
*/ | |
String userId = Long.toString(3L); | |
String base_dir = UPLOAD_DIR + "/" + userId; | |
// Vemos si se puede crear Directorio, si no puede ser creado | |
if (!crearDirectorioPrivado(base_dir)) { | |
throw new ServletException( | |
"No existe el directorio tmp y no pudo ser creado, contactese con el administrador."); | |
} | |
int FlowChunkSize = HttpUtils.toInt( | |
request.getParameter("flowChunkSize"), -1); | |
long FlowTotalSize = HttpUtils.toLong( | |
request.getParameter("flowTotalSize"), -1); | |
String FlowIdentifier = request.getParameter("flowIdentifier"); | |
String FlowFilename = request.getParameter("flowFilename"); | |
String FlowRelativePath = request.getParameter("flowRelativePath"); | |
// Here we add a ".temp" to every upload file to indicate NON-FINISHED | |
String FlowFilePath = new File(base_dir, FlowFilename) | |
.getAbsolutePath() + ".temp"; | |
FlowInfoStorage storage = FlowInfoStorage.getInstance(); | |
FlowInfo info = storage.get(FlowChunkSize, FlowTotalSize, | |
FlowIdentifier, FlowFilename, FlowRelativePath, FlowFilePath); | |
if (!info.valid()) { | |
storage.remove(info); | |
throw new ServletException("Invalid request params."); | |
} | |
return info; | |
} | |
private boolean crearDirectorioPrivado(String dir) { | |
// Vemos si esta creado, si no lo creamos | |
File carpeta = new File(dir); | |
if (!carpeta.exists()) { | |
if (carpeta.mkdir()) { | |
System.out.println("Directorio " + dir + " creado!"); | |
return true; | |
} else { | |
System.out.println("No se pudo crear el directorio " + dir); | |
return false; | |
} | |
} | |
System.out.println("Directorio" + dir + " ya existe no fue creado"); | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment