Skip to content

Instantly share code, notes, and snippets.

@oharsta
Last active May 15, 2016 15:27
Show Gist options
  • Select an option

  • Save oharsta/655dd3fba11619d9e89d40a02c5c4e69 to your computer and use it in GitHub Desktop.

Select an option

Save oharsta/655dd3fba11619d9e89d40a02c5c4e69 to your computer and use it in GitHub Desktop.
Parsing a large XML SAML feed of IdentityProviders and ServiceProviders to a Map with all Service Providers entityID's and the signing certificates
package eduproxy.saml;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
public class EduGainFeedParser {
private final Resource resource;
public EduGainFeedParser(Resource resource) {
this.resource = resource;
}
public Map<String, String> parse() throws IOException, XMLStreamException {
//despite it's name, the XMLInputFactoryImpl is not thread safe
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(resource.getInputStream());
Map<String, String> serviceProviders = new HashMap<>();
String entityId = null;
boolean isServiceProvider = false, isSigning = false;
while (reader.hasNext()) {
switch (reader.next()) {
case START_ELEMENT:
switch (reader.getLocalName()) {
case "EntityDescriptor":
entityId = reader.getAttributeValue(null, "entityID");
isServiceProvider = false;
break;
case "SPSSODescriptor":
isServiceProvider = true;
break;
case "KeyDescriptor":
String use = reader.getAttributeValue(null, "use");
isSigning = "signing".equals(use);
break;
case "X509Certificate": {
if (isServiceProvider && isSigning) {
addEntity(entityId, reader.getElementText(), serviceProviders);
}
}
}
}
}
return serviceProviders;
}
private void addEntity(String entityId, String signature, Map<String, String> serviceProviders) {
if (StringUtils.hasText(signature)) {
serviceProviders.put(entityId, signature.replaceAll("\\s",""));
}
}
}
@oharsta
Copy link
Copy Markdown
Author

oharsta commented May 15, 2016

24MB in 250ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment