use of jmri.jmrit.roster.RosterEntry in project JMRI by JMRI.
the class RosterServlet method doPost.
/**
* Handle any POST request as an upload of a roster file from client.
*
* @param request servlet request
* @param response servlet response
* @throws javax.servlet.ServletException if unable to process uploads
* @throws java.io.IOException if communications is cut with
* client
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
OutputStream out = null;
InputStream fileContent = null;
String rosterFolderName = Roster.getDefault().getRosterLocation() + "roster" + File.separator;
String tempFolderName = System.getProperty("java.io.tmpdir");
if (!tempFolderName.endsWith(File.separator)) {
//make sure path ends with a separator
tempFolderName += File.separator;
}
Locale rl = request.getLocale();
//get the uploaded file(s)
List<FileMeta> files = MultipartRequestHandler.uploadByJavaServletAPI(request);
List<String> msgList = new ArrayList<>();
//loop thru files returned and validate and (if ok) save each
for (FileMeta fm : files) {
log.debug("processing uploaded '{}' file '{}' ({}), group='{}', roster='{}', temp='{}'", fm.getFileType(), fm.getFileName(), fm.getFileSize(), fm.getRosterGroup(), rosterFolderName, tempFolderName);
//only allow xml files or image files
if (!fm.getFileType().equals("text/xml") && !fm.getFileType().startsWith("image")) {
String m = String.format(rl, Bundle.getMessage(rl, "ErrorInvalidFileType"), fm.getFileName(), fm.getFileType());
log.error(m);
msgList.add(m);
//stop processing this one
break;
}
//save received file to temporary folder
File fileTemp = new File(tempFolderName + fm.getFileName());
try {
out = new FileOutputStream(fileTemp);
fileContent = fm.getContent();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = fileContent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
log.debug("file '{}' of type '{}' temp saved to {}", fm.getFileType(), fm.getFileName(), tempFolderName);
} catch (IOException e) {
String m = String.format(rl, Bundle.getMessage(rl, "ErrorSavingFile"), fm.getFileName());
log.error(m);
msgList.add(m);
//stop processing this one
break;
} finally {
if (out != null) {
out.close();
}
if (fileContent != null) {
fileContent.close();
}
}
//finally
//reference to target file name and location
File fileNew = new File(rosterFolderName + fm.getFileName());
//save image file, replacing if parm is set that way. return appropriate message
if (fm.getFileType().startsWith("image")) {
if (fileNew.exists()) {
if (!fm.getFileReplace()) {
String m = String.format(rl, Bundle.getMessage(rl, "ErrorFileExists"), fm.getFileName());
log.error(m);
msgList.add(m);
//get rid of temp file
fileTemp.delete();
} else {
//delete the old file
fileNew.delete();
if (fileTemp.renameTo(fileNew)) {
String m = String.format(rl, Bundle.getMessage(rl, "FileReplaced"), fm.getFileName());
log.debug(m);
msgList.add(m);
} else {
String m = String.format(rl, Bundle.getMessage(rl, "ErrorRenameFailed"), fm.getFileName());
log.error(m);
msgList.add(m);
//get rid of temp file
fileTemp.delete();
}
}
} else {
if (fileTemp.renameTo(fileNew)) {
String m = String.format(rl, Bundle.getMessage(rl, "FileAdded"), fm.getFileName());
log.debug(m);
msgList.add(m);
} else {
String m = String.format(rl, Bundle.getMessage(rl, "ErrorRenameFailed"), fm.getFileName());
log.error(m);
msgList.add(m);
//get rid of temp file
fileTemp.delete();
}
}
} else {
// create a temp rosterentry to check, based on uploaded file
RosterEntry reTemp = null;
try {
reTemp = RosterEntry.fromFile(new File(tempFolderName + fm.getFileName()));
} catch (JDOMException e) {
//handle XML failures
String m = String.format(rl, Bundle.getMessage(rl, "ErrorInvalidXML"), fm.getFileName(), e.getMessage());
log.error(m);
msgList.add(m);
//get rid of temp file
fileTemp.delete();
break;
}
//get existing entry if found
RosterEntry reOld = Roster.getDefault().getEntryForId(reTemp.getId());
if (reOld != null) {
if (!fm.getFileReplace()) {
String m = String.format(rl, Bundle.getMessage(rl, "ErrorFileExists"), fm.getFileName());
log.error(m);
msgList.add(m);
//get rid of temp file
fileTemp.delete();
} else {
//replace specified
//remove the old entry from roster
Roster.getDefault().removeEntry(reOld);
//saves XML file to roster folder and makes backup
reTemp.updateFile();
//add the new entry to roster
Roster.getDefault().addEntry(reTemp);
//save modified roster.xml file
Roster.getDefault().writeRoster();
String m = String.format(rl, Bundle.getMessage(rl, "RosterEntryReplaced"), fm.getFileName(), reTemp.getDisplayName());
log.debug(m);
msgList.add(m);
//get rid of temp file
fileTemp.delete();
}
} else {
//move the file to proper location
fileTemp.renameTo(fileNew);
Roster.getDefault().addEntry(reTemp);
Roster.getDefault().writeRoster();
String m = String.format(rl, Bundle.getMessage(rl, "RosterEntryAdded"), fm.getFileName(), reTemp.getId());
log.debug(m);
msgList.add(m);
}
}
}
//for FileMeta
//respond with a json list of messages from the upload attempts
response.setContentType("application/json");
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), msgList);
}
use of jmri.jmrit.roster.RosterEntry in project JMRI by JMRI.
the class RosterServlet method doRoster.
/**
* Generate the JSON, XML, or HTML output specified by {@link #doList(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)},
* {@link #doGroup(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String)},
* or
* {@link #doEntry(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}.
*
* @param request servlet request with format and locale for response
* @param response servlet response
* @param filter a JSON object with name-value pairs of parameters for
* {@link jmri.jmrit.roster.Roster#getEntriesMatchingCriteria(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)}.
* @throws java.io.IOException if communications is cut with client
*/
protected void doRoster(HttpServletRequest request, HttpServletResponse response, JsonNode filter) throws IOException {
ServletUtil.getInstance().setNonCachingHeaders(response);
log.debug("Getting roster with filter {}", filter);
String group = (!filter.path(GROUP).isMissingNode()) ? filter.path(GROUP).asText() : null;
log.debug("Group {} was in filter", group);
String format = request.getParameter(FORMAT);
if (format == null) {
format = "";
}
switch(format) {
case JSON.JSON:
response.setContentType(UTF8_APPLICATION_JSON);
JsonRosterServiceFactory factory = InstanceManager.getOptionalDefault(JsonRosterServiceFactory.class).orElseGet(() -> {
return InstanceManager.setDefault(JsonRosterServiceFactory.class, new JsonRosterServiceFactory());
});
response.getWriter().print(factory.getHttpService(mapper).getRoster(request.getLocale(), filter));
break;
case JSON.XML:
response.setContentType(UTF8_APPLICATION_XML);
File roster = new File(Roster.getDefault().getRosterIndexPath());
if (roster.exists()) {
response.getWriter().print(FileUtil.readFile(roster));
}
break;
case "html":
String row;
if ("simple".equals(request.getParameter("view"))) {
row = FileUtil.readURL(FileUtil.findURL(Bundle.getMessage(request.getLocale(), "SimpleTableRow.html")));
} else {
row = FileUtil.readURL(FileUtil.findURL(Bundle.getMessage(request.getLocale(), "TableRow.html")));
}
StringBuilder builder = new StringBuilder();
// NOI18N
response.setContentType(UTF8_TEXT_HTML);
if (Roster.AllEntries(request.getLocale()).equals(group)) {
group = null;
}
List<RosterEntry> entries = Roster.getDefault().getEntriesMatchingCriteria((!filter.path(ROAD).isMissingNode()) ? filter.path(ROAD).asText() : null, (!filter.path(NUMBER).isMissingNode()) ? filter.path(NUMBER).asText() : null, (!filter.path(ADDRESS).isMissingNode()) ? filter.path(ADDRESS).asText() : null, (!filter.path(MFG).isMissingNode()) ? filter.path(MFG).asText() : null, (!filter.path(DECODER_MODEL).isMissingNode()) ? filter.path(DECODER_MODEL).asText() : null, (!filter.path(DECODER_FAMILY).isMissingNode()) ? filter.path(DECODER_FAMILY).asText() : null, (!filter.path(NAME).isMissingNode()) ? filter.path(NAME).asText() : null, group);
entries.stream().forEach((entry) -> {
// NOTE: changing the following order will break JavaScript and HTML code
builder.append(String.format(request.getLocale(), row, entry.getId(), entry.getRoadName(), entry.getRoadNumber(), entry.getMfg(), entry.getModel(), entry.getOwner(), entry.getDccAddress(), entry.getDecoderModel(), entry.getDecoderFamily(), entry.getDecoderComment(), entry.getComment(), entry.getURL(), entry.getMaxSpeedPCT(), entry.getFileName(), StringUtil.escapeString(entry.getId())));
});
response.getWriter().print(builder.toString());
break;
default:
if (group == null) {
group = Roster.AllEntries(request.getLocale());
}
// NOI18N
response.setContentType(UTF8_TEXT_HTML);
response.getWriter().print(String.format(request.getLocale(), FileUtil.readURL(FileUtil.findURL(Bundle.getMessage(request.getLocale(), "Roster.html"))), String.format(request.getLocale(), Bundle.getMessage(request.getLocale(), "HtmlTitle"), ServletUtil.getInstance().getRailroadName(false), Bundle.getMessage(request.getLocale(), "RosterTitle")), ServletUtil.getInstance().getNavBar(request.getLocale(), request.getContextPath()), ServletUtil.getInstance().getRailroadName(false), ServletUtil.getInstance().getFooter(request.getLocale(), request.getContextPath()), group));
break;
}
}
use of jmri.jmrit.roster.RosterEntry in project JMRI by JMRI.
the class PaneProgFrameTest method testFrame.
// show me the specially-created frame
public void testFrame() {
if (GraphicsEnvironment.isHeadless()) {
return;
}
setupDoc();
PaneProgFrame p = new PaneProgFrame(null, new RosterEntry(), "test frame", "programmers/Basic.xml", new jmri.progdebugger.ProgDebugger(), false) {
// dummy implementations
@Override
protected JPanel getModePane() {
return null;
}
};
// ugly, temporary way to load the decoder info
jmri.jmrit.decoderdefn.DecoderFileTest t = new jmri.jmrit.decoderdefn.DecoderFileTest("");
t.setupDecoder();
// used as a temporary
DecoderFile df = new DecoderFile();
df.loadVariableModel(t.decoder, p.variableModel);
p.readConfig(root, new RosterEntry());
p.pack();
p.setVisible(true);
JFrame f = jmri.util.JmriJFrame.getFrame("test frame");
Assert.assertTrue("found frame", f != null);
f.dispose();
}
use of jmri.jmrit.roster.RosterEntry in project JMRI by JMRI.
the class JsonRosterServer method dispose.
public void dispose() {
Roster.getDefault().removePropertyChangeListener(this.rosterListener);
for (RosterEntry re : Roster.getDefault().getEntriesInGroup(Roster.ALLENTRIES)) {
re.removePropertyChangeListener(this.rosterEntryListener);
}
this.listening = false;
}
use of jmri.jmrit.roster.RosterEntry in project JMRI by JMRI.
the class JsonRosterServer method listen.
public void listen() {
if (!this.listening) {
Roster.getDefault().addPropertyChangeListener(this.rosterListener);
for (RosterEntry re : Roster.getDefault().getEntriesInGroup(Roster.ALLENTRIES)) {
re.addPropertyChangeListener(this.rosterEntryListener);
}
this.listening = true;
}
}
Aggregations