Java tutorial
// Copyright 2007 Hitachi Data Systems // All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may // not use this file except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. package com.archivas.clienttools.arcmover.cli; import com.archivas.clienttools.arcutils.api.ArcMoverFactory; import com.archivas.clienttools.arcutils.api.JobException; import com.archivas.clienttools.arcutils.api.jobs.ManagedJobSummary; import com.archivas.clienttools.arcutils.config.ConfigurationHelper; import com.archivas.clienttools.arcutils.utils.database.DatabaseException; import org.apache.commons.cli.*; import org.apache.commons.lang.text.StrBuilder; import java.io.PrintWriter; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class ArcJobMgr extends AbstractArcCli { public static final String PACKAGE_NAME = ArcProfileMgr.class.getPackage().getName(); public static final String CLASS_FULL_NAME = ArcProfileMgr.class.getName(); public static final String CLASS_NAME = CLASS_FULL_NAME.substring(PACKAGE_NAME.length() + 1); public static Logger LOG = Logger.getLogger(CLASS_FULL_NAME); // Help Constants private static String HELP_USAGE_LINE; private static final String HELP_HEADER = "Deletes, or displays information about saved jobs.\nTo rerun a job use hcpdm copy --rerun <job_name> or hcpdm delete --rerun <job_name>\n\n"; private static final String HELP_FOOTER = ""; /** Command Line Options **/ private static Options cliOptions; /** Stored commandline inputs **/ private static String jobName = null; /** Parsed Fields **/ enum JobMgrAction { LIST("list", "l", null, "Displays the list of saved jobs."), DELETE("delete", "d", "job_name", "Deletes the job from the job list."), HELP("help", "h", null, "Displays this help text (the default behavior)."); String cmdLineLongOpt; String cmdLineShortOpt; String argName; String description; JobMgrAction(String cmdLineLongOpt, String cmdLineShortOpt, String argName, String description) { this.cmdLineLongOpt = cmdLineLongOpt; this.cmdLineShortOpt = cmdLineShortOpt; this.argName = argName; this.description = description; } public String getCmdLineLongOpt() { return cmdLineLongOpt; } public String getCmdLineShortOpt() { return cmdLineShortOpt; } public String getArgName() { return argName; } public String getDescription() { return description; } } private static JobMgrAction cmdAction; /** Labels for Job Listing **/ private final static String JOB_NAME_LABEL = "Name"; private final static String JOB_TYPE_LABEL = "Job Type"; private final static String JOB_STATE_LABEL = "State"; private final static String COL_SEP = " "; public ArcJobMgr(String args[]) { super(args); HELP_USAGE_LINE = commandName + " job -d <job_name> | -l"; } @SuppressWarnings({ "static-access" }) public Options getOptions() { if (cliOptions == null) { Options options = new Options(); addOption(options, JobMgrAction.HELP); addOption(options, JobMgrAction.LIST); addOption(options, JobMgrAction.DELETE); cliOptions = options; } return cliOptions; } private void addOption(Options options, JobMgrAction action) { if (action.getArgName() != null) { options.addOption(OptionBuilder.hasOptionalArg().withArgName(action.getArgName()) .withDescription(action.getDescription()).withLongOpt(action.getCmdLineLongOpt()) .create(action.getCmdLineShortOpt())); } else { options.addOption(OptionBuilder.withDescription(action.getDescription()) .withLongOpt(action.getCmdLineLongOpt()).create(action.getCmdLineShortOpt())); } } public String getHelpFooter() { return HELP_FOOTER; } public String getHelpHeader() { return HELP_HEADER; } public String getHelpUsageLine() { return HELP_USAGE_LINE; } @SuppressWarnings({ "UseOfSystemOutOrSystemErr" }) public static void main(String args[]) { ArcJobMgr arcJobMgr = null; ConfigurationHelper.validateLaunchOK(); try { arcJobMgr = new ArcJobMgr(args); arcJobMgr.parseArgs(); if (cmdAction == JobMgrAction.HELP) { System.out.println(arcJobMgr.helpScreen()); } else { arcJobMgr.execute(new PrintWriter(System.out), new PrintWriter(System.err)); } } catch (ParseException e) { System.out.println("Error: " + e.getMessage()); System.out.println(); System.out.println(arcJobMgr.helpScreen()); arcJobMgr.setExitCode(EXIT_CODE_OPTION_PARSE_ERROR); } catch (Exception e) { LOG.log(Level.SEVERE, "Unexpected Exception.", e); System.out.println(); System.out.println("Failed to create a new profile " + e.getMessage()); arcJobMgr.setExitCode(EXIT_CODE_DM_ERROR); } finally { if (arcJobMgr != null) { arcJobMgr.exit(); } } } @SuppressWarnings({ "UnusedCatchParameter" }) protected void parseArgs() throws ParseException { // create the command cmdLine parser CommandLineParser parser = new PosixParser(); CommandLine cmdLine; // parse the command cmdLine arguments cmdLine = parser.parse(getOptions(), getArgs()); cmdAction = JobMgrAction.HELP; if (cmdLine.hasOption(JobMgrAction.LIST.getCmdLineLongOpt())) { cmdAction = JobMgrAction.LIST; } else if (cmdLine.hasOption(JobMgrAction.DELETE.getCmdLineLongOpt())) { cmdAction = JobMgrAction.DELETE; jobName = cmdLine.getOptionValue(JobMgrAction.DELETE.getCmdLineShortOpt()); } else if (!cmdLine.hasOption(JobMgrAction.HELP.getCmdLineLongOpt())) { throw new ParseException("Illegal options passed in."); } } /** * Entry point for generating a directory listing. */ public void execute(PrintWriter out, PrintWriter err) { StrBuilder output = new StrBuilder(); try { if (cmdAction == JobMgrAction.LIST) { output.append(createJobListing()); } else if (cmdAction == JobMgrAction.DELETE) { deleteJob(jobName); output.append("Job " + jobName + " was deleted."); } else { output.append(helpScreen()); } } catch (DatabaseException e) { output.append("Database Exception while trying to execute command: " + e.getMessage()); } catch (JobException e) { output.append("Job Exception while trying to execute command: " + e.getMessage()); } out.println(output.toString()); out.flush(); err.flush(); } private void deleteJob(String jobName) throws DatabaseException, JobException { boolean jobFound = false; List<ManagedJobSummary> jobsList = ArcMoverFactory.getInstance().getAllManagedJobs(); for (ManagedJobSummary job : jobsList) { if (getValue(job, JOB_NAME_LABEL).equals(jobName)) { ArcMoverFactory.getInstance().removeManagedJob(job.getJobId(), job.getJobType()); jobFound = true; break; } } if (!jobFound) { throw new JobException("Job was not deleted because job " + jobName + " was not found."); } } private String createJobListing() throws DatabaseException { StrBuilder sb = new StrBuilder(); List<ManagedJobSummary> jobsList = ArcMoverFactory.getInstance().getAllManagedJobs(); Map<String, Integer> columnWidths = calcColumnWidths(jobsList); for (Map.Entry<String, Integer> entry : columnWidths.entrySet()) { sb.appendFixedWidthPadRight(entry.getKey(), entry.getValue(), ' ').append(COL_SEP); } sb.append(NEWLINE); for (ManagedJobSummary job : jobsList) { sb.appendFixedWidthPadRight(getValue(job, JOB_NAME_LABEL), columnWidths.get(JOB_NAME_LABEL), ' ') .append(COL_SEP); sb.appendFixedWidthPadRight(getValue(job, JOB_TYPE_LABEL), columnWidths.get(JOB_TYPE_LABEL), ' ') .append(COL_SEP); sb.appendFixedWidthPadRight(getValue(job, JOB_STATE_LABEL), columnWidths.get(JOB_STATE_LABEL), ' ') .append(COL_SEP); sb.append(NEWLINE); } return sb.toString(); } private Map<String, Integer> calcColumnWidths(List<ManagedJobSummary> jobsList) { Map<String, Integer> columnWidths = new LinkedHashMap<String, Integer>(); columnWidths.put(JOB_NAME_LABEL, JOB_NAME_LABEL.length()); columnWidths.put(JOB_TYPE_LABEL, JOB_TYPE_LABEL.length()); columnWidths.put(JOB_STATE_LABEL, JOB_STATE_LABEL.length()); for (ManagedJobSummary job : jobsList) { columnWidths.put(JOB_NAME_LABEL, Math.max(columnWidths.get(JOB_NAME_LABEL), getValue(job, JOB_NAME_LABEL).length())); columnWidths.put(JOB_TYPE_LABEL, Math.max(columnWidths.get(JOB_TYPE_LABEL), getValue(job, JOB_TYPE_LABEL).length())); columnWidths.put(JOB_STATE_LABEL, Math.max(columnWidths.get(JOB_STATE_LABEL), getValue(job, JOB_STATE_LABEL).length())); } return columnWidths; } private String getValue(ManagedJobSummary job, String key) { if (JOB_NAME_LABEL.equals(key)) { return job.getJobName(); } else if (JOB_TYPE_LABEL.equals(key)) { return job.getJobType().getUiName(); } else if (JOB_STATE_LABEL.equals(key)) { return job.getJobStatus().toString(); } throw new IllegalArgumentException("Unsupported column index " + key); } }