use of org.dom4j.DocumentException in project zm-mailbox by Zimbra.
the class LocalConfigCLI method exec.
private void exec(String[] args) {
CommandLine cl = null;
CommandLineParser parser = new GnuParser();
try {
cl = parser.parse(mOptions, args);
} catch (ParseException pe) {
Logging.error("Failed to parse command line: " + pe);
System.exit(1);
}
if (cl.hasOption("q")) {
Logging.setQuietMode(true);
}
if (cl.hasOption("h")) {
usage();
}
// Load known keys from BackupLC if available
loadExtensionLC("com.zimbra.cs.backup.BackupLC");
// Load known keys from ZimbraOpenOfficeExt if available
loadExtensionLC("com.zimbra.openoffice.config.OpenOfficeLC");
// Load known keys from ZimbraVoice if available
loadExtensionLC("com.zimbra.cs.voice.VoiceLC");
// info/docs for supported keys
if (cl.hasOption("i")) {
checkCompatibleOptions("i", "q", cl);
LocalConfig.printDoc(System.out, cl.getArgs(), false);
return;
}
// info/docs for all keys (hidden option)
if (cl.hasOption("all")) {
checkCompatibleOptions("all", "q", cl);
LocalConfig.printDoc(System.out, cl.getArgs(), true);
return;
}
LocalConfig lc = null;
try {
lc = new LocalConfig(cl.getOptionValue("c"));
} catch (DocumentException de) {
error("failed when reading config file", de);
} catch (ConfigException ce) {
error("failed with error in config file", ce);
}
// edit
if (cl.hasOption("e")) {
checkNotRoot("-e");
checkCompatibleOptions("e", "qfrc", cl);
String[] av = cl.getArgs();
if (av == null || av.length == 0) {
error("insufficient arguments", null);
}
for (int i = 0; i < av.length; i++) {
String key = null;
String value = null;
if (cl.hasOption("r")) {
key = av[i];
value = RandomPassword.generate();
} else {
int eqidx = av[i].indexOf("=");
if (eqidx <= 0) {
// <= 0 also catches first char being =, ie no key specified
error("argument '" + av[i] + "' not in key=value form", null);
}
key = av[i].substring(0, eqidx);
value = av[i].substring(eqidx + 1, av[i].length());
}
if (KnownKey.needForceToEdit(key) && !cl.hasOption("f")) {
error("can not edit key " + key, null);
}
lc.set(key, value);
}
try {
lc.save();
} catch (Exception e) {
error("save to " + lc.getConfigFile() + " failed", e);
}
return;
}
// unset
if (cl.hasOption("u")) {
checkNotRoot("-u");
checkCompatibleOptions("u", "qfc", cl);
String[] av = cl.getArgs();
if (av == null || av.length == 0) {
error("insufficient arguments", null);
}
for (int i = 0; i < av.length; i++) {
String key = av[i];
if (!lc.isSet(key)) {
error("key " + key + " is not set", null);
}
lc.remove(key);
}
try {
lc.save();
} catch (Exception e) {
error("save to " + lc.getConfigFile() + " failed", e);
}
return;
}
// show path
if (cl.hasOption("p")) {
checkCompatibleOptions("p", "qc", cl);
System.out.println(lc.getConfigFile());
return;
}
if (cl.hasOption("l")) {
// reset logging and run native lib load
CliUtil.toolSetup("WARN");
try {
reload();
} catch (ServiceException e) {
if (e.getCause() instanceof ConnectException) {
error("'" + Provisioning.SERVICE_MAILBOX + "' service is not running", null);
} else {
error(e.getMessage(), e);
}
}
return;
}
// print values
String format = cl.getOptionValue("m");
ConfigWriter cwriter = null;
try {
cwriter = ConfigWriter.getInstance(format, cl.hasOption("x"), !cl.hasOption("s"));
} catch (ConfigException iae) {
error("failed to create writer " + format, iae);
}
try {
// changed
if (cl.hasOption("n")) {
checkCompatibleOptions("n", "qscmx", cl);
lc.printChanged(System.out, cwriter, cl.getArgs());
return;
}
// default
if (cl.hasOption("d")) {
checkCompatibleOptions("d", "qscmx", cl);
lc.printDefaults(System.out, cwriter, cl.getArgs());
return;
}
// current
checkCompatibleOptions("", "qscmx", cl);
lc.print(System.out, cwriter, cl.getArgs());
} catch (Exception e) {
error("exception occurred when printing", e);
}
}
use of org.dom4j.DocumentException in project cubrid-manager by CUBRID.
the class FormatXMLAction method run.
/**
* Format XML strings.
*/
public void run() {
//format editor.
try {
ByteArrayOutputStream sw = new ByteArrayOutputStream();
writeTo(sw, editor.getDocument().get(), "utf-8");
String string = new String(sw.toByteArray(), "utf-8");
editor.getDocument().set(string);
sw.close();
} catch (UnsupportedEncodingException e) {
showErrorMessage();
} catch (IOException e) {
showErrorMessage();
} catch (DocumentException e) {
showErrorMessage();
}
}
use of org.dom4j.DocumentException in project sic by belluccifranco.
the class AfipServiceImpl method getAfipWSAACredencial.
@Override
public AfipWSAACredencial getAfipWSAACredencial(String afipNombreServicio, Empresa empresa) {
AfipWSAACredencial afipCredencial = new AfipWSAACredencial();
String loginTicketResponse = "";
byte[] p12file = configuracionDelSistemaService.getConfiguracionDelSistemaPorEmpresa(empresa).getCertificadoAfip();
if (p12file.length == 0) {
throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_cds_certificado_vacio"));
}
String p12signer = configuracionDelSistemaService.getConfiguracionDelSistemaPorEmpresa(empresa).getFirmanteCertificadoAfip();
String p12pass = configuracionDelSistemaService.getConfiguracionDelSistemaPorEmpresa(empresa).getPasswordCertificadoAfip();
//siempre devuelve por 12hs
long ticketTime = 3600000L;
byte[] loginTicketRequest_xml_cms = afipWebServiceSOAPClient.crearCMS(p12file, p12pass, p12signer, afipNombreServicio, ticketTime);
LoginCms loginCms = new LoginCms();
loginCms.setIn0(Base64.getEncoder().encodeToString(loginTicketRequest_xml_cms));
try {
loginTicketResponse = afipWebServiceSOAPClient.loginCMS(loginCms);
} catch (WebServiceClientException ex) {
LOGGER.error(ex.getMessage());
throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_token_wsaa_error"));
}
try {
Reader tokenReader = new StringReader(loginTicketResponse);
Document tokenDoc = new SAXReader(false).read(tokenReader);
afipCredencial.setToken(tokenDoc.valueOf("/loginTicketResponse/credentials/token"));
afipCredencial.setSign(tokenDoc.valueOf("/loginTicketResponse/credentials/sign"));
afipCredencial.setCuit(empresa.getCuip());
} catch (DocumentException ex) {
LOGGER.error(ex.getMessage());
throw new BusinessServiceException(ResourceBundle.getBundle("Mensajes").getString("mensaje_error_procesando_xml"));
}
return afipCredencial;
}
use of org.dom4j.DocumentException in project hudson-2.x by hudson.
the class ManagedWindowsServiceLauncher method launch.
@Override
public void launch(final SlaveComputer computer, final TaskListener listener) throws IOException, InterruptedException {
try {
final PrintStream logger = listener.getLogger();
final String name = determineHost(computer);
logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingTo(name));
InetAddress host = InetAddress.getByName(name);
try {
Socket s = new Socket();
s.connect(new InetSocketAddress(host, 135), 5000);
s.close();
} catch (IOException e) {
logger.println("Failed to connect to port 135 of " + name + ". Is Windows firewall blocking this port? Or did you disable DCOM service?");
// again, let it continue.
}
JIDefaultAuthInfoImpl auth = createAuth();
JISession session = JISession.createSession(auth);
session.setGlobalSocketTimeout(60000);
SWbemServices services = WMI.connect(session, name);
String path = computer.getNode().getRemoteFS();
if (path.indexOf(':') == -1)
throw new IOException("Remote file system root path of the slave needs to be absolute: " + path);
SmbFile remoteRoot = new SmbFile("smb://" + name + "/" + path.replace('\\', '/').replace(':', '$') + "/", createSmbAuth());
if (!remoteRoot.exists())
remoteRoot.mkdirs();
try {
// does Java exist?
logger.println("Checking if Java exists");
WindowsRemoteProcessLauncher wrpl = new WindowsRemoteProcessLauncher(name, auth);
Process proc = wrpl.launch("java -fullversion", "c:\\");
proc.getOutputStream().close();
IOUtils.copy(proc.getInputStream(), logger);
proc.getInputStream().close();
int exitCode = proc.waitFor();
if (exitCode == 1) {
// we'll get this error code if Java is not found
//TODO enable me when JDK installer based on REST API will be ready
logger.println("No JDK found on slave node. Please install JDK");
throw new InterruptedException("No JDK found on slave node. Please install JDK");
// logger.println("No Java found. Downloading JDK");
// JDKInstaller jdki = new JDKInstaller("jdk-6u16-oth-JPR@CDS-CDS_Developer",true);
// URL jdk = jdki.locate(listener, Platform.WINDOWS, CPU.i386);
//
// listener.getLogger().println("Installing JDK");
// copyStreamAndClose(jdk.openStream(), new SmbFile(remoteRoot, "jdk.exe").getOutputStream());
//
// String javaDir = path + "\\jdk"; // this is where we install Java to
//
// WindowsRemoteFileSystem fs = new WindowsRemoteFileSystem(name, createSmbAuth());
// fs.mkdirs(javaDir);
//
// jdki.install(new WindowsRemoteLauncher(listener,wrpl), Platform.WINDOWS,
// fs, listener, javaDir ,path+"\\jdk.exe");
}
} catch (Exception e) {
e.printStackTrace(listener.error("Failed to prepare Java"));
}
String id = WindowsSlaveInstaller.generateServiceId(path);
Win32Service slaveService = services.getService(id);
if (slaveService == null) {
logger.println(Messages.ManagedWindowsServiceLauncher_InstallingSlaveService());
if (!DotNet.isInstalled(2, 0, name, auth)) {
// abort the launch
logger.println(Messages.ManagedWindowsServiceLauncher_DotNetRequired());
return;
}
// copy exe
logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveExe());
copyStreamAndClose(getClass().getResource("/windows-service/hudson.exe").openStream(), new SmbFile(remoteRoot, "hudson-slave.exe").getOutputStream());
copySlaveJar(logger, remoteRoot);
// copy hudson-slave.xml
logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveXml());
String xml = WindowsSlaveInstaller.generateSlaveXml(id, "javaw.exe", "-tcp %BASE%\\port.txt");
copyStreamAndClose(new ByteArrayInputStream(xml.getBytes("UTF-8")), new SmbFile(remoteRoot, "hudson-slave.xml").getOutputStream());
// install it as a service
logger.println(Messages.ManagedWindowsServiceLauncher_RegisteringService());
Document dom = new SAXReader().read(new StringReader(xml));
Win32Service svc = services.Get("Win32_Service").cast(Win32Service.class);
int r = svc.Create(id, dom.selectSingleNode("/service/name").getText() + " at " + path, path + "\\hudson-slave.exe", Win32OwnProcess, 0, "Manual", true);
if (r != 0) {
listener.error("Failed to create a service: " + svc.getErrorMessage(r));
return;
}
slaveService = services.getService(id);
} else {
copySlaveJar(logger, remoteRoot);
}
logger.println(Messages.ManagedWindowsServiceLauncher_StartingService());
slaveService.start();
// wait until we see the port.txt, but don't do so forever
logger.println(Messages.ManagedWindowsServiceLauncher_WaitingForService());
SmbFile portFile = new SmbFile(remoteRoot, "port.txt");
for (int i = 0; !portFile.exists(); i++) {
if (i >= 30) {
listener.error(Messages.ManagedWindowsServiceLauncher_ServiceDidntRespond());
return;
}
Thread.sleep(1000);
}
int p = readSmbFile(portFile);
// connect
logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingToPort(p));
final Socket s = new Socket(name, p);
// ready
computer.setChannel(new BufferedInputStream(new SocketInputStream(s)), new BufferedOutputStream(new SocketOutputStream(s)), listener.getLogger(), new Listener() {
@Override
public void onClosed(Channel channel, IOException cause) {
afterDisconnect(computer, listener);
}
});
} catch (SmbException e) {
e.printStackTrace(listener.error(e.getMessage()));
} catch (JIException e) {
if (e.getErrorCode() == 5)
// access denied error
e.printStackTrace(listener.error(Messages.ManagedWindowsServiceLauncher_AccessDenied()));
else
e.printStackTrace(listener.error(e.getMessage()));
} catch (DocumentException e) {
e.printStackTrace(listener.error(e.getMessage()));
}
}
use of org.dom4j.DocumentException in project Openfire by igniterealtime.
the class ServerDialback method sendVerifyKey.
private VerifyResult sendVerifyKey(String key, StreamID streamID, String recipient, String remoteDomain, Writer writer, XMPPPacketReader reader, Socket socket, boolean skipTLS) throws IOException, XmlPullParserException, RemoteConnectionFailedException {
final Logger log = LoggerFactory.getLogger(Log.getName() + "[Acting as Receiving Server: Verify key with AS: " + remoteDomain + " for OS: " + recipient + " (id " + streamID + ")]");
VerifyResult result = VerifyResult.error;
TLSStreamHandler tlsStreamHandler;
log.debug("Send the Authoritative Server a stream header and wait for answer.");
StringBuilder stream = new StringBuilder();
stream.append("<stream:stream");
stream.append(" xmlns:stream=\"http://etherx.jabber.org/streams\"");
stream.append(" xmlns=\"jabber:server\"");
stream.append(" xmlns:db=\"jabber:server:dialback\"");
stream.append(" to=\"");
stream.append(remoteDomain);
stream.append("\"");
stream.append(" from=\"");
stream.append(recipient);
stream.append("\"");
stream.append(" version=\"1.0\">");
writer.write(stream.toString());
writer.flush();
// Get the answer from the Authoritative Server
XmlPullParser xpp = reader.getXPPParser();
for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG; ) {
eventType = xpp.next();
}
// TODO there's code duplication here with LocalOutgoingServerSession.
log.debug("Got a response.");
if ((xpp.getAttributeValue("", "version") != null) && (xpp.getAttributeValue("", "version").equals("1.0"))) {
log.debug("The remote server is XMPP 1.0 compliant (or at least reports to be).");
Document doc;
try {
doc = reader.parseDocument();
} catch (DocumentException e) {
log.warn("Unable to verify key: XML Error!", e);
return VerifyResult.error;
}
Element features = doc.getRootElement();
Element starttls = features.element("starttls");
if (!skipTLS && starttls != null) {
writer.write("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>");
writer.flush();
try {
doc = reader.parseDocument();
} catch (DocumentException e) {
log.warn("Unable to verify key: XML Error!", e);
return VerifyResult.error;
}
if (!doc.getRootElement().getName().equals("proceed")) {
log.warn("Unable to verify key: Got {} instead of proceed for starttls", doc.getRootElement().getName());
log.debug("Like this: {}", doc.asXML());
return VerifyResult.error;
}
log.debug("Negotiating TLS with AS... ");
// Ugly hacks, apparently, copied from SocketConnection.
final ConnectionManagerImpl connectionManager = ((ConnectionManagerImpl) XMPPServer.getInstance().getConnectionManager());
tlsStreamHandler = new TLSStreamHandler(socket, connectionManager.getListener(ConnectionType.SOCKET_S2S, false).generateConnectionConfiguration(), true);
// Start handshake
tlsStreamHandler.start();
// Use new wrapped writers
writer = new BufferedWriter(new OutputStreamWriter(tlsStreamHandler.getOutputStream(), StandardCharsets.UTF_8));
reader.getXPPParser().setInput(new InputStreamReader(tlsStreamHandler.getInputStream(), StandardCharsets.UTF_8));
log.debug("Successfully negotiated TLS with AS... ");
/// Recurses!
return sendVerifyKey(key, streamID, recipient, remoteDomain, writer, reader, socket, skipTLS);
}
}
if ("jabber:server:dialback".equals(xpp.getNamespace("db"))) {
log.debug("Request for verification of the key and wait for response");
StringBuilder sb = new StringBuilder();
sb.append("<db:verify");
sb.append(" from=\"").append(recipient).append("\"");
sb.append(" to=\"").append(remoteDomain).append("\"");
sb.append(" id=\"").append(streamID.getID()).append("\">");
sb.append(key);
sb.append("</db:verify>");
writer.write(sb.toString());
writer.flush();
try {
Element doc = reader.parseDocument().getRootElement();
if ("db".equals(doc.getNamespacePrefix()) && "verify".equals(doc.getName())) {
if (doc.attributeValue("id") == null || !streamID.equals(BasicStreamIDFactory.createStreamID(doc.attributeValue("id")))) {
// Include the invalid-id stream error condition in the response
writer.write(new StreamError(StreamError.Condition.invalid_id).toXML());
writer.flush();
// condition is sent to the Originating Server
throw new RemoteConnectionFailedException("Invalid ID");
} else if (isHostUnknown(doc.attributeValue("to"))) {
// Include the host-unknown stream error condition in the response
writer.write(new StreamError(StreamError.Condition.host_unknown).toXML());
writer.flush();
// condition is sent to the Originating Server
throw new RemoteConnectionFailedException("Host unknown");
} else if (!remoteDomain.equals(doc.attributeValue("from"))) {
// Include the invalid-from stream error condition in the response
writer.write(new StreamError(StreamError.Condition.invalid_from).toXML());
writer.flush();
// condition is sent to the Originating Server
throw new RemoteConnectionFailedException("Invalid From");
} else if ("valid".equals(doc.attributeValue("type"))) {
log.debug("Key was VERIFIED by the Authoritative Server.");
result = VerifyResult.valid;
} else if ("invalid".equals(doc.attributeValue("type"))) {
log.debug("Key was NOT VERIFIED by the Authoritative Server.");
result = VerifyResult.invalid;
} else {
log.debug("Key was ERRORED by the Authoritative Server.");
result = VerifyResult.error;
}
} else {
log.debug("db:verify answer was: " + doc.asXML());
}
} catch (DocumentException | RuntimeException e) {
log.error("An error occurred while connecting to the Authoritative Server:", e);
// sent to the Originating Server
throw new RemoteConnectionFailedException("Error connecting to the Authoritative Server");
}
} else {
// Include the invalid-namespace stream error condition in the response
writer.write(new StreamError(StreamError.Condition.invalid_namespace).toXML());
writer.flush();
// sent to the Originating Server
throw new RemoteConnectionFailedException("Invalid namespace");
}
return result;
}
Aggregations