source: tapas/web/src/com/ether/WebHelper.java @ 449

Last change on this file since 449 was 449, checked in by vmipsl, 12 years ago

downloadFile to response

File size: 6.4 KB
Line 
1package com.ether;
2
3import com.ether.WebException.WebCode;
4import com.ether.user.User;
5import net.sf.json.JSONObject;
6import org.apache.commons.logging.Log;
7import org.apache.commons.logging.LogFactory;
8import org.jetbrains.annotations.NotNull;
9import org.jetbrains.annotations.Nullable;
10
11import javax.servlet.ServletOutputStream;
12import javax.servlet.http.HttpServletRequest;
13import javax.servlet.http.HttpServletResponse;
14import java.io.BufferedInputStream;
15import java.io.File;
16import java.io.FileInputStream;
17import java.io.IOException;
18import java.io.InputStream;
19import java.io.OutputStream;
20import java.io.PrintWriter;
21import java.security.InvalidParameterException;
22import java.util.Properties;
23
24public final class WebHelper
25{
26    private WebHelper()
27    {
28    }
29
30    @NotNull
31    public static String getRequestParameter( @NotNull final HttpServletRequest httpServletRequest, @Nullable final String parameterName, @Nullable final String defaultParameterValue, final boolean canBeNull )
32            throws InvalidParameterException
33    {
34        String parameterValue;
35        if( null == parameterName )
36            parameterValue = defaultParameterValue;
37
38        parameterValue = httpServletRequest.getParameter( parameterName );
39
40        if( parameterValue == null )
41            parameterValue = defaultParameterValue;
42
43        if( !canBeNull && parameterValue == null )
44            throw new InvalidParameterException( parameterName );
45
46        return parameterValue;
47    }
48
49    public static void writeJsonToResponse( @NotNull final HttpServletResponse httpServletResponse, @NotNull final String data )
50            throws IOException
51    {
52        httpServletResponse.setCharacterEncoding( UTF8Charset.getEncoding() );
53        httpServletResponse.setContentType( CONTENT_TYPE_TEXT_JSON );
54
55        final PrintWriter writer = httpServletResponse.getWriter();
56        writer.write( data );
57    }
58
59    public static void displayAjaxError( @NotNull final HttpServletResponse response, @Nullable final String methodName )
60            throws WebException
61    {
62        try
63        {
64            response.setStatus( HttpServletResponse.SC_NOT_IMPLEMENTED );
65            response.setCharacterEncoding( UTF8Charset.getEncoding() );
66            response.setContentType( "text/plain;charset=" + UTF8Charset.getEncoding() );
67            final ServletOutputStream outputStream = response.getOutputStream();
68            outputStream.print( "error.method_not_implemented : " + methodName + " is not implemented." );
69            outputStream.flush();
70            outputStream.close();
71        }
72        catch( IOException e )
73        {
74            throw new WebException( WebCode.IO_EXCEPTION_ERROR_TO_GET_OUTPUTSTREAM, e );
75        }
76    }
77
78    /**
79     * This method returns the user in session if there is one
80     *
81     * @param request
82     * @return
83     */
84    public static JSONObject getJSONUser( @NotNull final HttpServletRequest request )
85    {
86        final JSONObject jSONPeople = new JSONObject();
87
88        final User user = (User) request.getSession().getAttribute( "SES_USER" );
89        if( null == user )
90            return null;
91
92        jSONPeople.put( "name", user.getLastName() );
93        jSONPeople.put( "firstName", user.getFirstName() );
94        jSONPeople.put( "role", user.getRole() );
95        return jSONPeople;
96    }
97
98    /**
99     * Returns the property writed in the properties file
100     *
101     * @param request
102     * @param property
103     * @return
104     * @throws WebException
105     */
106    public static String getProperty( @NotNull final HttpServletRequest request, @NotNull final String property )
107            throws WebException
108    {
109        try
110        {
111            final String webInfPath = request.getSession().getServletContext().getRealPath( "WEB-INF" );
112            return getProperty( webInfPath + "/classes/", PROPERTIES_FILE, property );
113        }
114        catch( IOException e )
115        {
116            throw new WebException( WebException.WebCode.ERROR_TO_READ_FILE_PROPERTIES, e );
117        }
118    }
119
120    /**
121     * Returns the property writed in a properties file
122     *
123     * @param pathFile
124     * @param fileName
125     * @param property @return
126     * @throws IOException
127     */
128    public static String getProperty( @NotNull final String pathFile, final String fileName, @NotNull final String property )
129            throws IOException
130    {
131        final Properties prop = new Properties();
132        prop.load( new FileInputStream( pathFile + fileName ) );
133        return prop.getProperty( property );
134    }
135
136    /**
137     * This method send to the response (to download) the file named fileName localized in the path downloadPath
138     *
139     * @param fileName
140     * @param downloadPath
141     * @param response
142     * @throws WebException
143     */
144    public static void downloadFileToResponse( @NotNull final String fileName, @NotNull final String downloadPath, @NotNull final HttpServletResponse response )
145            throws WebException
146    {
147        response.setContentType( "multipart/zip" );
148        response.setHeader( "Content-Disposition", "attachment; filename=\"" + fileName.trim() + "\";" );
149
150        final File file = new File( downloadPath + fileName );
151        if( !file.exists() )
152            throw new WebException( WebException.WebCode.ERROR_TO_DOWNLOAD_FILE, file.getPath() );
153
154        response.setContentLength( (int) file.length() );
155        try
156        {
157            final OutputStream outputStream = response.getOutputStream();
158            final FileInputStream fileInputStream = new FileInputStream( file );
159
160            final BufferedInputStream bufferedInputStream = new BufferedInputStream( fileInputStream );
161            final InputStream inputStream = new BufferedInputStream( bufferedInputStream );
162
163            int count;
164            final byte[] buf = new byte[4096];
165            while( ( count = inputStream.read( buf ) ) > -1 )
166                outputStream.write( buf, 0, count );
167            inputStream.close();
168            outputStream.close();
169        }
170        catch( Exception ex )
171        {
172            throw new WebException( WebException.WebCode.ERROR_TO_DOWNLOAD_FILE, ex );
173        }
174    }
175
176    public static final int STATUS_CODE_SERVICE_EXCEPTION = 500;
177    public static final String PROPERTIES_FILE = "tapas.properties";
178
179    private static final Log LOGGER = LogFactory.getLog( WebHelper.class );
180    private static final String CONTENT_TYPE_TEXT_JSON = "text/javascript;charset=" + UTF8Charset.getEncoding();
181}
Note: See TracBrowser for help on using the repository browser.