use of com.helger.web.fileupload.IFileItem in project peppol-practical by phax.
the class PagePublicToolsSMPSML method _registerSMPtoSML.
private void _registerSMPtoSML(@Nonnull final WebPageExecutionContext aWPEC, @Nonnull final FormErrorList aFormErrors) {
final HCNodeList aNodeList = aWPEC.getNodeList();
final Locale aDisplayLocale = aWPEC.getDisplayLocale();
final ISMLConfigurationManager aSMLConfigurationMgr = PPMetaManager.getSMLConfigurationMgr();
final String sSMLID = aWPEC.params().getAsString(FIELD_SML_ID);
final ISMLConfiguration aSMLInfo = aSMLConfigurationMgr.getSMLInfoOfID(sSMLID);
final String sSMPID = aWPEC.params().getAsString(FIELD_SMP_ID);
final String sPhysicalAddress = aWPEC.params().getAsString(FIELD_PHYSICAL_ADDRESS);
final String sLogicalAddress = aWPEC.params().getAsString(FIELD_LOGICAL_ADDRESS);
final IFileItem aKeyStoreFile = aWPEC.params().getAsFileItem(FIELD_KEYSTORE);
final String sKeyStorePassword = aWPEC.params().getAsString(FIELD_KEYSTORE_PW);
final boolean bIsPeppol = aSMLInfo != null && aSMLInfo.getSMPAPIType() == ESMPAPIType.PEPPOL;
if (aSMLInfo == null)
aFormErrors.addFieldError(FIELD_SML_ID, "A valid SML must be selected!");
if (StringHelper.hasNoText(sSMPID))
aFormErrors.addFieldError(FIELD_SMP_ID, "A non-empty SMP ID must be provided!");
else if (!RegExHelper.stringMatchesPattern(CPPApp.PATTERN_SMP_ID, sSMPID))
aFormErrors.addFieldError(FIELD_SMP_ID, "The provided SMP ID contains invalid characters. It must match the following regular expression: " + CPPApp.PATTERN_SMP_ID);
if (StringHelper.hasNoText(sPhysicalAddress))
aFormErrors.addFieldError(FIELD_PHYSICAL_ADDRESS, "A physical address must be provided!");
else if (!RegExHelper.stringMatchesPattern(IPV4Addr.PATTERN_IPV4, sPhysicalAddress))
aFormErrors.addFieldError(FIELD_PHYSICAL_ADDRESS, "The provided physical address does not seem to be an IPv4 address!");
else {
final String[] aParts = StringHelper.getExplodedArray('.', sPhysicalAddress, 4);
final byte[] aBytes = new byte[] { (byte) StringParser.parseInt(aParts[0], -1), (byte) StringParser.parseInt(aParts[1], -1), (byte) StringParser.parseInt(aParts[2], -1), (byte) StringParser.parseInt(aParts[3], -1) };
try {
InetAddress.getByAddress(aBytes);
} catch (final UnknownHostException ex) {
final String sMsg = "The provided IP address does not resolve to a valid host. ";
aFormErrors.addFieldError(FIELD_PHYSICAL_ADDRESS, sMsg + AppCommonUI.getTechnicalDetailsString(ex, false));
}
}
if (StringHelper.hasNoText(sLogicalAddress))
aFormErrors.addFieldError(FIELD_LOGICAL_ADDRESS, "A logical address must be provided in the form 'http://smp.example.org'!");
else {
final URL aURL = URLHelper.getAsURL(sLogicalAddress);
if (aURL == null)
aFormErrors.addFieldError(FIELD_LOGICAL_ADDRESS, "The provided logical address seems not be a URL! Please use the form 'http://smp.example.org'");
else {
if (bIsPeppol) {
if (!"http".equals(aURL.getProtocol()) && !"https".equals(aURL.getProtocol()))
aFormErrors.addFieldError(FIELD_LOGICAL_ADDRESS, "The provided logical address must use the 'http' protocol and may not use the '" + aURL.getProtocol() + "' protocol. According to the Peppol SMP specification, no other protocols than 'http' are allowed!");
// -1 means default port
if (aURL.getPort() != 80 && aURL.getPort() != -1)
aFormErrors.addFieldError(FIELD_LOGICAL_ADDRESS, "The provided logical address must use the default http port 80 and not port " + aURL.getPort() + ". According to the Peppol SMP specification, no other ports are allowed!");
if (StringHelper.hasText(aURL.getPath()) && !"/".equals(aURL.getPath()))
aFormErrors.addFieldError(FIELD_LOGICAL_ADDRESS, "The provided logical address may not contain a path (" + aURL.getPath() + ") because according to the Peppol SMP specifications it must run in the root (/) path!");
}
}
}
final SSLSocketFactory aSocketFactory = _loadKeyStoreAndCreateSSLSocketFactory(EKeyStoreType.JKS, SECURITY_PROVIDER, aKeyStoreFile, sKeyStorePassword, aFormErrors, aDisplayLocale);
if (aFormErrors.isEmpty()) {
try {
final ManageServiceMetadataServiceCaller aCaller = _create(aSMLInfo.getSMLInfo(), aSocketFactory);
aCaller.create(sSMPID, sPhysicalAddress, sLogicalAddress);
final String sMsg = "Successfully registered SMP '" + sSMPID + "' with physical address '" + sPhysicalAddress + "' and logical address '" + sLogicalAddress + "' to the SML '" + aSMLInfo.getManagementServiceURL() + "'.";
LOGGER.info(sMsg);
aNodeList.addChild(success(sMsg));
AuditHelper.onAuditExecuteSuccess("smp-sml-create", sSMPID, sPhysicalAddress, sLogicalAddress, aSMLInfo.getManagementServiceURL());
} catch (final Exception ex) {
final String sMsg = "Error registering SMP '" + sSMPID + "' with physical address '" + sPhysicalAddress + "' and logical address '" + sLogicalAddress + "' to the SML '" + aSMLInfo.getManagementServiceURL() + "'.";
aNodeList.addChild(error(sMsg).addChild(AppCommonUI.getTechnicalDetailsUI(ex, true)));
AuditHelper.onAuditExecuteFailure("smp-sml-create", sSMPID, sPhysicalAddress, sLogicalAddress, aSMLInfo.getManagementServiceURL(), ex.getClass(), ex.getMessage());
}
} else
aNodeList.addChild(BootstrapWebPageUIHandler.INSTANCE.createIncorrectInputBox(aWPEC));
}
use of com.helger.web.fileupload.IFileItem in project peppol-practical by phax.
the class PagePublicToolsSMPSML method _updateSMPCertAtSML.
private void _updateSMPCertAtSML(@Nonnull final WebPageExecutionContext aWPEC, @Nonnull final FormErrorList aFormErrors) {
final HCNodeList aNodeList = aWPEC.getNodeList();
final Locale aDisplayLocale = aWPEC.getDisplayLocale();
final ISMLConfigurationManager aSMLConfigurationMgr = PPMetaManager.getSMLConfigurationMgr();
final LocalDate aNow = PDTFactory.getCurrentLocalDate();
final String sSMLID = aWPEC.params().getAsString(FIELD_SML_ID);
final ISMLConfiguration aSML = aSMLConfigurationMgr.getSMLInfoOfID(sSMLID);
final IFileItem aKeyStoreFile = aWPEC.params().getAsFileItem(FIELD_KEYSTORE);
final String sKeyStorePassword = aWPEC.params().getAsString(FIELD_KEYSTORE_PW);
final String sMigrationDate = aWPEC.params().getAsString(FIELD_PM_MIGRATION_DATE);
final LocalDate aMigrationDate = PDTFromString.getLocalDateFromString(sMigrationDate, aDisplayLocale);
final String sMigrationPublicCert = aWPEC.params().getAsStringTrimmed(FIELD_PM_PUBLIC_CERT);
X509Certificate aMigrationPublicCert = null;
if (aSML == null)
aFormErrors.addFieldError(FIELD_SML_ID, "A valid SML must be selected!");
if (StringHelper.hasText(sMigrationDate)) {
if (aMigrationDate == null)
aFormErrors.addFieldError(FIELD_PM_MIGRATION_DATE, "The provided certificate migration date '" + sMigrationDate + "' is invalid!");
else if (aMigrationDate.compareTo(aNow) <= 0)
aFormErrors.addFieldError(FIELD_PM_MIGRATION_DATE, "The certificate migration date must be in the future!");
}
if (StringHelper.hasNoText(sMigrationPublicCert)) {
aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "A new public certificate must be provided.");
} else {
try {
aMigrationPublicCert = CertificateHelper.convertStringToCertficate(sMigrationPublicCert);
} catch (final Exception ex) {
// Fall through
}
if (aMigrationPublicCert == null)
aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "The provided public certificate cannot be parsed as a X.509 certificate.");
else {
try {
aMigrationPublicCert.checkValidity();
} catch (final CertificateExpiredException ex) {
aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "The provided public certificate is already expired!");
aMigrationPublicCert = null;
} catch (final CertificateNotYetValidException ex) {
// That's okay
}
if (!sMigrationPublicCert.startsWith(CertificateHelper.BEGIN_CERTIFICATE))
aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "The provided value must start with '" + CertificateHelper.BEGIN_CERTIFICATE + "' (without the quotes)");
if (!sMigrationPublicCert.endsWith(CertificateHelper.END_CERTIFICATE))
aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "The provided value must end with '" + CertificateHelper.END_CERTIFICATE + "' (without the quotes)");
}
}
if (aMigrationPublicCert != null) {
final LocalDate aNotBefore = PDTFactory.createLocalDate(aMigrationPublicCert.getNotBefore());
final LocalDate aNotAfter = PDTFactory.createLocalDate(aMigrationPublicCert.getNotAfter());
if (aMigrationDate != null) {
if (aMigrationDate.isBefore(aNotBefore))
aFormErrors.addFieldError(FIELD_PM_MIGRATION_DATE, "The provided certificate migration date " + PDTToString.getAsString(aMigrationDate, aDisplayLocale) + " must not be before the certificate NotBefore date " + PDTToString.getAsString(aNotBefore, aDisplayLocale) + "!");
if (aMigrationDate.isAfter(aNotAfter))
aFormErrors.addFieldError(FIELD_PM_MIGRATION_DATE, "The provided certificate migration date " + PDTToString.getAsString(aMigrationDate, aDisplayLocale) + " must not be after the certificate NotAfter date " + PDTToString.getAsString(aNotAfter, aDisplayLocale) + "!");
} else {
if (aNotBefore.compareTo(aNow) <= 0)
aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "The effective certificate migration date (" + PDTToString.getAsString(aNotBefore, aDisplayLocale) + " - taken from the new public certificate) must be in the future!");
}
}
final SSLSocketFactory aSocketFactory = _loadKeyStoreAndCreateSSLSocketFactory(EKeyStoreType.JKS, SECURITY_PROVIDER, aKeyStoreFile, sKeyStorePassword, aFormErrors, aDisplayLocale);
if (aFormErrors.isEmpty()) {
final BDMSLClient aCaller = new BDMSLClient(aSML.getSMLInfo());
aCaller.setSSLSocketFactory(aSocketFactory);
try {
aCaller.prepareChangeCertificate(sMigrationPublicCert, aMigrationDate);
final LocalDateTime aNotBefore = PDTFactory.createLocalDateTime(aMigrationPublicCert.getNotBefore());
final LocalDateTime aNotAfter = PDTFactory.createLocalDateTime(aMigrationPublicCert.getNotAfter());
final LocalDate aEffectiveMigrationDate = aMigrationDate != null ? aMigrationDate : aNotBefore.toLocalDate();
final String sMsg = "Successfully prepared migration of SMP certificate at SML '" + aSML.getManagementServiceURL() + "'" + " to be exchanged at " + PDTToString.getAsString(aEffectiveMigrationDate, aDisplayLocale) + ".";
LOGGER.info(sMsg);
aNodeList.addChild(success().addChildren(div(sMsg), div("Issuer: " + aMigrationPublicCert.getIssuerX500Principal().getName()), div("Subject: " + aMigrationPublicCert.getSubjectX500Principal().getName()), div("Not before: " + PDTToString.getAsString(aNotBefore, aDisplayLocale)), div("Not after: " + PDTToString.getAsString(aNotAfter, aDisplayLocale))));
AuditHelper.onAuditExecuteSuccess("smp-sml-update-cert", aSML.getManagementServiceURL(), sMigrationPublicCert, aMigrationDate);
} catch (final com.helger.peppol.smlclient.bdmsl.BadRequestFault | com.helger.peppol.smlclient.bdmsl.InternalErrorFault | com.helger.peppol.smlclient.bdmsl.NotFoundFault | com.helger.peppol.smlclient.bdmsl.UnauthorizedFault | ClientTransportException ex) {
final String sMsg = "Error preparing migration of SMP certificate at SML '" + aSML.getManagementServiceURL() + "'.";
aNodeList.addChild(error(sMsg).addChild(AppCommonUI.getTechnicalDetailsUI(ex, true)));
AuditHelper.onAuditExecuteFailure("smp-sml-update-cert", aSML.getManagementServiceURL(), sMigrationPublicCert, aMigrationDate, ex.getClass(), ex.getMessage());
}
} else
aNodeList.addChild(BootstrapWebPageUIHandler.INSTANCE.createIncorrectInputBox(aWPEC));
}
use of com.helger.web.fileupload.IFileItem in project phoss-directory by phax.
the class PageSecureIndexImport method fillContent.
@Override
protected void fillContent(final WebPageExecutionContext aWPEC) {
final HCNodeList aNodeList = aWPEC.getNodeList();
final Locale aDisplayLocale = aWPEC.getDisplayLocale();
final IIdentifierFactory aIdentifierFactory = PDMetaManager.getIdentifierFactory();
final FormErrorList aFormErrors = new FormErrorList();
{
final IPDBusinessCardProvider aBCProv = PDMetaManager.getBusinessCardProvider();
if (aBCProv instanceof SMPBusinessCardProvider) {
final SMPBusinessCardProvider aSMPBCProv = (SMPBusinessCardProvider) aBCProv;
if (aSMPBCProv.isFixedSMP()) {
aNodeList.addChild(info("Fixed SMP URI " + aSMPBCProv.getFixedSMPURI() + " is used."));
} else {
aNodeList.addChild(info("The following SMLs are crawled for entries: " + StringHelper.getImplodedMapped(", ", aSMPBCProv.getAllSMLsToUse(), ISMLInfo::getDisplayName)));
}
}
}
final boolean bIsFormSubmitted = aWPEC.hasAction(CPageParam.ACTION_PERFORM);
if (bIsFormSubmitted) {
final IFileItem aFile = aWPEC.params().getAsFileItem(FIELD_FILE);
if (aFile == null || StringHelper.hasNoText(aFile.getName()))
aFormErrors.addFieldError(FIELD_FILE, "No file was selected");
if (aFormErrors.isEmpty()) {
final HCNodeList aResultNL = new HCNodeList();
final SAXReaderSettings aSettings = new SAXReaderSettings();
aSettings.setFeatureValues(EXMLParserFeature.AVOID_DOS_SETTINGS);
final CollectingSAXErrorHandler aErrorHandler = new CollectingSAXErrorHandler();
aSettings.setErrorHandler(aErrorHandler);
final ICommonsList<IParticipantIdentifier> aQueued = new CommonsArrayList<>();
final ICommonsList<IParticipantIdentifier> aNotQueued = new CommonsArrayList<>();
aSettings.setContentHandler(new DefaultHandler() {
@Override
public void startElement(final String sURI, final String sLocalName, final String sQName, final Attributes aAttributes) throws SAXException {
if (sQName.equals("participant")) {
final String sScheme = aAttributes.getValue("scheme");
final String sValue = aAttributes.getValue("value");
final IParticipantIdentifier aParticipantID = aIdentifierFactory.createParticipantIdentifier(sScheme, sValue);
if (aParticipantID != null) {
if (PDMetaManager.getIndexerMgr().queueWorkItem(aParticipantID, EIndexerWorkItemType.CREATE_UPDATE, CPDStorage.OWNER_IMPORT_TRIGGERED, PDIndexerManager.HOST_LOCALHOST).isChanged()) {
aQueued.add(aParticipantID);
} else {
aNotQueued.add(aParticipantID);
}
} else
LOGGER.error("Failed to convert '" + sScheme + "' and '" + sValue + "' to a participant identifier");
}
}
});
LOGGER.info("Importing participant IDs from '" + aFile.getNameSecure() + "'");
final ESuccess eSuccess = SAXReader.readXMLSAX(new FileItemResource(aFile), aSettings);
LOGGER.info("Finished reading XML file. Queued " + aQueued.size() + "; not queued: " + aNotQueued.size() + "; errors: " + aErrorHandler.getErrorList().size());
// Some things may have been queued even in case of error
if (aQueued.isNotEmpty()) {
final HCUL aUL = new HCUL();
for (final IParticipantIdentifier aPI : aQueued) aUL.addItem(aPI.getURIEncoded());
aResultNL.addChild(success(div("The following identifiers were successfully queued for indexing:")).addChild(aUL));
}
if (aNotQueued.isNotEmpty()) {
final HCUL aUL = new HCUL();
for (final IParticipantIdentifier aPI : aNotQueued) aUL.addItem(aPI.getURIEncoded());
aResultNL.addChild(warn(div("The following identifiers could not be queued (because they are already in the queue):")).addChild(aUL));
}
if (eSuccess.isFailure()) {
final HCUL aUL = new HCUL();
for (final IError aError : aErrorHandler.getErrorList()) {
final String sMsg = aError.getAsString(AppCommonUI.DEFAULT_LOCALE);
LOGGER.error(" " + sMsg);
aUL.addItem(sMsg);
}
aResultNL.addChild(error(div("Error parsing provided XML:")).addChild(aUL));
}
aWPEC.postRedirectGetInternal(aResultNL);
}
}
final BootstrapForm aForm = aNodeList.addAndReturnChild(getUIHandler().createFormFileUploadSelf(aWPEC, bIsFormSubmitted));
aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Import file").setCtrl(new BootstrapFileUpload(FIELD_FILE, aDisplayLocale)).setHelpText("Select a file that was created from a full XML export to index of all them manually.").setErrorList(aFormErrors.getListOfField(FIELD_FILE)));
final BootstrapButtonToolbar aToolbar = aForm.addAndReturnChild(new BootstrapButtonToolbar(aWPEC));
aToolbar.addHiddenField(CPageParam.PARAM_ACTION, CPageParam.ACTION_PERFORM);
aToolbar.addSubmitButton("Import all", EDefaultIcon.YES);
}
use of com.helger.web.fileupload.IFileItem in project ph-web by phax.
the class AbstractFileUploadBase method parseRequest.
/**
* Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a>
* compliant <code>multipart/form-data</code> stream.
*
* @param aCtx
* The context for the request to be parsed.
* @return A list of <code>FileItem</code> instances parsed from the request,
* in the order that they were transmitted.
* @throws FileUploadException
* if there are problems reading/parsing the request or storing files.
*/
@Nonnull
@ReturnsMutableCopy
public ICommonsList<IFileItem> parseRequest(@Nonnull final IRequestContext aCtx) throws FileUploadException {
final ICommonsList<IFileItem> aItems = new CommonsArrayList<>();
boolean bSuccessful = false;
try {
final IFileItemIterator aItemIter = getItemIterator(aCtx);
final IFileItemFactory aFileItemFactory = getFileItemFactory();
if (aFileItemFactory == null)
throw new IllegalStateException("No FileItemFactory has been set.");
while (aItemIter.hasNext()) {
final IFileItemStream aFileItemStream = aItemIter.next();
// Don't use getName() here to prevent an InvalidFileNameException.
final IFileItem aFileItem = aFileItemFactory.createItem(aFileItemStream.getFieldName(), aFileItemStream.getContentType(), aFileItemStream.isFormField(), aFileItemStream.getNameUnchecked());
aItems.add(aFileItem);
try (final InputStream aIS = aFileItemStream.openStream();
final OutputStream aOS = aFileItem.getOutputStream()) {
final byte[] aBuffer = new byte[8192];
int nBytesRead;
// potentially blocking read
while ((nBytesRead = aIS.read(aBuffer, 0, aBuffer.length)) > -1) {
aOS.write(aBuffer, 0, nBytesRead);
}
} catch (final FileUploadIOException ex) {
throw (FileUploadException) ex.getCause();
} catch (final IOException ex) {
throw new IOFileUploadException("Processing of " + RequestHelper.MULTIPART_FORM_DATA + " request failed. " + ex.getMessage(), ex);
}
if (aFileItem instanceof IFileItemHeadersSupport) {
final IFileItemHeaders aFileItemHeaders = aFileItemStream.getHeaders();
((IFileItemHeadersSupport) aFileItem).setHeaders(aFileItemHeaders);
}
}
bSuccessful = true;
return aItems;
} catch (final FileUploadIOException ex) {
throw (FileUploadException) ex.getCause();
} catch (final IOException ex) {
throw new FileUploadException(ex.getMessage(), ex);
} finally {
if (!bSuccessful) {
// Delete all file items
for (final IFileItem aFileItem : aItems) {
try {
aFileItem.delete();
} catch (final Exception ex) {
// ignore it
if (LOGGER.isErrorEnabled())
LOGGER.error("Failed to delete fileItem " + aFileItem, ex);
}
}
}
}
}
use of com.helger.web.fileupload.IFileItem in project ph-web by phax.
the class DiskFileItemTest method testBelowThreshold.
/**
* Test creation of a field for which the amount of data falls below the
* configured threshold.
*/
@Test
public void testBelowThreshold() {
// Create the FileItem
final byte[] testFieldValueBytes = _createContentBytes(THRESHOLD - 1);
final IFileItem item = _createFileItem(testFieldValueBytes);
// Check state is as expected
assertTrue("Initial: in memory", item.isInMemory());
assertEquals("Initial: size", item.getSize(), testFieldValueBytes.length);
_compareBytes("Initial", item.directGet(), testFieldValueBytes);
// Serialize & Deserialize
if (false)
try {
final IFileItem newItem = (IFileItem) _serializeDeserialize(item);
// Test deserialized content is as expected
assertTrue("Check in memory", newItem.isInMemory());
_compareBytes("Check", testFieldValueBytes, newItem.directGet());
// Compare FileItem's (except byte[])
_compareFileItems(item, newItem);
} catch (final Exception e) {
fail("Error Serializing/Deserializing: " + e);
}
}
Aggregations