BrightSide Workbench Full Report + Source Code
FileUtil.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2011 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 package org.turro.elephant.impl.util;
19 
20 import java.io.BufferedReader;
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStreamReader;
26 import java.io.OutputStreamWriter;
27 import java.nio.ByteBuffer;
28 import java.nio.CharBuffer;
29 import java.nio.channels.FileChannel;
30 import java.nio.charset.Charset;
31 import java.util.Date;
32 import java.util.Locale;
33 import java.util.Properties;
34 import javax.servlet.ServletException;
35 import org.turro.string.ObjectString;
36 import org.turro.string.Strings;
37 import org.turro.collections.LinkedProperties;
38 import org.turro.elephant.context.ElephantContext;
39 import org.turro.elephant.context.IAction;
40 import org.turro.elephant.impl.abstracts.AbstractAction;
41 import org.turro.i18n.I_;
42 import org.turro.parser.wiki.WikiCompiler;
43 import org.turro.plugin.contacts.IContact;
44 
49 public class FileUtil extends AbstractAction implements IAction {
50 
51  public static final String
52  VALID_EXT_REGEXP = "\\.(jsp|html|htm|txt|zul|zhtml)",
53  VALID_LOCALE_REGEXP = "(_[a-zA-Z]{2})?(_[a-zA-Z]{2})?(_[a-zA-Z]{2})?";
54 
56  public FileUtil() {
57  }
58 
59  @Override
60  public int execute() throws Exception {
61  String context = getParameter("context"),
62  file = getParameter("file"),
63  lang = getParameter("lang"),
64  action = getActionParameter();
65 
66  if("edit".equals(action)) {
67  if(!constructor.isInRole("default:edit")) return IAction.ERROR;
68  if(!(constructor.isInRole("lang:" + lang) || constructor.isInRole("lang:all"))) return IAction.ERROR;
69  }
70  else if("new".equals(action)) {
71  if(!constructor.isInRole("default:new")) return IAction.ERROR;
72  file = "000" + ObjectString.formatObject(new Date(), "yyyyMMddHHmmssSSS", false) + lang + ".html";
73  }
74  else if("delete".equals(action)) {
75  if(!constructor.isInRole("default:delete")) return IAction.ERROR;
76  removeFiles(context, crudeName(file));
78  return IAction.DONE;
79  }
80  else if("preview".equals(action)) {
81  if(!constructor.isInRole("default:edit")) return IAction.ERROR;
82  if(!(constructor.isInRole("lang:" + lang) || constructor.isInRole("lang:all"))) return IAction.ERROR;
83  createPreview();
84  return IAction.DONE;
85  }
86 
87  file = substituteLang(file, lang);
88 
89  File result = new File(ElephantContext.getRealPath(context + "/" + file));
90  IContact user = constructor.getUser();
91  String actual = crudeName(file) +
92  "." +
93  ObjectString.formatObject(new Date(), "yyyyMMddHHmmssSSS", false) +
94  "." +
95  user.getId() +
96  lang +
97  ".wiki";
98  File wiki = new File(ElephantContext.getRealPath(context + "/" + actual));
99 
100  saveContent(wiki, result);
101 
103  return IAction.DONE;
104  }
105 
106  private void createPreview() throws IOException, ServletException {
107  String s = constructor.getParameter("body", true);
108  if(s != null) {
109  //constructor.addHeaders(ContextFactory.getFactoryElement("default-element"));
110  constructor.getOut().print(
111  "<INPUT align='right' type='button' value='" +
112  I_.get("Close") +
113  "' onClick='window.close()' /><hr />");
114  constructor.getOut().print("<div class='default-element'><div class='default-body'>");
115  constructor.processOutput(WikiCompiler.source(s).constructor(constructor).html());
116  constructor.getOut().print("</div></div></body></html>");
117  }
118  }
119 
120  private void saveContent(File wiki, File result) throws IOException {
121  String s = constructor.getParameter("body");
122  if(s != null) {
123  setContent(wiki, s);
124  setContent(result, WikiCompiler.source(s).constructor(constructor).html());
125  }
126  }
127 
128  private void removeFiles(String context, String prefix) {
129  File folder = new File(ElephantContext.getRealPath(context));
130  File files[] = folder.listFiles();
131  for(int i = 0; i < files.length; i++) {
132  if(files[i].getName().matches(prefix + ".*")) {
133  files[i].delete();
134  }
135  }
136  }
137 
138  public static CharSequence getCharSequenceFile(String filename) throws IOException {
139  FileInputStream fis = new FileInputStream(filename);
140  FileChannel fc = fis.getChannel();
141  ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int)fc.size());
142  CharBuffer cbuf = Charset.forName(ElephantContext.getEncoding()).newDecoder().decode(bbuf);
143  return cbuf;
144  }
145 
146  public static BufferedReader getBufferedFile(String folder, String file) throws java.io.IOException {
147  return getBufferedFile(folder + "/" + file);
148  }
149 
150  public static BufferedReader getBufferedFile(String file) throws java.io.IOException {
151  return getBufferedFile(new File(file));
152  }
153 
154  public static BufferedReader getBufferedFile(File file) throws java.io.IOException {
155  return new BufferedReader(new InputStreamReader(new FileInputStream(file), ElephantContext.getEncoding()));
156  }
157 
158  public static OutputStreamWriter getFileWriter(String folder, String file) throws java.io.IOException {
159  return getFileWriter(folder + "/" + file);
160  }
161 
162  public static OutputStreamWriter getFileWriter(String file) throws java.io.IOException {
163  return getFileWriter(new File(file));
164  }
165 
166  public static OutputStreamWriter getFileWriter(File file) throws java.io.IOException {
167  return getFileWriter(file, false);
168  }
169 
170  public static OutputStreamWriter getFileWriter(File file, boolean append) throws java.io.IOException {
171  return new OutputStreamWriter(new FileOutputStream(file, append), ElephantContext.getEncoding());
172  }
173 
174  public static Properties getProperties(File file) throws java.io.IOException {
175  Properties properties = new Properties();
176  properties.load(new InputStreamReader(new FileInputStream(file), ElephantContext.getEncoding()));
177  return properties;
178  }
179 
180  public static Properties getOrderedProperties(File file) throws java.io.IOException {
181  Properties properties = new LinkedProperties();
182  properties.load(new InputStreamReader(new FileInputStream(file), ElephantContext.getEncoding()));
183  return properties;
184  }
185 
186  public static String substituteLang(String file, String lang) {
187  String extension = file.substring(file.lastIndexOf("."));
188  return file.replaceAll(VALID_LOCALE_REGEXP + VALID_EXT_REGEXP + "$", lang + extension);
189  }
190 
191  public static String baseName(String file) {
192  if(file.matches(".*" + VALID_EXT_REGEXP)) {
193  String extension = file.substring(file.lastIndexOf("."));
194  return file.replaceAll(VALID_LOCALE_REGEXP + VALID_EXT_REGEXP + "$", extension);
195  }
196  return null;
197  }
198 
199  public static String extension(String name) {
200  int p = name.lastIndexOf(".");
201  if(p > -1 && p < name.length()) {
202  return name.substring(p + 1);
203  }
204  return null;
205  }
206 
207  public static String crudeName(String file) {
208  if(file.matches(".*" + VALID_EXT_REGEXP)) {
209  return file.replaceAll(VALID_LOCALE_REGEXP + VALID_EXT_REGEXP + "$", "");
210  }
211  return null;
212  }
213 
214  public static Locale getLocale(String file) {
215  file = file.substring(0, file.lastIndexOf("."));
216  int p = file.indexOf("_");
217  if(p > -1) {
218  try {
219  return Locale.forLanguageTag(file.substring(p + 1));
220  } catch(Exception ex) {
221  return Locale.ENGLISH;
222  }
223  } else {
224  return Locale.ENGLISH;
225  }
226  }
227 
228  public static String getLang(String file) {
229  file = file.substring(0, file.lastIndexOf("."));
230  int p = file.indexOf("_");
231  if(p > -1)
232  return file.substring(p);
233  else
234  return "";
235  }
236 
237  public static String getRealContext(String context) {
238  int p;
239  if((p = context.indexOf("/_internal")) > -1) {
240  return context.substring(0, p);
241  }
242  return context;
243  }
244 
245  public static String getContent(File file) throws IOException {
246  if(file.exists()) {
247  BufferedReader br = getBufferedFile(file);
248  StringBuilder sb = new StringBuilder();
249  String s;
250  while((s = br.readLine()) != null) {
251  sb.append(s);
252  }
253  br.close();
254  return sb.toString();
255  }
256  return null;
257  }
258 
259  public static String getContentWithLineBreaks(File file) throws IOException {
260  if(file.exists()) {
261  BufferedReader br = getBufferedFile(file);
262  StringBuilder sb = new StringBuilder();
263  String s;
264  while((s = br.readLine()) != null) {
265  sb.append(s);
266  sb.append("\n");
267  }
268  br.close();
269  return sb.toString();
270  }
271  return null;
272  }
273 
274  public static void setContent(File file, String value) throws IOException {
275  if(value != null) {
276  OutputStreamWriter osw = getFileWriter(file);
277  osw.write(value);
278  osw.close();
279  }
280  }
281 
282  public static void appendContent(File file, String value) throws IOException {
283  if(value != null) {
284  OutputStreamWriter osw = getFileWriter(file, true);
285  osw.write(value);
286  osw.close();
287  }
288  }
289 
290  public static File getFolderFile(File file) {
291  String filePath = file.getAbsolutePath();
292  return new File(filePath.substring(0, filePath.lastIndexOf('/')));
293  }
294 
295  public static String checkFileName(File folder, String name) {
296  return checkFileName(folder.getAbsolutePath(), name);
297  }
298 
299  public static String checkFileName(String path, String name) {
300  if(!path.contains("WEB-INF")) {
301  name = Strings.unpunctuate(name);
302  }
303  return name;
304  }
305 
306  public static boolean existsFile(String requestURI) {
307  File f = new File(requestURI);
308  return f.exists() && f.isFile();
309  }
310 
311 }
static OutputStreamWriter getFileWriter(File file, boolean append)
Definition: FileUtil.java:170
static String getLang(String file)
Definition: FileUtil.java:228
static boolean existsFile(String requestURI)
Definition: FileUtil.java:306
static String substituteLang(String file, String lang)
Definition: FileUtil.java:186
static String baseName(String file)
Definition: FileUtil.java:191
static Locale getLocale(String file)
Definition: FileUtil.java:214
static OutputStreamWriter getFileWriter(String folder, String file)
Definition: FileUtil.java:158
static String getContentWithLineBreaks(File file)
Definition: FileUtil.java:259
static String getRealContext(String context)
Definition: FileUtil.java:237
static OutputStreamWriter getFileWriter(File file)
Definition: FileUtil.java:166
static CharSequence getCharSequenceFile(String filename)
Definition: FileUtil.java:138
static final String VALID_EXT_REGEXP
Definition: FileUtil.java:52
static Properties getOrderedProperties(File file)
Definition: FileUtil.java:180
static String checkFileName(File folder, String name)
Definition: FileUtil.java:295
static void appendContent(File file, String value)
Definition: FileUtil.java:282
static void setContent(File file, String value)
Definition: FileUtil.java:274
static String checkFileName(String path, String name)
Definition: FileUtil.java:299
static Properties getProperties(File file)
Definition: FileUtil.java:174
static String crudeName(String file)
Definition: FileUtil.java:207
static OutputStreamWriter getFileWriter(String file)
Definition: FileUtil.java:162
static BufferedReader getBufferedFile(String folder, String file)
Definition: FileUtil.java:146
static File getFolderFile(File file)
Definition: FileUtil.java:290
static String extension(String name)
Definition: FileUtil.java:199
static BufferedReader getBufferedFile(String file)
Definition: FileUtil.java:150
static BufferedReader getBufferedFile(File file)
Definition: FileUtil.java:154
static String getContent(File file)
Definition: FileUtil.java:245
static String get(String msg)
Definition: I_.java:41
String getParameter(String param)