Skip to content

Commit

Permalink
NullPointer fixes. better hostname handling. Toggle streamColor. (#27)
Browse files Browse the repository at this point in the history
* ignore .DS_Store file

* [JENKINS-38148] Handle some null pointers.

Cannot prevent bad DNS/Hostname config.

* [JENKINS-38201] Partial fix

cannot prevent bad DNS/Hostname.

* [JENKINS-33103, JENKINS-38148] added toggle for color reset.

* [JENKINS-38201] Better error message
  • Loading branch information
Casz committed Sep 15, 2016
1 parent ceb22c4 commit 54cb799
Show file tree
Hide file tree
Showing 11 changed files with 87 additions and 56 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -7,3 +7,4 @@ work
.settings
.idea
*.iml
.DS_Store
6 changes: 3 additions & 3 deletions src/main/java/hudson/plugins/accurev/AccurevLauncher.java
Expand Up @@ -143,6 +143,7 @@ listenerToLogFailuresTo, loggerToLogFailuresTo, new ParseOutputToStream(),
synchronizationLockObjectOrNull, environmentVariables, directoryToRunCommandFrom,
listenerToLogFailuresTo, loggerToLogFailuresTo, new ParseIgnoreOutput(), null);
}
if (result == null) return false;
return result;
}

Expand Down Expand Up @@ -270,8 +271,7 @@ public static <TResult, TContext> TResult runCommand(//
commandExitCode, outputFromCommand, errorFromCommand, loggerToLogFailuresTo, listenerToLogFailuresTo);
return null;
}
final TResult parsedResult = commandOutputParser.parse(outputFromCommand, commandOutputParserContext);
return parsedResult;
return commandOutputParser.parse(outputFromCommand, commandOutputParserContext);
} catch (Exception ex) {
logCommandException(machineReadableCommand, directoryToRunCommandFrom, humanReadableCommandName, ex,
loggerToLogFailuresTo, listenerToLogFailuresTo);
Expand Down Expand Up @@ -433,7 +433,7 @@ private static String getRemoteHostname(final FilePath directoryToRunCommandFrom
final String hostName = act.getHostName();
return hostName;
} catch (UnknownHostException e) {
return e.toString();
return "Unable to determine actual hostname, ensure proper FQDN.\n"+e.toString();
} catch (IOException e) {
return e.toString();
} catch (InterruptedException e) {
Expand Down
12 changes: 10 additions & 2 deletions src/main/java/hudson/plugins/accurev/AccurevSCM.java
Expand Up @@ -303,7 +303,6 @@ public SCMDescriptor<?> getDescriptor() {
* <li>ACCUREV_SERVER - The server name</li>
* <li>ACCUREV_REFTREE - The workspace name</li>
* <li>ACCUREV_SUBPATH - The workspace subpath</li>
*
* </ul>
*
* @param build build
Expand Down Expand Up @@ -738,6 +737,7 @@ public static final class AccurevServer implements Serializable {
private boolean minimiseLogins;
private boolean useNonexpiringLogin;
private boolean useRestrictedShowStreams;
private boolean useColor;
private static final long serialVersionUID = 3270850408409304611L;

/**
Expand Down Expand Up @@ -787,7 +787,8 @@ public AccurevServer(//
boolean syncOperations, //
boolean minimiseLogins, //
boolean useNonexpiringLogin, //
boolean useRestrictedShowStreams) {
boolean useRestrictedShowStreams,
boolean useColor) {
this();
this.name = name;
this.host = host;
Expand All @@ -799,6 +800,7 @@ public AccurevServer(//
this.minimiseLogins = minimiseLogins;
this.useNonexpiringLogin = useNonexpiringLogin;
this.useRestrictedShowStreams = useRestrictedShowStreams;
this.useColor = useColor;
}

/**
Expand Down Expand Up @@ -933,6 +935,12 @@ public void setUseRestrictedShowStreams(boolean useRestrictedShowStreams) {
this.useRestrictedShowStreams = useRestrictedShowStreams;
}

public boolean isUseColor() { return useColor; }

public void setUseColor(boolean useColor) {
this.useColor = useColor;
}

public FormValidation doValidTransactionTypesCheck(@QueryParameter String value)//
throws IOException, ServletException {
final String[] formValidTypes = value.split(VTT_DELIM);
Expand Down
Expand Up @@ -28,8 +28,14 @@ public RemoteWorkspaceDetails call() throws UnknownHostException {
} catch (IOException e) {
path = f.getAbsolutePath();
}

return new RemoteWorkspaceDetails(addr.getCanonicalHostName(), path, File.separator);
String ipPattern = "^(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\\.){3}([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$";
String hostName = addr.getCanonicalHostName(); // try full hostname
if (hostName.matches(ipPattern))
hostName = addr.getHostName(); // try hostname
// Accurev does not accept IP addresses so we are going to throw an error.
if (hostName.matches(ipPattern))
throw new UnknownHostException("Found IP, but need HostName, ensure proper FQDN.");
return new RemoteWorkspaceDetails(hostName, path, File.separator);
}

@Override
Expand Down
48 changes: 24 additions & 24 deletions src/main/java/hudson/plugins/accurev/cmd/ChangeLogCmd.java
Expand Up @@ -74,23 +74,23 @@ public static boolean captureChangelog(AccurevServer server,
final String commandDescription = "Changelog command";
final Boolean success = AccurevLauncher.runCommand(commandDescription, launcher, cmd, null, scm.getOptionalLock(),
accurevEnv, workspace, listener, logger, new ParseOutputToFile(), changelogFile);
if (!success) {
if (success == null || !success) {
return false;
}
//==============================================================================================
//See the content of changelogfile

if ( changelogFile != null ) {
applyWebURL( server, accurevEnv, workspace, listener, accurevPath, launcher, changelogFile, logger, scm );
}
applyWebURL( server, accurevEnv, workspace, listener, accurevPath, launcher, changelogFile, logger, scm );
}
//=============================================================================================
listener.getLogger().println("Changelog calculated successfully.");
return true;
}

/**
* Parse the settings.xml file to get the webui url and apply it to the changelog.
*
*
* @param server Server
* @param accurevEnv Accurev Enviroment
* @param workspace Workspace
Expand All @@ -101,26 +101,26 @@ public static boolean captureChangelog(AccurevServer server,
* @param logger logger
* @param scm Accurev SCM
*/
private static void applyWebURL(AccurevServer server,
Map<String, String> accurevEnv,
FilePath workspace,
TaskListener listener,
String accurevPath,
Launcher launcher,
File changelogFile,
Logger logger,
private static void applyWebURL(AccurevServer server,
Map<String, String> accurevEnv,
FilePath workspace,
TaskListener listener,
String accurevPath,
Launcher launcher,
File changelogFile,
Logger logger,
AccurevSCM scm) {

final ArgumentListBuilder getConfigcmd = new ArgumentListBuilder();
getConfigcmd.add(accurevPath);
getConfigcmd.add("getconfig");
Command.addServer(getConfigcmd, server);
getConfigcmd.add("-s");
getConfigcmd.add("-s");
getConfigcmd.add("-r");
getConfigcmd.add("settings.xml");
GetConfigWebURL webuiURL;
Map<String, GetConfigWebURL> webURL = null;

try {
webURL = AccurevLauncher.runCommand("Get config to fetch webURL",
launcher, getConfigcmd, null, scm.getOptionalLock(), accurevEnv, workspace, listener, logger,
Expand All @@ -129,43 +129,43 @@ private static void applyWebURL(AccurevServer server,
logger.warning("Error loading settings.xml");
// Error getting settings.xml file.
}

if( webURL == null || webURL.isEmpty() ) {
return;
}

webuiURL = webURL.get("webuiURL");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder;
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(changelogFile);

NodeList nodes = document.getElementsByTagName("transaction");

Element depotElement = document.createElement("depot");
if(nodes!=null && nodes.getLength()>0)
nodes.item(0).getParentNode().insertBefore(depotElement, nodes.item(0));

depotElement.appendChild(document.createTextNode(scm.getDepot()));

Element webuiElement = document.createElement("webuiURL");
if(nodes!=null && nodes.getLength()>0)
nodes.item(0).getParentNode().insertBefore(webuiElement, nodes.item(0));

if(webuiURL!=null)
webuiElement.appendChild(document.createTextNode((webuiURL.getWebURL().endsWith("/")?(webuiURL.getWebURL().substring(0, webuiURL.getWebURL().length()-1)):(webuiURL.getWebURL()))));
else
webuiElement.appendChild(document.createTextNode(""));
webuiElement.appendChild(document.createTextNode(""));

DOMSource source = new DOMSource(document);

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult(changelogFile);
transformer.transform(source, result);
} catch (ParserConfigurationException | IOException | SAXException | TransformerException e) {

}
}
}
36 changes: 18 additions & 18 deletions src/main/java/hudson/plugins/accurev/cmd/PopulateCmd.java
Expand Up @@ -17,19 +17,19 @@
import hudson.plugins.accurev.parsers.output.ParsePopulate;
public class PopulateCmd extends Command {


private static final Logger logger = Logger.getLogger(PopulateCmd.class.getName());

private Date _startDateOfPopulate;

/**
*
*
* @return Date
*/
public Date get_startDateOfPopulate() {
return (Date) _startDateOfPopulate.clone();
}

/**
* @param launcher launcher
* @param listener listener
Expand All @@ -43,28 +43,28 @@ public Date get_startDateOfPopulate() {
* @param overwrite overwrite
* @return boolean
*/
public boolean populate(AccurevSCM scm, Launcher launcher, TaskListener listener,
AccurevServer server, String accurevClientExePath,
String streamName,
boolean overwrite,
public boolean populate(AccurevSCM scm, Launcher launcher, TaskListener listener,
AccurevServer server, String accurevClientExePath,
String streamName,
boolean overwrite,
String fromMessage,
FilePath accurevWorkingSpace, Map<String, String> accurevEnv) {
listener.getLogger().println("Populating " + fromMessage + "...");
final ArgumentListBuilder popcmd = new ArgumentListBuilder();
popcmd.add(accurevClientExePath);
popcmd.add("pop");
addServer(popcmd, server);

if ( streamName != null ) {
popcmd.add("-v");
popcmd.add(streamName);
}

popcmd.add("-L");
popcmd.add(accurevWorkingSpace.getRemote());

if ( overwrite ) popcmd.add("-O");

popcmd.add("-R");
if ((scm.getSubPath() == null) || (scm.getSubPath().trim().length() == 0)) {
popcmd.add(".");
Expand All @@ -75,12 +75,12 @@ public boolean populate(AccurevSCM scm, Launcher launcher, TaskListener listener
}
}
_startDateOfPopulate = new Date();
if (!AccurevLauncher.runCommand("Populate " + fromMessage + " command", launcher, popcmd, null, scm.getOptionalLock(), accurevEnv,
accurevWorkingSpace, listener, logger, new ParsePopulate(), listener.getLogger())) {
return false;
}
final Boolean success = AccurevLauncher.runCommand("Populate " + fromMessage + " command", launcher, popcmd, null, scm.getOptionalLock(), accurevEnv,
accurevWorkingSpace, listener, logger, new ParsePopulate(), listener.getLogger());
if (success == null || !success) {
return false;
}
listener.getLogger().println("Populate completed successfully.");
return true;
}
}

11 changes: 7 additions & 4 deletions src/main/java/hudson/plugins/accurev/cmd/Update.java
Expand Up @@ -62,9 +62,9 @@ public static Boolean hasChanges(AccurevSCM scm, //

List<String> files = new ArrayList<>();
final ArgumentListBuilder cmd = createCommand(server, accurevPath, true, reftree, false);
boolean transactionFound = AccurevLauncher.runCommand("Update command", launcher, cmd, null, scm.getOptionalLock(), accurevEnv, workspace, listener,
Boolean transactionFound = AccurevLauncher.runCommand("Update command", launcher, cmd, null, scm.getOptionalLock(), accurevEnv, workspace, listener,
logger, XmlParserFactory.getFactory(), new ParseUpdate(), files);
if (transactionFound) {
if (transactionFound != null && transactionFound) {
String filterForPollSCM = scm.getFilterForPollSCM();
String subPath = scm.getSubPath();
Collection<String> filterPaths = null;
Expand Down Expand Up @@ -94,6 +94,8 @@ public static Boolean hasChanges(AccurevSCM scm, //
}
}
}
} else {
return false;
}
return transactionFound;
}
Expand All @@ -108,10 +110,11 @@ public static boolean performUpdate(final AccurevSCM scm, //
final String reftree,
File changelogFile) throws IOException, InterruptedException {
final ArgumentListBuilder cmd = createCommand(server, accurevPath, false, reftree, false);
boolean success = AccurevLauncher.runCommand("Update command", launcher,
final Boolean result = AccurevLauncher.runCommand("Update command", launcher,
cmd, null, scm.getOptionalLock(), accurevEnv, workspace, listener,
logger, new ParseOutputToFile(), changelogFile);
if (result == null) return false;
return result;

return success;
}
}
Expand Up @@ -188,7 +188,10 @@ public boolean checkout(Run<?, ?> build, Launcher launcher, FilePath jenkinsWork
return false;
}

setStreamColor();
//Disable for now until toggle is available. Also do not fail if admin privileges is not provided.
if (server.isUseColor()) {
setStreamColor();
}

if (!checkout(build, changelogFile)) {
return false;
Expand Down
Expand Up @@ -25,10 +25,10 @@ public Boolean parse(XmlPullParser parser, List<AccurevTransaction> context) thr
resultTransaction.setDate(ParseChangeLog.convertAccurevTimestamp(parser.getAttributeValue("",
"time")));
resultTransaction.setUser(parser.getAttributeValue("", "user"));
} else if (parser.getName().equalsIgnoreCase("comment")) {
} else if (parser.getName().equalsIgnoreCase("comment") && resultTransaction != null) {
// parse comments
resultTransaction.setMsg(parser.nextText());
}else if (parser.getName().equalsIgnoreCase("version")) {
}else if (parser.getName().equalsIgnoreCase("version") && resultTransaction != null) {
// parse path & convert it to standard format
String path = parser.getAttributeValue("", "path");
if (path != null) {
Expand Down
Expand Up @@ -38,6 +38,9 @@
<f:entry title="Show one stream at a time" help="/plugin/accurev/help/use-restricted-show-streams.html">
<f:checkbox name="server.useRestrictedShowStreams" checked="${server.useRestrictedShowStreams}" default="false" />
</f:entry>
<f:entry title="Enable reset Color" help="/plugin/accurev/help/use-color.html">
<f:checkbox name="server.useColor" checked="${server.useColor}" default="false" />
</f:entry>
</f:advanced>
</table>
<div align="right">
Expand Down
7 changes: 7 additions & 0 deletions src/main/webapp/help/use-color.html
@@ -0,0 +1,7 @@
<div>
<p>
If checked, plugin will reset the color on stream when build is starting.
<br /><br />
This can be used by custom post step to color the build according to build result (red, green, yellow...).
</p>
</div>

0 comments on commit 54cb799

Please sign in to comment.