proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/profile/converter/ComplexTypeSAML2AttributeConverter.java
|
ComplexTypeSAML2AttributeConverter
|
from
|
class ComplexTypeSAML2AttributeConverter implements AttributeConverter {
/** {@inheritDoc} */
@Override
public Object convert(final Object a) {
val attribute = (Attribute) a;
List<SAML2AuthenticationCredentials.SAMLAttribute> extractedAttributes = new ArrayList<>();
// collect all complex values
attribute.getAttributeValues().stream()
.filter(XMLObject::hasChildren)
.forEach(attributeValue -> {
val attrs = collectAttributesFromNodeList(attributeValue.getDOM().getChildNodes());
extractedAttributes.addAll(attrs);
});
// collect all simple values
SAML2AuthenticationCredentials.SAMLAttribute simpleValues = from(attribute);
if (!simpleValues.getAttributeValues().isEmpty()) {
extractedAttributes.add(simpleValues);
}
return extractedAttributes;
}
private SAML2AuthenticationCredentials.SAMLAttribute from(Attribute attribute) {<FILL_FUNCTION_BODY>}
private List<SAML2AuthenticationCredentials.SAMLAttribute> collectAttributesFromNodeList(NodeList nodeList) {
List<SAML2AuthenticationCredentials.SAMLAttribute> results = new ArrayList<>();
if (nodeList == null) {
return results;
}
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.hasChildNodes()) {
results.addAll(collectAttributesFromNodeList(node.getChildNodes()));
} else if (!node.getTextContent().isBlank()) {
SAML2AuthenticationCredentials.SAMLAttribute samlAttribute = new SAML2AuthenticationCredentials.SAMLAttribute();
samlAttribute.setName(node.getParentNode().getLocalName());
samlAttribute.getAttributeValues().add(node.getTextContent());
results.add(samlAttribute);
}
}
return results;
}
}
|
val samlAttribute = new SAML2AuthenticationCredentials.SAMLAttribute();
samlAttribute.setFriendlyName(attribute.getFriendlyName());
samlAttribute.setName(attribute.getName());
samlAttribute.setNameFormat(attribute.getNameFormat());
List<String> values = attribute.getAttributeValues()
.stream()
.filter(val -> !val.hasChildren())
.map(XMLObject::getDOM)
.filter(dom -> dom != null && dom.getTextContent() != null)
.map(Element::getTextContent)
.collect(Collectors.toList());
samlAttribute.setAttributeValues(values);
return samlAttribute;
| 507
| 177
| 684
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/profile/converter/SimpleSAML2AttributeConverter.java
|
SimpleSAML2AttributeConverter
|
convert
|
class SimpleSAML2AttributeConverter implements AttributeConverter {
/** {@inheritDoc} */
@Override
public Object convert(final Object a) {<FILL_FUNCTION_BODY>}
}
|
val attribute = (Attribute) a;
val samlAttribute = new SAML2AuthenticationCredentials.SAMLAttribute();
samlAttribute.setFriendlyName(attribute.getFriendlyName());
samlAttribute.setName(attribute.getName());
samlAttribute.setNameFormat(attribute.getNameFormat());
attribute.getAttributeValues()
.stream()
.map(XMLObject::getDOM)
.filter(dom -> dom != null && dom.getTextContent() != null)
.forEach(dom -> samlAttribute.getAttributeValues().add(dom.getTextContent().trim()));
return samlAttribute;
| 52
| 159
| 211
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/profile/impl/AbstractSAML2MessageSender.java
|
AbstractSAML2MessageSender
|
sendMessage
|
class AbstractSAML2MessageSender<T extends SAMLObject> implements SAML2MessageSender<T> {
protected final SignatureSigningParametersProvider signatureSigningParametersProvider;
protected final String destinationBindingType;
protected final boolean signErrorResponses;
protected final boolean isRequestSigned;
/** {@inheritDoc} */
@Override
public void sendMessage(final SAML2MessageContext context,
final T request,
final Object relayState) {<FILL_FUNCTION_BODY>}
/**
* <p>storeMessage.</p>
*
* @param context a {@link SAML2MessageContext} object
* @param request a T object
*/
protected void storeMessage(final SAML2MessageContext context, final T request) {
val messageStorage = context.getSamlMessageStore();
if (messageStorage != null) {
if (request instanceof RequestAbstractType requestAbstractType) {
messageStorage.set(requestAbstractType.getID(), request);
} else if (request instanceof StatusResponseType statusResponseType) {
messageStorage.set(statusResponseType.getID(), request);
}
}
}
/**
* <p>getEndpoint.</p>
*
* @param context a {@link SAML2MessageContext} object
* @return a {@link Endpoint} object
*/
protected abstract Endpoint getEndpoint(SAML2MessageContext context);
/**
* <p>invokeOutboundMessageHandlers.</p>
*
* @param spDescriptor a {@link SPSSODescriptor} object
* @param idpssoDescriptor a {@link IDPSSODescriptor} object
* @param messageContext a {@link MessageContext} object
*/
protected void invokeOutboundMessageHandlers(final SPSSODescriptor spDescriptor,
final IDPSSODescriptor idpssoDescriptor,
final MessageContext messageContext) {
try {
MessageHandler handlerEnd =
new EndpointURLSchemeSecurityHandler();
handlerEnd.initialize();
handlerEnd.invoke(messageContext);
MessageHandler handlerDest =
new SAMLOutboundDestinationHandler();
handlerDest.initialize();
handlerDest.invoke(messageContext);
if (!destinationBindingType.equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI) &&
mustSignRequest(spDescriptor, idpssoDescriptor)) {
LOGGER.debug("Signing SAML2 outbound context...");
val handler = new
SAMLOutboundProtocolMessageSigningHandler();
handler.setSignErrorResponses(this.signErrorResponses);
handler.initialize();
handler.invoke(messageContext);
}
} catch (final Exception e) {
throw new SAMLException(e);
}
}
/**
* <p>mustSignRequest.</p>
*
* @param spDescriptor a {@link SPSSODescriptor} object
* @param idpssoDescriptor a {@link IDPSSODescriptor} object
* @return a boolean
*/
protected boolean mustSignRequest(final SPSSODescriptor spDescriptor, final IDPSSODescriptor idpssoDescriptor) {
return isRequestSigned;
}
private MessageEncoder getMessageEncoder(final SPSSODescriptor spDescriptor,
final IDPSSODescriptor idpssoDescriptor,
final SAML2MessageContext ctx) {
val adapter = ctx.getProfileRequestContextOutboundMessageTransportResponse();
if (SAMLConstants.SAML2_POST_BINDING_URI.equals(destinationBindingType)) {
val velocityEngine = VelocityEngineFactory.getEngine();
val encoder = new Pac4jHTTPPostEncoder(adapter);
encoder.setVelocityEngine(velocityEngine);
return encoder;
} else if (SAMLConstants.SAML2_POST_SIMPLE_SIGN_BINDING_URI.equals(destinationBindingType)) {
val velocityEngine = VelocityEngineFactory.getEngine();
val encoder = new Pac4jHTTPPostSimpleSignEncoder(adapter);
encoder.setVelocityEngine(velocityEngine);
return encoder;
} else if (SAMLConstants.SAML2_REDIRECT_BINDING_URI.equals(destinationBindingType)) {
return new Pac4jHTTPRedirectDeflateEncoder(adapter, mustSignRequest(spDescriptor, idpssoDescriptor));
} else {
throw new UnsupportedOperationException("Binding type - "
+ destinationBindingType + " is not supported");
}
}
}
|
val spDescriptor = context.getSPSSODescriptor();
val idpssoDescriptor = context.getIDPSSODescriptor();
val acsService = context.getSPAssertionConsumerService();
val encoder = getMessageEncoder(spDescriptor, idpssoDescriptor, context);
val outboundContext = new SAML2MessageContext(context.getCallContext());
outboundContext.setMessageContext(context.getMessageContext());
outboundContext.getProfileRequestContext().setProfileId(outboundContext.getProfileRequestContext().getProfileId());
outboundContext.getProfileRequestContext().setInboundMessageContext(
context.getProfileRequestContext().getInboundMessageContext());
outboundContext.getProfileRequestContext().setOutboundMessageContext(
context.getProfileRequestContext().getOutboundMessageContext());
outboundContext.getMessageContext().setMessage(request);
outboundContext.getSAMLEndpointContext().setEndpoint(acsService);
outboundContext.getSAMLPeerEndpointContext().setEndpoint(getEndpoint(outboundContext));
outboundContext.getSAMLPeerEntityContext().setRole(outboundContext.getSAMLPeerEntityContext().getRole());
outboundContext.getSAMLPeerEntityContext().setEntityId(outboundContext.getSAMLPeerEntityContext().getEntityId());
outboundContext.getSAMLProtocolContext().setProtocol(outboundContext.getSAMLProtocolContext().getProtocol());
outboundContext.getSecurityParametersContext()
.setSignatureSigningParameters(this.signatureSigningParametersProvider.build(spDescriptor));
if (relayState != null) {
outboundContext.getSAMLBindingContext().setRelayState(relayState.toString());
}
try {
val messageContext = outboundContext.getMessageContext();
invokeOutboundMessageHandlers(spDescriptor, idpssoDescriptor, messageContext);
encoder.setMessageContext(messageContext);
encoder.initialize();
encoder.prepareContext();
encoder.encode();
storeMessage(context, request);
SAML2Utils.logProtocolMessage(request);
} catch (final MessageEncodingException e) {
throw new SAMLException("Error encoding saml message", e);
} catch (final ComponentInitializationException e) {
throw new SAMLException("Error initializing saml encoder", e);
}
| 1,168
| 596
| 1,764
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/redirect/SAML2RedirectionActionBuilder.java
|
SAML2RedirectionActionBuilder
|
getRedirectionAction
|
class SAML2RedirectionActionBuilder implements RedirectionActionBuilder {
private final SAML2Client client;
protected SAML2ObjectBuilder<AuthnRequest> saml2ObjectBuilder;
/**
* <p>Constructor for SAML2RedirectionActionBuilder.</p>
*
* @param client a {@link SAML2Client} object
*/
public SAML2RedirectionActionBuilder(final SAML2Client client) {
CommonHelper.assertNotNull("client", client);
this.client = client;
this.saml2ObjectBuilder = new SAML2AuthnRequestBuilder();
}
/** {@inheritDoc} */
@Override
public Optional<RedirectionAction> getRedirectionAction(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
val context = this.client.getContextProvider().buildContext(ctx, this.client);
val relayState = this.client.getStateGenerator().generateValue(ctx);
val authnRequest = this.saml2ObjectBuilder.build(context);
this.client.getSSOMessageSender().sendMessage(context, authnRequest, relayState);
val adapter = context.getProfileRequestContextOutboundMessageTransportResponse();
val webContext = ctx.webContext();
val bindingType = this.client.getConfiguration().getAuthnRequestBindingType();
if (SAMLConstants.SAML2_POST_BINDING_URI.equalsIgnoreCase(bindingType) ||
SAMLConstants.SAML2_POST_SIMPLE_SIGN_BINDING_URI.equalsIgnoreCase(bindingType)) {
val content = adapter.getOutgoingContent();
return Optional.of(HttpActionHelper.buildFormPostContentAction(webContext, content));
}
val location = adapter.getRedirectUrl();
return Optional.of(HttpActionHelper.buildRedirectUrlAction(webContext, location));
| 206
| 276
| 482
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/sso/artifact/DefaultSignatureSigningParametersResolver.java
|
DefaultSignatureSigningParametersResolver
|
resolveSingle
|
class DefaultSignatureSigningParametersResolver implements SignatureSigningParametersResolver {
private SignatureSigningParametersProvider provider;
/**
* <p>Constructor for DefaultSignatureSigningParametersResolver.</p>
*
* @param provider a {@link SignatureSigningParametersProvider} object
*/
public DefaultSignatureSigningParametersResolver(final SignatureSigningParametersProvider provider) {
this.provider = provider;
}
/** {@inheritDoc} */
@Override
public Iterable<SignatureSigningParameters> resolve(final CriteriaSet criteria) throws ResolverException {
val ret = resolveSingle(criteria);
return ret == null ? Collections.emptySet() : Collections.singleton(ret);
}
/** {@inheritDoc} */
@Override
public SignatureSigningParameters resolveSingle(final CriteriaSet criteria) throws ResolverException {<FILL_FUNCTION_BODY>}
}
|
if (criteria == null) {
throw new ResolverException("CriteriaSet was null");
}
val role = criteria.get(RoleDescriptorCriterion.class);
if (role == null) {
throw new ResolverException("No RoleDescriptorCriterion specified");
}
return provider.build((SSODescriptor) role.getRole());
| 226
| 93
| 319
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/sso/artifact/IssuerFunction.java
|
IssuerFunction
|
apply
|
class IssuerFunction implements Function<MessageContext, String> {
/** {@inheritDoc} */
@Override
public String apply(final MessageContext context) {<FILL_FUNCTION_BODY>}
}
|
if (context == null) {
return null;
}
val message = (SAMLObject) context.getMessage();
Issuer issuer = null;
if (message instanceof RequestAbstractType) {
issuer = ((RequestAbstractType) message).getIssuer();
} else if (message instanceof StatusResponseType) {
issuer = ((StatusResponseType) message).getIssuer();
}
return issuer != null ? issuer.getValue() : null;
| 52
| 120
| 172
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/sso/artifact/SAML2ArtifactBindingDecoder.java
|
SAML2ArtifactBindingDecoder
|
doDecode
|
class SAML2ArtifactBindingDecoder extends AbstractPac4jDecoder {
private final SAML2MetadataResolver idpMetadataResolver;
private final SAML2MetadataResolver spMetadataResolver;
private final SOAPPipelineProvider soapPipelineProvider;
/**
* <p>Constructor for SAML2ArtifactBindingDecoder.</p>
*
* @param context a {@link CallContext} object
* @param idpMetadataResolver a {@link SAML2MetadataResolver} object
* @param spMetadataResolver a {@link SAML2MetadataResolver} object
* @param soapPipelineProvider a {@link SOAPPipelineProvider} object
*/
public SAML2ArtifactBindingDecoder(final CallContext context, final SAML2MetadataResolver idpMetadataResolver,
final SAML2MetadataResolver spMetadataResolver, final SOAPPipelineProvider soapPipelineProvider) {
super(context);
this.idpMetadataResolver = idpMetadataResolver;
this.spMetadataResolver = spMetadataResolver;
this.soapPipelineProvider = soapPipelineProvider;
}
/** {@inheritDoc} */
@Override
public String getBindingURI(final SAML2MessageContext messageContext) {
return SAMLConstants.SAML2_ARTIFACT_BINDING_URI;
}
/** {@inheritDoc} */
@Override
protected void doDecode() throws MessageDecodingException {<FILL_FUNCTION_BODY>}
/**
* <p>transferContext.</p>
*
* @param operationContext a {@link InOutOperationContext} object
* @param messageContext a {@link SAML2MessageContext} object
*/
protected void transferContext(final InOutOperationContext operationContext, final SAML2MessageContext messageContext) {
messageContext.getMessageContext()
.addSubcontext(Objects.requireNonNull(Objects.requireNonNull(operationContext.getInboundMessageContext())
.getSubcontext(SAMLPeerEntityContext.class)));
}
}
|
try {
val endpointResolver = new DefaultEndpointResolver<ArtifactResolutionService>();
endpointResolver.initialize();
val roleResolver = new PredicateRoleDescriptorResolver(
idpMetadataResolver.resolve());
roleResolver.initialize();
val messageContext = new SAML2MessageContext(getCallContext());
val soapClient = new PipelineFactoryHttpSOAPClient() {
@SuppressWarnings("rawtypes")
@Override
public void send(final String endpoint, final InOutOperationContext operationContext)
throws SOAPException, SecurityException {
super.send(endpoint, operationContext);
transferContext(operationContext, messageContext);
}
};
soapClient.setPipelineFactory(soapPipelineProvider.getPipelineFactory());
soapClient.setHttpClient(soapPipelineProvider.getHttpClientBuilder().buildClient());
val artifactDecoder = new Pac4jHTTPArtifactDecoder();
artifactDecoder.setCallContext(callContext);
artifactDecoder.setSelfEntityIDResolver(new FixedEntityIdResolver(spMetadataResolver));
artifactDecoder.setRoleDescriptorResolver(roleResolver);
artifactDecoder.setArtifactEndpointResolver(endpointResolver);
artifactDecoder.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
artifactDecoder.setSoapClient(soapClient);
artifactDecoder.setParserPool(getParserPool());
artifactDecoder.initialize();
artifactDecoder.decode();
messageContext.getMessageContext().setMessage(artifactDecoder.getMessageContext().getMessage());
this.populateBindingContext(messageContext);
this.setMessageContext(messageContext.getMessageContext());
} catch (final Exception e) {
throw new MessageDecodingException(e);
}
| 510
| 444
| 954
|
<methods>public non-sealed void <init>() ,public abstract java.lang.String getBindingURI(org.pac4j.saml.context.SAML2MessageContext) ,public void setParserPool(net.shibboleth.shared.xml.ParserPool) <variables>static final java.lang.String[] SAML_PARAMETERS,protected final non-sealed CallContext callContext,protected net.shibboleth.shared.xml.ParserPool parserPool
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/sso/impl/SAML2WebSSOMessageSender.java
|
SAML2WebSSOMessageSender
|
mustSignRequest
|
class SAML2WebSSOMessageSender extends AbstractSAML2MessageSender<AuthnRequest> {
/**
* <p>Constructor for SAML2WebSSOMessageSender.</p>
*
* @param signatureSigningParametersProvider a {@link SignatureSigningParametersProvider} object
* @param destinationBindingType a {@link String} object
* @param signErrorResponses a boolean
* @param isAuthnRequestSigned a boolean
*/
public SAML2WebSSOMessageSender(final SignatureSigningParametersProvider signatureSigningParametersProvider,
final String destinationBindingType,
final boolean signErrorResponses,
final boolean isAuthnRequestSigned) {
super(signatureSigningParametersProvider, destinationBindingType, signErrorResponses, isAuthnRequestSigned);
}
/** {@inheritDoc} */
@Override
protected boolean mustSignRequest(final SPSSODescriptor spDescriptor, final IDPSSODescriptor idpssoDescriptor) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
protected Endpoint getEndpoint(final SAML2MessageContext context) {
return context.getIDPSingleSignOnService(destinationBindingType);
}
}
|
var signOutboundContext = false;
if (this.isRequestSigned) {
LOGGER.debug("Requests are expected to be always signed before submission");
signOutboundContext = true;
} else if (spDescriptor.isAuthnRequestsSigned()) {
LOGGER.debug("The service provider metadata indicates that authn requests are signed");
signOutboundContext = true;
} else if (idpssoDescriptor.getWantAuthnRequestsSigned()) {
LOGGER.debug("The identity provider metadata indicates that authn requests may be signed");
signOutboundContext = true;
}
return signOutboundContext;
| 317
| 159
| 476
|
<methods>public non-sealed void <init>() ,public void sendMessage(org.pac4j.saml.context.SAML2MessageContext, org.opensaml.saml.saml2.core.AuthnRequest, java.lang.Object) <variables>protected final non-sealed java.lang.String destinationBindingType,protected final non-sealed boolean isRequestSigned,protected final non-sealed boolean signErrorResponses,protected final non-sealed org.pac4j.saml.crypto.SignatureSigningParametersProvider signatureSigningParametersProvider
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/state/SAML2StateGenerator.java
|
SAML2StateGenerator
|
generateValue
|
class SAML2StateGenerator implements ValueGenerator {
/** Constant <code>SAML_RELAY_STATE_ATTRIBUTE="samlRelayState"</code> */
public static final String SAML_RELAY_STATE_ATTRIBUTE = "samlRelayState";
private final SAML2Client client;
/** {@inheritDoc} */
@Override
public String generateValue(final CallContext ctx) {<FILL_FUNCTION_BODY>}
}
|
val webContext = ctx.webContext();
val sessionStore = ctx.sessionStore();
val relayState = sessionStore.get(webContext, SAML_RELAY_STATE_ATTRIBUTE);
// clean from session after retrieving it
if (relayState.isPresent()) {
sessionStore.set(webContext, SAML_RELAY_STATE_ATTRIBUTE, null);
}
return relayState.isPresent() ? (String) relayState.get() : client.computeFinalCallbackUrl(webContext);
| 123
| 132
| 255
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/store/HazelcastSAMLMessageStore.java
|
HazelcastSAMLMessageStore
|
get
|
class HazelcastSAMLMessageStore implements SAMLMessageStore {
private static final String MAP_NAME = HazelcastSAMLMessageStore.class.getSimpleName();
private final HazelcastInstance hazelcastInstance;
/**
* <p>Constructor for HazelcastSAMLMessageStore.</p>
*
* @param hazelcastInstance a {@link HazelcastInstance} object
*/
public HazelcastSAMLMessageStore(final HazelcastInstance hazelcastInstance) {
CommonHelper.assertNotNull("hazelcastInstance", hazelcastInstance);
this.hazelcastInstance = hazelcastInstance;
}
private IMap<String, String> getStoreMapInstance() {
IMap<String, String> inst = hazelcastInstance.getMap(MAP_NAME);
LOGGER.debug("Located Hazelcast map instance [{}]", MAP_NAME);
return inst;
}
/** {@inheritDoc} */
@Override
public Optional<XMLObject> get(final String messageID) {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public void set(final String messageID, final XMLObject message) {
IMap<String, String> map = getStoreMapInstance();
LOGGER.debug("Storing message {} to Hazelcast map {}", messageID, MAP_NAME);
map.put(messageID, Base64.getEncoder().encodeToString(
Configuration.serializeSamlObject(message).toString().getBytes(StandardCharsets.UTF_8)));
}
/** {@inheritDoc} */
@Override
public void remove(final String messageID) {
IMap<String, String> map = getStoreMapInstance();
LOGGER.debug("Removing message {} from Hazelcast map {}", messageID, MAP_NAME);
map.remove(messageID);
}
}
|
IMap<String, String> map = getStoreMapInstance();
LOGGER.debug("Attempting to get message {} from Hazelcast map {}", messageID, MAP_NAME);
String message = map.get(messageID);
if (message == null) {
LOGGER.debug("Message {} not found in Hazelcast map {}", messageID, MAP_NAME);
return Optional.empty();
}
LOGGER.debug("Message {} found in Hazelcast map {}, clearing", messageID, MAP_NAME);
map.remove(messageID);
return Configuration.deserializeSamlObject(
new String(Base64.getDecoder().decode(message), StandardCharsets.UTF_8));
| 480
| 180
| 660
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/store/HttpSessionStore.java
|
HttpSessionStore
|
get
|
class HttpSessionStore implements SAMLMessageStore {
/**
* The web context to store data.
*/
private final WebContext context;
private final SessionStore sessionStore;
/**
* Internal store for messages, corresponding to the object in session.
*/
private LinkedHashMap<String, String> internalMessages;
/**
* Session key for storing the hashtable.
*/
private static final String SAML_STORAGE_KEY = "_springSamlStorageKey";
/**
* {@inheritDoc}
*
* Stores a request message into the repository. RequestAbstractType must have an ID
* set. Any previous message with the same ID will be overwritten.
*/
@Override
public void set(final String messageID, final XMLObject message) {
LOGGER.debug("Storing message {} to session {}", messageID,
sessionStore.getSessionId(context, true).orElseThrow());
val messages = getMessages();
messages.put(messageID, Configuration.serializeSamlObject(message).toString());
updateSession(messages);
}
/**
* {@inheritDoc}
*
* Returns previously stored message with the given ID or null, if there is no message
* stored.
* <p>
* Message is stored in String format and must be unmarshalled into XMLObject. Call to this
* method may thus be expensive.
* <p>
* Messages are automatically cleared upon successful reception, as we presume that there
* are never multiple ongoing SAML exchanges for the same session. This saves memory used by
* the session.
*/
@Override
public Optional<XMLObject> get(final String messageID) {<FILL_FUNCTION_BODY>}
/**
* Provides message store hashtable. Table is lazily initialized when user tries to store or retrieve
* the first message.
*
* @return message store
*/
private LinkedHashMap<String, String> getMessages() {
if (internalMessages == null) {
internalMessages = initializeSession();
}
return internalMessages;
}
/**
* Call to the method tries to load internalMessages hashtable object from the session, if the object doesn't exist
* it will be created and stored.
* <p>
* Method synchronizes on session object to prevent two threads from overwriting each others hashtable.
*/
@SuppressWarnings("unchecked")
private LinkedHashMap<String, String> initializeSession() {
var messages = sessionStore.get(context, SAML_STORAGE_KEY);
if (messages.isEmpty()) {
synchronized (context) {
messages = sessionStore.get(context, SAML_STORAGE_KEY);
if (messages.isEmpty()) {
messages = Optional.of(new LinkedHashMap<>());
updateSession((LinkedHashMap<String, String>) messages.get());
}
}
}
return (LinkedHashMap<String, String>) messages.get();
}
/**
* Updates session with the internalMessages key. Some application servers require session value to be updated
* in order to replicate the session across nodes or persist it correctly.
*/
private void updateSession(final LinkedHashMap<String, String> messages) {
sessionStore.set(context, SAML_STORAGE_KEY, messages);
}
/** {@inheritDoc} */
@Override
public void remove(final String key) {
set(key, null);
}
}
|
val messages = getMessages();
val o = messages.get(messageID);
if (o == null) {
LOGGER.debug("Message {} not found in session {}", messageID, sessionStore.getSessionId(context, true).orElseThrow());
return Optional.empty();
}
LOGGER.debug("Message {} found in session {}, clearing", messageID, sessionStore.getSessionId(context, true).orElseThrow());
messages.clear();
updateSession(messages);
return Configuration.deserializeSamlObject(o);
| 887
| 139
| 1,026
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/transport/AbstractPac4jDecoder.java
|
AbstractPac4jDecoder
|
unmarshallMessage
|
class AbstractPac4jDecoder extends AbstractMessageDecoder {
static final String[] SAML_PARAMETERS = {"SAMLRequest", "SAMLResponse", "logoutRequest"};
/** Parser pool used to deserialize the message. */
@Getter
protected ParserPool parserPool;
@Getter
protected final CallContext callContext;
/**
* <p>getBase64DecodedMessage.</p>
*
* @return an array of {@link byte} objects
* @throws MessageDecodingException if any.
*/
protected byte[] getBase64DecodedMessage() throws MessageDecodingException {
Optional<String> encodedMessage = Optional.empty();
for (val parameter : SAML_PARAMETERS) {
encodedMessage = this.callContext.webContext().getRequestParameter(parameter);
if (encodedMessage.isPresent()) {
break;
}
}
if (encodedMessage.isEmpty()) {
encodedMessage = Optional.ofNullable(this.callContext.webContext().getRequestContent());
// we have a body, it may be the SAML request/response directly
// but we also try to parse it as a list key=value where the value is the SAML request/response
if (encodedMessage.isPresent()) {
val a = URLEncodedUtils.parse(encodedMessage.get(), StandardCharsets.UTF_8);
final Multimap<String, String> paramMap = HashMultimap.create();
for (val p : a) {
paramMap.put(p.getName(), p.getValue());
}
for (val parameter : SAML_PARAMETERS) {
val newEncodedMessageCollection = paramMap.get(parameter);
if (newEncodedMessageCollection != null && !newEncodedMessageCollection.isEmpty()) {
encodedMessage = Optional.of(newEncodedMessageCollection.iterator().next());
break;
}
}
}
}
if (encodedMessage.isEmpty()) {
throw new MessageDecodingException("Request did not contain either a SAMLRequest parameter, a SAMLResponse parameter, "
+ "a logoutRequest parameter or a body content");
} else {
if (encodedMessage.get().contains("<")) {
LOGGER.trace("Raw SAML message:\n{}", encodedMessage);
return encodedMessage.get().getBytes(StandardCharsets.UTF_8);
} else {
try {
val decodedBytes = Base64Support.decode(encodedMessage.get());
LOGGER.trace("Decoded SAML message:\n{}", new String(decodedBytes, StandardCharsets.UTF_8));
return decodedBytes;
} catch (final Exception e) {
throw new MessageDecodingException(e);
}
}
}
}
/** {@inheritDoc} */
@Override
protected void doDestroy() {
parserPool = null;
super.doDestroy();
}
/** {@inheritDoc} */
@Override
protected void doInitialize() throws ComponentInitializationException {
super.doInitialize();
LOGGER.debug("Initialized {}", this.getClass().getSimpleName());
if (parserPool == null) {
throw new ComponentInitializationException("Parser pool cannot be null");
}
}
/**
* Populate the context which carries information specific to this binding.
*
* @param messageContext the current message context
*/
protected void populateBindingContext(final SAML2MessageContext messageContext) {
val bindingContext = messageContext.getMessageContext().getSubcontext(SAMLBindingContext.class, true);
bindingContext.setBindingUri(getBindingURI(messageContext));
bindingContext.setHasBindingSignature(false);
bindingContext.setRelayState(bindingContext.getRelayState());
bindingContext.setIntendedDestinationEndpointURIRequired(SAMLBindingSupport.isMessageSigned(messageContext.getMessageContext()));
}
/**
* Get the binding of the message context;.
*
* @param messageContext the message context
* @return the binding URI
*/
public abstract String getBindingURI(SAML2MessageContext messageContext);
/**
* Helper method that deserializes and unmarshalls the message from the given stream.
*
* @param messageStream input stream containing the message
* @return the inbound message
* @throws MessageDecodingException thrown if there is a problem deserializing/unmarshalling the message
*/
protected XMLObject unmarshallMessage(final InputStream messageStream) throws MessageDecodingException {<FILL_FUNCTION_BODY>}
/**
* Sets the parser pool used to deserialize incoming messages.
*
* @param pool parser pool used to deserialize incoming messages
*/
public void setParserPool(final ParserPool pool) {
Constraint.isNotNull(pool, "ParserPool cannot be null");
parserPool = pool;
}
}
|
try {
val message = XMLObjectSupport.unmarshallFromInputStream(getParserPool(), messageStream);
return message;
} catch (final XMLParserException e) {
throw new MessageDecodingException("Error unmarshalling message from input stream", e);
} catch (final UnmarshallingException e) {
throw new MessageDecodingException("Error unmarshalling message from input stream", e);
}
| 1,249
| 105
| 1,354
|
<methods>public void <init>() ,public void decode() throws org.opensaml.messaging.decoder.MessageDecodingException,public org.opensaml.messaging.context.MessageContext getMessageContext() <variables>public static final java.lang.String BASE_PROTOCOL_MESSAGE_LOGGER_CATEGORY,private final org.slf4j.Logger log,private org.opensaml.messaging.context.MessageContext messageContext,private org.slf4j.Logger protocolMessageLog,private java.lang.String protocolMessageLoggerSubCategory
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/transport/DefaultPac4jSAMLResponse.java
|
Pac4jServletOutputStreamWriter
|
getOutgoingContent
|
class Pac4jServletOutputStreamWriter extends OutputStreamWriter {
private final ByteArrayOutputStream outputStream;
public Pac4jServletOutputStreamWriter(final ByteArrayOutputStream out) {
super(out, StandardCharsets.UTF_8);
outputStream = out;
}
public final String getOutgoingContent() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return this.getOutgoingContent();
}
}
|
try {
val result = new String(this.outputStream.toByteArray(), StandardCharsets.UTF_8);
return result;
} catch (final Exception e) {
throw new RuntimeException(e);
}
| 117
| 60
| 177
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/transport/Pac4jHTTPPostDecoder.java
|
Pac4jHTTPPostDecoder
|
doDecode
|
class Pac4jHTTPPostDecoder extends AbstractPac4jDecoder {
/**
* <p>Constructor for Pac4jHTTPPostDecoder.</p>
*
* @param context a {@link CallContext} object
*/
public Pac4jHTTPPostDecoder(final CallContext context) {
super(context);
}
/** {@inheritDoc} */
@Override
protected void doDecode() throws MessageDecodingException {<FILL_FUNCTION_BODY>}
/** {@inheritDoc} */
@Override
public String getBindingURI(final SAML2MessageContext messageContext) {
if (messageContext.getSOAP11Context().getEnvelope() != null) {
return SAMLConstants.SAML2_SOAP11_BINDING_URI;
} else {
return SAMLConstants.SAML2_POST_BINDING_URI;
}
}
}
|
val messageContext = new SAML2MessageContext(callContext);
if (WebContextHelper.isPost(callContext.webContext())) {
val relayState = this.callContext.webContext().getRequestParameter("RelayState").orElse(null);
LOGGER.debug("Decoded SAML relay state of: {}", relayState);
SAMLBindingSupport.setRelayState(messageContext.getMessageContext(), relayState);
val base64DecodedMessage = this.getBase64DecodedMessage();
val xmlObject = this.unmarshallMessage(new ByteArrayInputStream(base64DecodedMessage));
SAML2Utils.logProtocolMessage(xmlObject);
final SAMLObject inboundMessage;
if (xmlObject instanceof Envelope soapMessage) {
messageContext.getSOAP11Context().setEnvelope(soapMessage);
try {
new SAMLSOAPDecoderBodyHandler().invoke(messageContext.getMessageContext());
} catch (final MessageHandlerException e) {
throw new MessageDecodingException("Cannot decode SOAP envelope", e);
}
} else {
inboundMessage = (SAMLObject) xmlObject;
messageContext.getMessageContext().setMessage(inboundMessage);
}
LOGGER.debug("Decoded SAML message");
this.populateBindingContext(messageContext);
this.setMessageContext(messageContext.getMessageContext());
} else {
throw new MessageDecodingException("This message decoder only supports the HTTP POST method");
}
| 239
| 379
| 618
|
<methods>public non-sealed void <init>() ,public abstract java.lang.String getBindingURI(org.pac4j.saml.context.SAML2MessageContext) ,public void setParserPool(net.shibboleth.shared.xml.ParserPool) <variables>static final java.lang.String[] SAML_PARAMETERS,protected final non-sealed CallContext callContext,protected net.shibboleth.shared.xml.ParserPool parserPool
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/transport/Pac4jHTTPPostSimpleSignEncoder.java
|
Pac4jHTTPPostSimpleSignEncoder
|
postEncode
|
class Pac4jHTTPPostSimpleSignEncoder extends HTTPPostSimpleSignEncoder {
private final Pac4jSAMLResponse responseAdapter;
/**
* <p>Constructor for Pac4jHTTPPostSimpleSignEncoder.</p>
*
* @param responseAdapter a {@link Pac4jSAMLResponse} object
*/
public Pac4jHTTPPostSimpleSignEncoder(final Pac4jSAMLResponse responseAdapter) {
this.responseAdapter = responseAdapter;
setVelocityTemplateId(DEFAULT_TEMPLATE_ID);
}
/**
* {@inheritDoc}
*
* Gets the response URL from the message context.
*/
@Override
protected URI getEndpointURL(final MessageContext messageContext) throws MessageEncodingException {
try {
return SAMLBindingSupport.getEndpointURL(messageContext);
} catch (final BindingException e) {
throw new MessageEncodingException("Could not obtain message endpoint URL", e);
}
}
/** {@inheritDoc} */
@Override
protected void postEncode(final MessageContext messageContext, final String endpointURL) throws MessageEncodingException {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*
* Check component attributes. Copy/Paste parents initialization (no super.doInitialize) except for
* AbstractHttpServletResponseMessageEncoder since HttpServletResponse is always null.
*/
@Override
protected void doInitialize() throws ComponentInitializationException {
LOGGER.debug("Initialized {}", this.getClass().getSimpleName());
if (getMessageContext() == null) {
throw new ComponentInitializationException("Message context cannot be null");
}
if (getVelocityEngine() == null) {
throw new ComponentInitializationException("VelocityEngine must be supplied");
}
if (getVelocityTemplateId() == null) {
throw new ComponentInitializationException("Velocity template id must be supplied");
}
}
}
|
LOGGER.debug("Invoking Velocity template to create POST body");
try {
val velocityContext = new VelocityContext();
this.populateVelocityContext(velocityContext, messageContext, endpointURL);
responseAdapter.setContentType("text/html");
responseAdapter.init();
val out = responseAdapter.getOutputStreamWriter();
this.getVelocityEngine().mergeTemplate(this.getVelocityTemplateId(), "UTF-8", velocityContext, out);
out.flush();
} catch (final Exception e) {
throw new MessageEncodingException("Error creating output document", e);
}
| 497
| 157
| 654
|
<methods>public void <init>() ,public java.lang.String getBindingURI() <variables>static final boolean $assertionsDisabled,public static final java.lang.String DEFAULT_TEMPLATE_ID,private final org.slf4j.Logger log
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/transport/Pac4jHTTPRedirectDeflateDecoder.java
|
Pac4jHTTPRedirectDeflateDecoder
|
inflate
|
class Pac4jHTTPRedirectDeflateDecoder extends AbstractPac4jDecoder {
/**
* <p>Constructor for Pac4jHTTPRedirectDeflateDecoder.</p>
*
* @param context a {@link CallContext} object
*/
public Pac4jHTTPRedirectDeflateDecoder(final CallContext context) {
super(context);
}
/** {@inheritDoc} */
@Override
protected void doDecode() throws MessageDecodingException {
val messageContext = new SAML2MessageContext(callContext);
if (WebContextHelper.isGet(callContext.webContext())) {
val relayState = this.callContext.webContext().getRequestParameter("RelayState").orElse(null);
LOGGER.debug("Decoded SAML relay state of: {}", relayState);
SAMLBindingSupport.setRelayState(messageContext.getMessageContext(), relayState);
val base64DecodedMessage = this.getBase64DecodedMessage();
val inflatedMessage = inflate(base64DecodedMessage);
XMLObject inboundMessage = (SAMLObject) this.unmarshallMessage(inflatedMessage);
SAML2Utils.logProtocolMessage(inboundMessage);
messageContext.getMessageContext().setMessage(inboundMessage);
LOGGER.debug("Decoded SAML message");
this.populateBindingContext(messageContext);
this.setMessageContext(messageContext.getMessageContext());
} else {
throw new MessageDecodingException("This message decoder only supports the HTTP-Redirect method");
}
}
/**
* <p>inflate.</p>
*
* @param input an array of {@link byte} objects
* @return a {@link InputStream} object
* @throws MessageDecodingException if any.
*/
protected InputStream inflate(final byte[] input) throws MessageDecodingException {<FILL_FUNCTION_BODY>}
/**
* <p>internalInflate.</p>
*
* @param input an array of {@link byte} objects
* @param inflater a {@link Inflater} object
* @return a {@link InputStream} object
* @throws IOException if any.
*/
protected InputStream internalInflate(final byte[] input, final Inflater inflater) throws IOException {
val baos = new ByteArrayOutputStream();
val iis = new InflaterInputStream(new ByteArrayInputStream(input), inflater);
try {
val buffer = new byte[1000];
int length;
while ((length = iis.read(buffer)) > 0) {
baos.write(buffer, 0, length);
}
val decodedBytes = baos.toByteArray();
val decodedMessage = new String(decodedBytes, StandardCharsets.UTF_8);
LOGGER.debug("Inflated SAML message: {}", decodedMessage);
return new ByteArrayInputStream(decodedBytes);
} finally {
baos.close();
iis.close();
}
}
/** {@inheritDoc} */
@Override
public String getBindingURI(final SAML2MessageContext messageContext) {
return SAMLConstants.SAML2_REDIRECT_BINDING_URI;
}
}
|
try {
// compatible with GZIP and PKZIP
return internalInflate(input, new Inflater(true));
} catch (final IOException e) {
try {
// deflate compression only
return internalInflate(input, new Inflater());
} catch (final IOException e2) {
LOGGER.warn("Cannot inflate message, returning it as is");
return new ByteArrayInputStream(input);
}
}
| 834
| 116
| 950
|
<methods>public non-sealed void <init>() ,public abstract java.lang.String getBindingURI(org.pac4j.saml.context.SAML2MessageContext) ,public void setParserPool(net.shibboleth.shared.xml.ParserPool) <variables>static final java.lang.String[] SAML_PARAMETERS,protected final non-sealed CallContext callContext,protected net.shibboleth.shared.xml.ParserPool parserPool
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/util/Configuration.java
|
Configuration
|
deserializeSamlObject
|
class Configuration {
private Configuration() {
}
static {
LOGGER.info("Bootstrapping OpenSAML configuration via Pac4j...");
bootstrap();
}
private static void bootstrap() {
var configurationManagers = ServiceLoader.load(ConfigurationManager.class, Configuration.class.getClassLoader());
if (configurationManagers.findFirst().isEmpty())
configurationManagers = ServiceLoader.load(ConfigurationManager.class);
final List<ConfigurationManager> configurationManagerList = new ArrayList<>();
configurationManagers.forEach(configurationManagerList::add);
if (!configurationManagerList.isEmpty()) {
configurationManagerList.sort(FrameworkAdapter.INSTANCE::compareManagers);
configurationManagerList.get(0).configure();
}
}
/**
* <p>getParserPool.</p>
*
* @return a {@link ParserPool} object
*/
public static ParserPool getParserPool() {
return XMLObjectProviderRegistrySupport.getParserPool();
}
/**
* <p>getBuilderFactory.</p>
*
* @return a {@link XMLObjectBuilderFactory} object
*/
public static XMLObjectBuilderFactory getBuilderFactory() {
return XMLObjectProviderRegistrySupport.getBuilderFactory();
}
/**
* <p>getMarshallerFactory.</p>
*
* @return a {@link MarshallerFactory} object
*/
public static MarshallerFactory getMarshallerFactory() {
return XMLObjectProviderRegistrySupport.getMarshallerFactory();
}
/**
* <p>getUnmarshallerFactory.</p>
*
* @return a {@link UnmarshallerFactory} object
*/
public static UnmarshallerFactory getUnmarshallerFactory() {
return XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
}
/**
* <p>serializeSamlObject.</p>
*
* @param samlObject a {@link XMLObject} object
* @return a {@link StringWriter} object
*/
public static StringWriter serializeSamlObject(final XMLObject samlObject) {
val writer = new StringWriter();
try {
val marshaller = getMarshallerFactory().getMarshaller(samlObject.getElementQName());
if (marshaller != null) {
val element = marshaller.marshall(samlObject);
Source domSource = new DOMSource(element);
Result result = new StreamResult(writer);
val tf = TransformerFactory.newInstance();
val transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(domSource, result);
}
} catch (final Exception e) {
throw new SAMLException(e.getMessage(), e);
}
return writer;
}
/**
* <p>deserializeSamlObject.</p>
*
* @param obj a {@link String} object
* @return a {@link Optional} object
*/
public static Optional<XMLObject> deserializeSamlObject(final String obj) {<FILL_FUNCTION_BODY>}
}
|
try (val reader = new StringReader(obj)) {
return Optional.of(XMLObjectSupport.unmarshallFromReader(Configuration.getParserPool(), reader));
} catch (final Exception e) {
LOGGER.error("Error unmarshalling message from input stream", e);
return Optional.empty();
}
| 839
| 81
| 920
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/util/DefaultConfigurationManager.java
|
DefaultConfigurationManager
|
initParserPool
|
class DefaultConfigurationManager implements ConfigurationManager {
/** {@inheritDoc} */
@Override
public void configure() {
XMLObjectProviderRegistry registry;
synchronized (ConfigurationService.class) {
registry = ConfigurationService.get(XMLObjectProviderRegistry.class);
if (registry == null) {
registry = new XMLObjectProviderRegistry();
ConfigurationService.register(XMLObjectProviderRegistry.class, registry);
}
}
try {
InitializationService.initialize();
} catch (final InitializationException e) {
throw new RuntimeException("Exception initializing OpenSAML", e);
}
val parserPool = initParserPool();
registry.setParserPool(parserPool);
}
private static ParserPool initParserPool() {<FILL_FUNCTION_BODY>}
}
|
try {
val parserPool = new BasicParserPool();
parserPool.setMaxPoolSize(100);
parserPool.setCoalescing(true);
parserPool.setIgnoreComments(true);
parserPool.setNamespaceAware(true);
parserPool.setExpandEntityReferences(false);
parserPool.setXincludeAware(false);
parserPool.setIgnoreElementContentWhitespace(true);
final Map<String, Object> builderAttributes = new HashMap<>();
parserPool.setBuilderAttributes(builderAttributes);
final Map<String, Boolean> features = new HashMap<>();
features.put("http://apache.org/xml/features/disallow-doctype-decl", Boolean.TRUE);
features.put("http://apache.org/xml/features/validation/schema/normalized-value", Boolean.FALSE);
features.put("http://javax.xml.XMLConstants/feature/secure-processing", Boolean.TRUE);
features.put("http://xml.org/sax/features/external-general-entities", Boolean.FALSE);
features.put("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);
parserPool.setBuilderFeatures(features);
parserPool.initialize();
return parserPool;
} catch (final ComponentInitializationException e) {
throw new RuntimeException("Exception initializing parserPool", e);
}
| 203
| 356
| 559
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/util/SAML2HttpClientBuilder.java
|
SAML2HttpClientBuilder
|
build
|
class SAML2HttpClientBuilder {
private Duration connectionTimeout;
private Duration socketTimeout;
private boolean useSystemProperties;
private boolean followRedirects;
private boolean closeConnectionAfterResponse = true;
private int maxConnectionsTotal = 3;
private CredentialsProvider credentialsProvider;
/**
* <p>build.</p>
*
* @return a {@link HttpClient} object
*/
public HttpClient build() {<FILL_FUNCTION_BODY>}
@RequiredArgsConstructor
private static class Pac4jHttpClientBuilder extends HttpClientBuilder {
private final CredentialsProvider credentialsProvider;
@Override
protected CredentialsProvider buildDefaultCredentialsProvider() {
if (credentialsProvider != null) {
return credentialsProvider;
}
return super.buildDefaultCredentialsProvider();
}
}
}
|
try {
val builder = new Pac4jHttpClientBuilder(credentialsProvider);
builder.resetDefaults();
if (this.connectionTimeout != null) {
builder.setConnectionTimeout(this.connectionTimeout);
}
builder.setUseSystemProperties(this.useSystemProperties);
if (this.socketTimeout != null) {
builder.setSocketTimeout(this.socketTimeout);
}
builder.setHttpFollowRedirects(this.followRedirects);
builder.setMaxConnectionsTotal(this.maxConnectionsTotal);
builder.setConnectionCloseAfterResponse(this.closeConnectionAfterResponse);
return builder.buildClient();
} catch (final Exception e) {
throw new TechnicalException(e);
}
| 225
| 189
| 414
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/util/SAML2Utils.java
|
SAML2Utils
|
buildChainingMetadataResolver
|
class SAML2Utils implements HttpConstants {
/** SLF4J logger. */
private static final Logger protocolMessageLog = LoggerFactory.getLogger("PROTOCOL_MESSAGE");
/**
* Private constructor, to prevent instantiation of this utility class.
*/
private SAML2Utils() {
super();
}
/**
* <p>generateID.</p>
*
* @return a {@link String} object
*/
public static String generateID() {
return "_".concat(CommonHelper.randomString(39)).toLowerCase();
}
/**
* Compares two URIs for equality, ignoring default port numbers for selected protocols.
*
* By default, {@link URI#equals(Object)} doesn't take into account default port numbers,
* so http://server:80/resource is a different URI than http://server/resource.
*
* And URLs should not be used for comparison, as written here:
* http://stackoverflow.com/questions/3771081/proper-way-to-check-for-url-equality
*
* @param uri1
* URI 1 to be compared.
* @param uri2
* URI 2 to be compared.
* @return True if both URIs are equal.
*/
public static boolean urisEqualAfterPortNormalization(final URI uri1, final URI uri2) {
if (uri1 == null && uri2 == null) {
return true;
}
if (uri1 == null || uri2 == null) {
return false;
}
try {
val normalizedUri1 = normalizePortNumbersInUri(uri1);
val normalizedUri2 = normalizePortNumbersInUri(uri2);
val eq = normalizedUri1.equals(normalizedUri2);
return eq;
} catch (final URISyntaxException use) {
LOGGER.error("Cannot compare 2 URIs.", use);
return false;
}
}
/**
* Normalizes a URI. If it contains the default port for the used scheme, the method replaces the port with "default".
*
* @param uri
* The URI to normalize.
*
* @return A normalized URI.
*
* @throws URISyntaxException
* If a URI cannot be created because of wrong syntax.
*/
private static URI normalizePortNumbersInUri(final URI uri) throws URISyntaxException {
var port = uri.getPort();
val scheme = uri.getScheme();
if (SCHEME_HTTP.equals(scheme) && port == DEFAULT_HTTP_PORT) {
port = -1;
}
if (SCHEME_HTTPS.equals(scheme) && port == DEFAULT_HTTPS_PORT) {
port = -1;
}
val result = new URI(scheme, uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(), uri.getFragment());
return result;
}
/**
* <p>buildChainingMetadataResolver.</p>
*
* @param idpMetadataProvider a {@link SAML2MetadataResolver} object
* @param spMetadataProvider a {@link SAML2MetadataResolver} object
* @return a {@link ChainingMetadataResolver} object
*/
public static ChainingMetadataResolver buildChainingMetadataResolver(final SAML2MetadataResolver idpMetadataProvider,
final SAML2MetadataResolver spMetadataProvider) {<FILL_FUNCTION_BODY>}
/**
* <p>logProtocolMessage.</p>
*
* @param object a {@link XMLObject} object
*/
public static void logProtocolMessage(final XMLObject object) {
if (protocolMessageLog.isDebugEnabled()) {
try {
val requestXml = SerializeSupport.nodeToString(XMLObjectSupport.marshall(object));
protocolMessageLog.debug(requestXml);
} catch (final MarshallingException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
|
val metadataManager = new ChainingMetadataResolver();
metadataManager.setId(ChainingMetadataResolver.class.getCanonicalName());
try {
final List<MetadataResolver> list = new ArrayList<>();
list.add(idpMetadataProvider.resolve());
list.add(spMetadataProvider.resolve());
metadataManager.setResolvers(list);
metadataManager.initialize();
} catch (final ResolverException e) {
throw new TechnicalException("Error adding idp or sp metadatas to manager", e);
} catch (final ComponentInitializationException e) {
throw new TechnicalException("Error initializing manager", e);
}
return metadataManager;
| 1,043
| 167
| 1,210
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-saml/src/main/java/org/pac4j/saml/util/VelocityEngineFactory.java
|
VelocityEngineFactory
|
getEngine
|
class VelocityEngineFactory {
/**
* <p>getEngine.</p>
*
* @return a {@link VelocityEngine} object
*/
public static VelocityEngine getEngine() {<FILL_FUNCTION_BODY>}
}
|
try {
val props = new Properties();
props.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8");
props.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
props.setProperty("resource.loader.string.class", StringResourceLoader.class.getName());
props.setProperty("resource.loader.classpath.class", ClasspathResourceLoader.class.getName());
props.setProperty(RuntimeConstants.RESOURCE_LOADERS, "classpath,string");
val engine = new VelocityEngine();
engine.init(props);
return engine;
} catch (final Exception e) {
throw new TechnicalException("Error configuring velocity", e);
}
| 69
| 182
| 251
|
<no_super_class>
|
pac4j_pac4j
|
pac4j/pac4j-sql/src/main/java/org/pac4j/sql/profile/service/DbProfileService.java
|
DbProfileService
|
buildAttributesList
|
class DbProfileService extends AbstractProfileService<DbProfile> {
protected DBI dbi;
private String usersTable = "users";
@Setter
private DataSource dataSource;
/**
* <p>Constructor for DbProfileService.</p>
*/
public DbProfileService() {}
/**
* <p>Constructor for DbProfileService.</p>
*
* @param dataSource a DataSource object
*/
public DbProfileService(final DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* <p>Constructor for DbProfileService.</p>
*
* @param dataSource a DataSource object
* @param attributes a {@link String} object
*/
public DbProfileService(final DataSource dataSource, final String attributes) {
this.dataSource = dataSource;
setAttributes(attributes);
}
/**
* <p>Constructor for DbProfileService.</p>
*
* @param dataSource a DataSource object
* @param attributes a {@link String} object
* @param passwordEncoder a {@link PasswordEncoder} object
*/
public DbProfileService(final DataSource dataSource, final String attributes, final PasswordEncoder passwordEncoder) {
this.dataSource = dataSource;
setAttributes(attributes);
setPasswordEncoder(passwordEncoder);
}
/**
* <p>Constructor for DbProfileService.</p>
*
* @param dataSource a DataSource object
* @param passwordEncoder a {@link PasswordEncoder} object
*/
public DbProfileService(final DataSource dataSource, final PasswordEncoder passwordEncoder) {
this.dataSource = dataSource;
setPasswordEncoder(passwordEncoder);
}
/** {@inheritDoc} */
@Override
protected void internalInit(final boolean forceReinit) {
assertNotNull("passwordEncoder", getPasswordEncoder());
assertNotNull("dataSource", this.dataSource);
this.dbi = new DBI(this.dataSource);
setProfileDefinitionIfUndefined(new CommonProfileDefinition(x -> new DbProfile()));
setSerializer(new JsonSerializer(DbProfile.class));
super.internalInit(forceReinit);
}
/** {@inheritDoc} */
@Override
protected void insert(final Map<String, Object> attributes) {
final List<String> names = new ArrayList<>();
final List<String> questionMarks = new ArrayList<>();
final Collection<Object> values = new ArrayList<>();
for (val entry : attributes.entrySet()) {
names.add(entry.getKey());
questionMarks.add("?");
values.add(entry.getValue());
}
val query = "insert into " + usersTable + " (" + buildAttributesList(names) + ") values ("
+ buildAttributesList(questionMarks) + ")";
execute(query, values.toArray());
}
/** {@inheritDoc} */
@Override
protected void update(final Map<String, Object> attributes) {
val attributesList = new StringBuilder();
String id = null;
final Collection<Object> values = new ArrayList<>();
var i = 0;
for (val entry : attributes.entrySet()) {
val name = entry.getKey();
val value = entry.getValue();
if (ID.equals(name)) {
id = (String) value;
} else {
if (i > 0) {
attributesList.append(",");
}
attributesList.append(name);
attributesList.append("= :");
attributesList.append(name);
values.add(value);
i++;
}
}
assertNotNull(ID, id);
values.add(id);
val query = "update " + usersTable + " set " + attributesList.toString() + " where " + getIdAttribute() + " = :id";
execute(query, values.toArray());
}
/** {@inheritDoc} */
@Override
protected void deleteById(final String id) {
val query = "delete from " + usersTable + " where " + getIdAttribute() + " = :id";
execute(query, id);
}
/**
* <p>execute.</p>
*
* @param query a {@link String} object
* @param args a {@link Object} object
*/
protected void execute(final String query, final Object... args) {
Handle h = null;
try {
h = dbi.open();
logger.debug("Execute query: {} and values: {}", query, args);
h.execute(query, args);
} finally {
if (h != null) {
h.close();
}
}
}
/** {@inheritDoc} */
@Override
protected List<Map<String, Object>> read(final List<String> names, final String key, final String value) {
val attributesList = buildAttributesList(names);
val query = "select " + attributesList + " from " + usersTable + " where " + key + " = :" + key;
return query(query, key, value);
}
/**
* <p>query.</p>
*
* @param query a {@link String} object
* @param key a {@link String} object
* @param value a {@link String} object
* @return a {@link List} object
*/
protected List<Map<String, Object>> query(final String query, final String key, final String value) {
Handle h = null;
try {
h = dbi.open();
logger.debug("Query: {} for key/value: {} / {}", query, key, value);
return h.createQuery(query).bind(key, value).list(2);
} finally {
if (h != null) {
h.close();
}
}
}
/**
* <p>buildAttributesList.</p>
*
* @param names a {@link List} object
* @return a {@link String} object
*/
protected String buildAttributesList(final Iterable<String> names) {<FILL_FUNCTION_BODY>}
/**
* <p>Setter for the field <code>usersTable</code>.</p>
*
* @param usersTable a {@link String} object
*/
public void setUsersTable(final String usersTable) {
assertNotBlank("usersTable", usersTable);
this.usersTable = usersTable;
}
}
|
val sb = new StringBuilder();
var firstOne = true;
for (val name : names) {
if (!firstOne) {
sb.append(",");
}
sb.append(name);
firstOne = false;
}
return sb.toString();
| 1,680
| 74
| 1,754
|
<methods>public non-sealed void <init>() ,public void create(org.pac4j.sql.profile.DbProfile, java.lang.String) ,public org.pac4j.sql.profile.DbProfile findById(java.lang.String) ,public org.pac4j.sql.profile.DbProfile findByLinkedId(java.lang.String) ,public void remove(org.pac4j.sql.profile.DbProfile) ,public void removeById(java.lang.String) ,public void update(org.pac4j.sql.profile.DbProfile, java.lang.String) ,public Optional<org.pac4j.core.credentials.Credentials> validate(CallContext, org.pac4j.core.credentials.Credentials) <variables>public static final java.lang.String ID,public static final java.lang.String LINKEDID,public static final java.lang.String SERIALIZED_PROFILE,protected java.lang.String[] attributeNames,private java.lang.String attributes,private java.lang.String idAttribute,protected final org.slf4j.Logger logger,private java.lang.String passwordAttribute,private org.pac4j.core.credentials.password.PasswordEncoder passwordEncoder,private org.pac4j.core.util.serializer.Serializer serializer,private java.lang.String usernameAttribute
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/colorpane/CSArrayBased.java
|
CSArrayBased
|
initUI
|
class CSArrayBased
{
private JPanel panel;
private PDColorSpace colorSpace = null;
private int numberOfComponents = 0;
private String errmsg = "";
public CSArrayBased(COSArray array)
{
try
{
colorSpace = PDColorSpace.create(array);
if (!(colorSpace instanceof PDPattern))
{
numberOfComponents = colorSpace.getNumberOfComponents();
}
}
catch (IOException ex)
{
errmsg = ex.getMessage();
}
initUI();
}
private void initUI()
{<FILL_FUNCTION_BODY>}
/**
* return the main panel that hold all the UI elements.
*
* @return JPanel instance
*/
public Component getPanel()
{
return panel;
}
}
|
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setPreferredSize(new Dimension(300, 500));
if (colorSpace == null)
{
JLabel error = new JLabel(errmsg);
error.setAlignmentX(Component.CENTER_ALIGNMENT);
error.setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));
panel.add(error);
return;
}
JLabel colorSpaceLabel = new JLabel(colorSpace.getName() + " colorspace");
colorSpaceLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
colorSpaceLabel.setFont(new Font(Font.MONOSPACED, Font.BOLD, 30));
panel.add(colorSpaceLabel);
if (numberOfComponents > 0)
{
JLabel colorCountLabel = new JLabel("Component Count: " + numberOfComponents);
colorCountLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
colorCountLabel.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
panel.add(colorCountLabel);
}
if (colorSpace instanceof PDICCBased)
{
PDICCBased icc = (PDICCBased) colorSpace;
int colorSpaceType = icc.getColorSpaceType();
String cs;
switch (colorSpaceType)
{
case ColorSpace.CS_LINEAR_RGB:
cs = "linear RGB";
break;
case ColorSpace.CS_CIEXYZ:
cs = "CIEXYZ";
break;
case ColorSpace.CS_GRAY:
cs = "linear gray";
break;
case ColorSpace.CS_sRGB:
cs = "sRGB";
break;
case ColorSpace.TYPE_RGB:
cs = "RGB";
break;
case ColorSpace.TYPE_GRAY:
cs = "gray";
break;
case ColorSpace.TYPE_CMYK:
cs = "CMYK";
break;
default:
cs = "type " + colorSpaceType;
break;
}
JLabel otherLabel = new JLabel("Colorspace type: " + cs);
otherLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
otherLabel.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
panel.add(otherLabel);
}
| 224
| 676
| 900
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/colorpane/CSDeviceN.java
|
CSDeviceN
|
getColorantData
|
class CSDeviceN
{
private final PDDeviceN deviceN;
private JPanel panel;
/**
* Constructor
*
* @param array COSArray instance that holds the DeviceN color space
*
* @throws IOException if the instance could not be created
*/
public CSDeviceN(COSArray array) throws IOException
{
deviceN = new PDDeviceN(array);
DeviceNColorant[] colorants = getColorantData();
initUI(colorants);
}
/**
* Parses the colorant data from the array.
*
* @return the parsed colorants.
* @throws java.io.IOException if the color conversion fails.
*/
private DeviceNColorant[] getColorantData() throws IOException
{<FILL_FUNCTION_BODY>}
private void initUI(DeviceNColorant[] colorants)
{
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setPreferredSize(new Dimension(300, 500));
JLabel colorSpaceLabel = new JLabel("DeviceN colorspace");
colorSpaceLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
colorSpaceLabel.setFont(new Font(Font.MONOSPACED, Font.BOLD, 30));
DeviceNTableModel tableModel = new DeviceNTableModel(colorants);
JTable table = new JTable(tableModel);
table.setDefaultRenderer(Color.class, new ColorBarCellRenderer());
table.setRowHeight(60);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(table);
panel.add(colorSpaceLabel);
panel.add(scrollPane);
}
/**
* return the main panel that hold all the UI elements.
*
* @return JPanel instance
*/
public Component getPanel()
{
return panel;
}
private Color getColorObj(float[] rgbValues)
{
return new Color(rgbValues[0], rgbValues[1], rgbValues[2]);
}
}
|
List<String> colorantNames = deviceN.getColorantNames();
int componentCount = colorantNames.size();
DeviceNColorant[] colorants = new DeviceNColorant[componentCount];
for (int i = 0; i < componentCount; i++)
{
DeviceNColorant colorant = new DeviceNColorant();
colorant.setName(colorantNames.get(i));
float[] maximum = new float[componentCount];
float[] minimum = new float[componentCount];
maximum[i] = 1;
colorant.setMaximum(getColorObj(deviceN.toRGB(maximum)));
colorant.setMinimum(getColorObj(deviceN.toRGB(minimum)));
colorants[i] = colorant;
}
return colorants;
| 560
| 201
| 761
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/colorpane/CSIndexed.java
|
CSIndexed
|
initUI
|
class CSIndexed
{
private final PDIndexed indexed;
private JPanel panel;
private final int colorCount;
/**
* Constructor.
*
* @param array COSArray instance for Indexed color space.
* @throws IOException if the instance could not be created
*/
public CSIndexed(COSArray array) throws IOException
{
indexed = new PDIndexed(array);
colorCount = getHival(array) + 1;
initUI(getColorantData());
}
/**
* Parses the colorant data from the array and return.
*
* @return
*/
private IndexedColorant[] getColorantData()
{
IndexedColorant[] colorants = new IndexedColorant[colorCount];
for (int i = 0; i < colorCount; i++)
{
IndexedColorant colorant = new IndexedColorant();
colorant.setIndex(i);
float[] rgbValues = indexed.toRGB(new float[]{i});
colorant.setRgbValues(rgbValues);
colorants[i] = colorant;
}
return colorants;
}
private void initUI(IndexedColorant[] colorants)
{<FILL_FUNCTION_BODY>}
/**
* return the main panel that hold all the UI elements.
*
* @return JPanel instance
*/
public Component getPanel()
{
return panel;
}
private int getHival(COSArray array)
{
int hival = ((COSNumber) array.getObject(2).getCOSObject()).intValue();
return Math.min(hival, 255);
}
}
|
panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setPreferredSize(new Dimension(300, 500));
JLabel colorSpaceLabel = new JLabel("Indexed colorspace");
colorSpaceLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
colorSpaceLabel.setFont(new Font(Font.MONOSPACED, Font.BOLD, 30));
JPanel colorspaceLabelPanel = new JPanel();
colorspaceLabelPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
colorspaceLabelPanel.add(colorSpaceLabel);
JLabel colorCountLabel = new JLabel(" Total Color Count: " + colorCount);
colorCountLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
colorCountLabel.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
IndexedTableModel tableModel = new IndexedTableModel(colorants);
JTable table = new JTable(tableModel);
table.setDefaultRenderer(Color.class, new ColorBarCellRenderer());
table.setRowHeight(40);
table.getColumnModel().getColumn(0).setMinWidth(30);
table.getColumnModel().getColumn(0).setMaxWidth(50);
table.getColumnModel().getColumn(1).setMinWidth(100);
table.getColumnModel().getColumn(1).setMaxWidth(100);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(table);
scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
Box box = Box.createVerticalBox();
box.add(colorCountLabel);
box.add(scrollPane);
box.setAlignmentX(Component.LEFT_ALIGNMENT);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0.05;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.PAGE_START;
panel.add(colorspaceLabelPanel, gbc);
gbc.gridy = 2;
gbc.weighty=0.9;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.BELOW_BASELINE;
panel.add(box, gbc);
| 449
| 655
| 1,104
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/colorpane/ColorBarCellRenderer.java
|
ColorBarCellRenderer
|
getTableCellRendererComponent
|
class ColorBarCellRenderer implements TableCellRenderer
{
@Override
public Component getTableCellRendererComponent(
JTable jTable, Object o, boolean b, boolean b2, int i, int i2)
{<FILL_FUNCTION_BODY>}
}
|
JLabel colorBar = new JLabel();
colorBar.setOpaque(true);
colorBar.setBackground((Color) o);
return colorBar;
| 67
| 44
| 111
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/colorpane/DeviceNTableModel.java
|
DeviceNTableModel
|
getValueAt
|
class DeviceNTableModel extends AbstractTableModel
{
private static final String[] COLUMNNAMES = { "Colorant", "Maximum", "Minimum"};
private final DeviceNColorant[] data;
/**
* Constructor
* @param colorants array of DeviceNColorant
*/
public DeviceNTableModel(DeviceNColorant[] colorants)
{
data = colorants;
}
@Override
public int getRowCount()
{
return data.length;
}
@Override
public int getColumnCount()
{
return COLUMNNAMES.length;
}
@Override
public Object getValueAt(int row, int column)
{<FILL_FUNCTION_BODY>}
@Override
public String getColumnName(int column)
{
return COLUMNNAMES[column];
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
switch (columnIndex)
{
case 0:
return String.class;
case 1:
case 2:
return Color.class;
default:
return null;
}
}
}
|
switch (column)
{
case 0:
return data[row].getName();
case 1:
return data[row].getMaximum();
case 2:
return data[row].getMinimum();
default:
return null;
}
| 306
| 73
| 379
|
<methods>public void addTableModelListener(javax.swing.event.TableModelListener) ,public int findColumn(java.lang.String) ,public void fireTableCellUpdated(int, int) ,public void fireTableChanged(javax.swing.event.TableModelEvent) ,public void fireTableDataChanged() ,public void fireTableRowsDeleted(int, int) ,public void fireTableRowsInserted(int, int) ,public void fireTableRowsUpdated(int, int) ,public void fireTableStructureChanged() ,public Class<?> getColumnClass(int) ,public java.lang.String getColumnName(int) ,public T[] getListeners(Class<T>) ,public javax.swing.event.TableModelListener[] getTableModelListeners() ,public boolean isCellEditable(int, int) ,public void removeTableModelListener(javax.swing.event.TableModelListener) ,public void setValueAt(java.lang.Object, int, int) <variables>protected javax.swing.event.EventListenerList listenerList
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/colorpane/IndexedColorant.java
|
IndexedColorant
|
getRGBValuesString
|
class IndexedColorant
{
private int index;
private float[] rgbValues;
/**
* Constructor.
*/
public IndexedColorant(){}
public int getIndex()
{
return index;
}
public void setIndex(int index)
{
this.index = index;
}
public void setRgbValues(float[] rgbValues)
{
this.rgbValues = rgbValues;
}
public Color getColor()
{
return new Color(rgbValues[0], rgbValues[1], rgbValues[2]);
}
public String getRGBValuesString()
{<FILL_FUNCTION_BODY>}
}
|
StringBuilder builder = new StringBuilder();
for (float i: rgbValues)
{
builder.append((int)(i*255));
builder.append(", ");
}
builder.deleteCharAt(builder.lastIndexOf(","));
return builder.toString();
| 189
| 75
| 264
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/colorpane/IndexedTableModel.java
|
IndexedTableModel
|
getValueAt
|
class IndexedTableModel extends AbstractTableModel
{
private static final String[] COLUMNSNAMES = {"Index", "RGB value", "Color"};
private final IndexedColorant[] data;
/**
* Constructor
* @param colorants array of IndexedColorant
*/
public IndexedTableModel(IndexedColorant[] colorants)
{
data = colorants;
}
@Override
public int getRowCount()
{
return data.length;
}
@Override
public int getColumnCount()
{
return COLUMNSNAMES.length;
}
@Override
public Object getValueAt(int row, int column)
{<FILL_FUNCTION_BODY>}
@Override
public String getColumnName(int column)
{
return COLUMNSNAMES[column];
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
switch (columnIndex)
{
case 0:
return Integer.class;
case 1:
return String.class;
case 2:
return Color.class;
default:
return null;
}
}
}
|
switch (column)
{
case 0:
return data[row].getIndex();
case 1:
return data[row].getRGBValuesString();
case 2:
return data[row].getColor();
default:
return null;
}
| 315
| 75
| 390
|
<methods>public void addTableModelListener(javax.swing.event.TableModelListener) ,public int findColumn(java.lang.String) ,public void fireTableCellUpdated(int, int) ,public void fireTableChanged(javax.swing.event.TableModelEvent) ,public void fireTableDataChanged() ,public void fireTableRowsDeleted(int, int) ,public void fireTableRowsInserted(int, int) ,public void fireTableRowsUpdated(int, int) ,public void fireTableStructureChanged() ,public Class<?> getColumnClass(int) ,public java.lang.String getColumnName(int) ,public T[] getListeners(Class<T>) ,public javax.swing.event.TableModelListener[] getTableModelListeners() ,public boolean isCellEditable(int, int) ,public void removeTableModelListener(javax.swing.event.TableModelListener) ,public void setValueAt(java.lang.Object, int, int) <variables>protected javax.swing.event.EventListenerList listenerList
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/flagbitspane/AnnotFlag.java
|
AnnotFlag
|
getFlagBits
|
class AnnotFlag extends Flag
{
private final COSDictionary annotDictionary;
/**
* Constructor
* @param annotDictionary COSDictionary instance
*/
AnnotFlag(COSDictionary annotDictionary)
{
this.annotDictionary = annotDictionary;
}
@Override
String getFlagType()
{
return "Annot flag";
}
@Override
String getFlagValue()
{
return "Flag value: " + annotDictionary.getInt(COSName.F);
}
@Override
Object[][] getFlagBits()
{<FILL_FUNCTION_BODY>}
}
|
PDAnnotation annotation = new PDAnnotation(annotDictionary)
{
};
return new Object[][]{
new Object[]{1, "Invisible", annotation.isInvisible()},
new Object[]{2, "Hidden", annotation.isHidden()},
new Object[]{3, "Print", annotation.isPrinted()},
new Object[]{4, "NoZoom", annotation.isNoZoom()},
new Object[]{5, "NoRotate", annotation.isNoRotate()},
new Object[]{6, "NoView", annotation.isNoView()},
new Object[]{7, "ReadOnly", annotation.isReadOnly()},
new Object[]{8, "Locked", annotation.isLocked()},
new Object[]{9, "ToggleNoView", annotation.isToggleNoView()},
new Object[]{10, "LockedContents", annotation.isLockedContents()}
};
| 169
| 225
| 394
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/flagbitspane/EncryptFlag.java
|
EncryptFlag
|
getFlagBits
|
class EncryptFlag extends Flag
{
private final COSDictionary encryptDictionary;
/**
* Constructor
* @param encryptDict COSDictionary instance.
*/
EncryptFlag(COSDictionary encryptDict)
{
encryptDictionary = encryptDict;
}
@Override
String getFlagType()
{
return "Encrypt flag";
}
@Override
String getFlagValue()
{
return "Flag value:" + encryptDictionary.getInt(COSName.P);
}
@Override
Object[][] getFlagBits()
{<FILL_FUNCTION_BODY>}
}
|
AccessPermission ap = new AccessPermission(encryptDictionary.getInt(COSName.P));
return new Object[][]{
new Object[]{3, "can print", ap.canPrint()},
new Object[]{4, "can modify", ap.canModify()},
new Object[]{5, "can extract content", ap.canExtractContent()},
new Object[]{6, "can modify annotations", ap.canModifyAnnotations()},
new Object[]{9, "can fill in form fields", ap.canFillInForm()},
new Object[]{10, "can extract for accessibility", ap.canExtractForAccessibility()},
new Object[]{11, "can assemble document", ap.canAssembleDocument()},
new Object[]{12, "can print faithful", ap.canPrintFaithful()},
};
| 175
| 205
| 380
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/flagbitspane/FieldFlag.java
|
FieldFlag
|
getChoiceFieldFlagBits
|
class FieldFlag extends Flag
{
private final COSDictionary dictionary;
/**
* Constructor
* @param dictionary COSDictionary instance
*/
FieldFlag(COSDictionary dictionary)
{
this.dictionary = dictionary;
}
@Override
String getFlagType()
{
COSName fieldType = dictionary.getCOSName(COSName.FT);
if (COSName.TX.equals(fieldType))
{
return "Text field flag";
}
else if (COSName.BTN.equals(fieldType))
{
return "Button field flag";
}
else if (COSName.CH.equals(fieldType))
{
return "Choice field flag";
}
return "Field flag";
}
@Override
String getFlagValue()
{
return "Flag value: " + dictionary.getInt(COSName.FF);
}
@Override
Object[][] getFlagBits()
{
int flagValue = dictionary.getInt(COSName.FF);
COSName fieldType = dictionary.getCOSName(COSName.FT);
if (COSName.TX.equals(fieldType))
{
return getTextFieldFlagBits(flagValue);
}
else if (COSName.BTN.equals(fieldType))
{
return getButtonFieldFlagBits(flagValue);
}
else if (COSName.CH.equals(fieldType))
{
return getChoiceFieldFlagBits(flagValue);
}
return getFieldFlagBits(flagValue);
}
private Object[][] getTextFieldFlagBits(final int flagValue)
{
return new Object[][]{
new Object[]{1, "ReadOnly", isFlagBitSet(flagValue, 1)},
new Object[]{2, "Required", isFlagBitSet(flagValue, 2)},
new Object[]{3, "NoExport", isFlagBitSet(flagValue, 3)},
new Object[]{13, "Multiline", isFlagBitSet(flagValue, 13)},
new Object[]{14, "Password", isFlagBitSet(flagValue, 14)},
new Object[]{21, "FileSelect", isFlagBitSet(flagValue, 21)},
new Object[]{23, "DoNotSpellCheck", isFlagBitSet(flagValue, 23)},
new Object[]{24, "DoNotScroll", isFlagBitSet(flagValue, 24)},
new Object[]{25, "Comb", isFlagBitSet(flagValue, 25)},
new Object[]{26, "RichText", isFlagBitSet(flagValue, 26)}
};
}
private Object[][] getButtonFieldFlagBits(final int flagValue)
{
return new Object[][]{
new Object[]{1, "ReadOnly", isFlagBitSet(flagValue, 1)},
new Object[]{2, "Required", isFlagBitSet(flagValue, 2)},
new Object[]{3, "NoExport", isFlagBitSet(flagValue, 3)},
new Object[]{15, "NoToggleToOff", isFlagBitSet(flagValue, 15)},
new Object[]{16, "Radio", isFlagBitSet(flagValue, 16)},
new Object[]{17, "Pushbutton", isFlagBitSet(flagValue, 17)},
new Object[]{26, "RadiosInUnison", isFlagBitSet(flagValue, 26)}
};
}
private Object[][] getChoiceFieldFlagBits(final int flagValue)
{<FILL_FUNCTION_BODY>}
private Object[][] getFieldFlagBits(final int flagValue)
{
return new Object[][]{
new Object[]{1, "ReadOnly", isFlagBitSet(flagValue, 1)},
new Object[]{2, "Required", isFlagBitSet(flagValue, 2)},
new Object[]{3, "NoExport", isFlagBitSet(flagValue, 3)}
};
}
/**
* Check the corresponding flag bit if set or not
* @param flagValue the flag integer
* @param bitPosition bit position to check
* @return if set return true else false
*/
private Boolean isFlagBitSet(int flagValue, int bitPosition)
{
int binaryFormat = 1 << (bitPosition - 1);
return (flagValue & binaryFormat) == binaryFormat;
}
}
|
return new Object[][]{
new Object[]{1, "ReadOnly", isFlagBitSet(flagValue, 1)},
new Object[]{2, "Required", isFlagBitSet(flagValue, 2)},
new Object[]{3, "NoExport", isFlagBitSet(flagValue, 3)},
new Object[]{18, "Combo", isFlagBitSet(flagValue, 18)},
new Object[]{19, "Edit", isFlagBitSet(flagValue, 19)},
new Object[]{20, "Sort", isFlagBitSet(flagValue, 20)},
new Object[]{22, "MultiSelect", isFlagBitSet(flagValue, 22)},
new Object[]{23, "DoNotSpellCheck", isFlagBitSet(flagValue, 23)},
new Object[]{27, "CommitOnSelChange", isFlagBitSet(flagValue, 27)}
};
| 1,131
| 227
| 1,358
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/flagbitspane/FlagBitsPane.java
|
FlagBitsPane
|
createPane
|
class FlagBitsPane
{
private FlagBitsPaneView view;
private final PDDocument document;
/**
* Constructor.
*
* @param document the current document
* @param dictionary COSDictionary instance.
* @param flagType COSName instance.
*/
public FlagBitsPane(PDDocument document, final COSDictionary dictionary, COSName flagType)
{
this.document = document;
createPane(dictionary, flagType);
}
private void createPane(final COSDictionary dictionary, final COSName flagType)
{<FILL_FUNCTION_BODY>}
/**
* Returns the Pane itself
* @return JPanel instance
*/
public JPanel getPane()
{
return view.getPanel();
}
}
|
Flag flag;
if (COSName.FLAGS.equals(flagType))
{
flag = new FontFlag(dictionary);
view = new FlagBitsPaneView(
flag.getFlagType(), flag.getFlagValue(), flag.getFlagBits(), flag.getColumnNames());
}
if (COSName.F.equals(flagType))
{
flag = new AnnotFlag(dictionary);
view = new FlagBitsPaneView(
flag.getFlagType(), flag.getFlagValue(), flag.getFlagBits(), flag.getColumnNames());
}
if (COSName.FF.equals(flagType))
{
flag = new FieldFlag(dictionary);
view = new FlagBitsPaneView(
flag.getFlagType(), flag.getFlagValue(), flag.getFlagBits(), flag.getColumnNames());
}
if (COSName.PANOSE.equals(flagType))
{
flag = new PanoseFlag(dictionary);
view = new FlagBitsPaneView(
flag.getFlagType(), flag.getFlagValue(), flag.getFlagBits(), flag.getColumnNames());
}
if (COSName.P.equals(flagType))
{
flag = new EncryptFlag(dictionary);
view = new FlagBitsPaneView(
flag.getFlagType(), flag.getFlagValue(), flag.getFlagBits(), flag.getColumnNames());
}
if (COSName.SIG_FLAGS.equals(flagType))
{
flag = new SigFlag(document, dictionary);
view = new FlagBitsPaneView(
flag.getFlagType(), flag.getFlagValue(), flag.getFlagBits(), flag.getColumnNames());
}
| 212
| 452
| 664
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/flagbitspane/FlagBitsPaneView.java
|
FlagBitsPaneView
|
createView
|
class FlagBitsPaneView
{
private final JPanel panel;
private final String flagHeader;
private final String flagValue;
private final Object[][] tableData;
private final String[] columnNames;
/**
* Constructor
* @param flagHeader String instance. Flag type.
* @param flagValue String instance. Flag integer value.
* @param tableRowData Object 2d array for table row data.
* @param columnNames String array for column names.
*/
FlagBitsPaneView(String flagHeader, String flagValue, Object[][] tableRowData, String[] columnNames)
{
this.flagHeader = flagHeader;
this.flagValue = flagValue;
this.tableData = tableRowData;
this.columnNames = columnNames;
panel = new JPanel();
if (flagValue != null && tableData != null)
{
createView();
}
}
private void createView()
{<FILL_FUNCTION_BODY>}
/**
* Returns the view.
* @return JPanel instance.
*/
JPanel getPanel()
{
return panel;
}
}
|
panel.setLayout(new GridBagLayout());
panel.setPreferredSize(new Dimension(300, 500));
JLabel flagLabel = new JLabel(flagHeader);
flagLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
flagLabel.setFont(new Font(Font.MONOSPACED, Font.BOLD, 30));
JPanel flagLabelPanel = new JPanel();
flagLabelPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
flagLabelPanel.add(flagLabel);
JLabel flagValueLabel = new JLabel(flagValue);
flagValueLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
flagValueLabel.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
JTable table = new JTable(tableData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
Box box = Box.createVerticalBox();
box.add(flagValueLabel);
box.add(scrollPane);
box.setAlignmentX(Component.LEFT_ALIGNMENT);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0.05;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.PAGE_START;
panel.add(flagLabelPanel, gbc);
gbc.gridy = 2;
gbc.weighty = 0.9;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.BELOW_BASELINE;
panel.add(box, gbc);
| 303
| 506
| 809
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/flagbitspane/FontFlag.java
|
FontFlag
|
getFlagBits
|
class FontFlag extends Flag
{
private final COSDictionary fontDescriptor;
/**
* Constructor
* @param fontDescDictionary COSDictionary instance.
*/
FontFlag(COSDictionary fontDescDictionary)
{
fontDescriptor = fontDescDictionary;
}
@Override
String getFlagType()
{
return "Font flag";
}
@Override
String getFlagValue()
{
return "Flag value:" + fontDescriptor.getInt(COSName.FLAGS);
}
@Override
Object[][] getFlagBits()
{<FILL_FUNCTION_BODY>}
}
|
PDFontDescriptor fontDesc = new PDFontDescriptor(fontDescriptor);
return new Object[][]{
new Object[]{1, "FixedPitch", fontDesc.isFixedPitch()},
new Object[]{2, "Serif", fontDesc.isSerif()},
new Object[]{3, "Symbolic", fontDesc.isSymbolic()},
new Object[]{4, "Script", fontDesc.isScript()},
new Object[]{6, "NonSymbolic", fontDesc.isNonSymbolic()},
new Object[]{7, "Italic", fontDesc.isItalic()},
new Object[]{17, "AllCap", fontDesc.isAllCap()},
new Object[]{18, "SmallCap", fontDesc.isSmallCap()},
new Object[]{19, "ForceBold", fontDesc.isForceBold()}
};
| 167
| 209
| 376
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/flagbitspane/PanoseFlag.java
|
PanoseFlag
|
getSerifStyleValue
|
class PanoseFlag extends Flag
{
private final byte[] bytes;
private final COSString byteValue;
/**
* Constructor.
* @param dictionary COSDictionary instance. style dictionary that contains panose object.
*/
public PanoseFlag(COSDictionary dictionary)
{
byteValue = (COSString)dictionary.getDictionaryObject(COSName.PANOSE);
bytes = getPanoseBytes(dictionary);
}
@Override
String getFlagType()
{
return "Panose classification";
}
@Override
String getFlagValue()
{
return "Panose byte :" + byteValue.toHexString();
}
@Override
Object[][] getFlagBits()
{
PDPanoseClassification pc = new PDPanose(bytes).getPanose();
return new Object[][]{
{2, "Family Kind", pc.getFamilyKind(), getFamilyKindValue(pc.getFamilyKind())},
{3, "Serif Style", pc.getSerifStyle(), getSerifStyleValue(pc.getSerifStyle())},
{4, "Weight", pc.getWeight(), getWeightValue(pc.getWeight())},
{5, "Proportion", pc.getProportion(), getProportionValue(pc.getProportion())},
{6, "Contrast", pc.getContrast(), getContrastValue(pc.getContrast())},
{7, "Stroke Variation", pc.getStrokeVariation(), getStrokeVariationValue(pc.getStrokeVariation())},
{8, "Arm Style", pc.getArmStyle(), getArmStyleValue(pc.getArmStyle())},
{9, "Letterform", pc.getLetterform(), getLetterformValue(pc.getLetterform())},
{10, "Midline", pc.getMidline(), getMidlineValue(pc.getMidline())},
{11, "X-height", pc.getXHeight(), getXHeightValue(pc.getXHeight())},
};
}
@Override
String[] getColumnNames()
{
return new String[] {"Byte Position", "Name", "Byte Value", "Value"};
}
private String getFamilyKindValue(int index)
{
return new String[]{
"Any",
"No Fit",
"Latin Text",
"Latin Hand Written",
"Latin Decorative",
"Latin Symbol"
}[index];
}
private String getSerifStyleValue(int index)
{<FILL_FUNCTION_BODY>}
private String getWeightValue(int index)
{
return new String[]{
"Any",
"No Fit",
"Very Light",
"Light",
"Thin",
"Book",
"Medium",
"Demi",
"Bold",
"Heavy",
"Black",
"Extra Black"
}[index];
}
private String getProportionValue(int index)
{
return new String[]{
"Any",
"No fit",
"Old Style",
"Modern",
"Even Width",
"Extended",
"Condensed",
"Very Extended",
"Very Condensed",
"Monospaced"
}[index];
}
private String getContrastValue(int index)
{
return new String[]{
"Any",
"No Fit",
"None",
"Very Low",
"Low",
"Medium Low",
"Medium",
"Medium High",
"High",
"Very High"
}[index];
}
private String getStrokeVariationValue(int index)
{
return new String[]{
"Any",
"No Fit",
"No Variation",
"Gradual/Diagonal",
"Gradual/Transitional",
"Gradual/Vertical",
"Gradual/Horizontal",
"Rapid/Vertical",
"Rapid/Horizontal",
"Instant/Vertical",
"Instant/Horizontal",
}[index];
}
private String getArmStyleValue(int index)
{
return new String[]{
"Any",
"No Fit",
"Straight Arms/Horizontal",
"Straight Arms/Wedge",
"Straight Arms/Vertical",
"Straight Arms/Single Serif",
"Straight Arms/Double Serif",
"Non-Straight/Horizontal",
"Non-Straight/Wedge",
"Non-Straight/Vertical",
"Non-Straight/Single Serif",
"Non-Straight/Double Serif",
}[index];
}
private String getLetterformValue(int index)
{
return new String[]{
"Any",
"No Fit",
"Normal/Contact",
"Normal/Weighted",
"Normal/Boxed",
"Normal/Flattened",
"Normal/Rounded",
"Normal/Off Center",
"Normal/Square",
"Oblique/Contact",
"Oblique/Weighted",
"Oblique/Boxed",
"Oblique/Flattened",
"Oblique/Rounded",
"Oblique/Off Center",
"Oblique/Square",
}[index];
}
private String getMidlineValue(int index)
{
return new String[]{
"Any",
"No Fit",
"Standard/Trimmed",
"Standard/Pointed",
"Standard/Serifed",
"High/Trimmed",
"High/Pointed",
"High/Serifed",
"Constant/Trimmed",
"Constant/Pointed",
"Constant/Serifed",
"Low/Trimmed",
"Low/Pointed",
"Low/Serifed"
}[index];
}
private String getXHeightValue(int index)
{
return new String[]{
"Any",
"No Fit",
"Constant/Small",
"Constant/Standard",
"Constant/Large",
"Ducking/Small",
"Ducking/Standard",
"Ducking/Large",
}[index];
}
public final byte[] getPanoseBytes(COSDictionary style)
{
COSString panose = (COSString)style.getDictionaryObject(COSName.PANOSE);
return panose.getBytes();
}
}
|
return new String[]{
"Any",
"No Fit",
"Cove",
"Obtuse Cove",
"Square Cove",
"Obtuse Square Cove",
"Square",
"Thin",
"Oval",
"Exaggerated",
"Triangle",
"Normal Sans",
"Obtuse Sans",
"Perpendicular Sans",
"Flared",
"Rounded"
}[index];
| 1,711
| 127
| 1,838
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/flagbitspane/SigFlag.java
|
SigFlag
|
getFlagBits
|
class SigFlag extends Flag
{
private final PDDocument document;
private final COSDictionary acroFormDictionary;
/**
* Constructor
*
* @param acroFormDictionary COSDictionary instance.
*/
SigFlag(PDDocument document, COSDictionary acroFormDictionary)
{
this.document = document;
this.acroFormDictionary = acroFormDictionary;
}
@Override
String getFlagType()
{
return "Signature flag";
}
@Override
String getFlagValue()
{
return "Flag value: " + acroFormDictionary.getInt(COSName.SIG_FLAGS);
}
@Override
Object[][] getFlagBits()
{<FILL_FUNCTION_BODY>}
}
|
PDAcroForm acroForm = new PDAcroForm(document, acroFormDictionary);
return new Object[][]{
new Object[]{1, "SignaturesExist", acroForm.isSignaturesExist()},
new Object[]{2, "AppendOnly", acroForm.isAppendOnly()},
};
| 209
| 82
| 291
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/fontencodingpane/FontEncodingPaneController.java
|
FontPane
|
getYBounds
|
class FontPane
{
abstract JPanel getPanel();
/**
* Calculate vertical bounds common to all rendered glyphs.
*
* @param tableData
* @param glyphIndex the table index that has glyphs.
* @return an array with two elements: min lower bound (but max 0), and max upper bound (but min
* 0).
*/
double[] getYBounds(Object[][] tableData, int glyphIndex)
{<FILL_FUNCTION_BODY>}
}
|
double minY = 0;
double maxY = 0;
for (Object[] aTableData : tableData)
{
GeneralPath path = (GeneralPath) aTableData[glyphIndex];
Rectangle2D bounds2D = path.getBounds2D();
if (bounds2D.isEmpty())
{
continue;
}
minY = Math.min(minY, bounds2D.getMinY());
maxY = Math.max(maxY, bounds2D.getMaxY());
}
return new double[]{minY, maxY};
| 132
| 147
| 279
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/fontencodingpane/FontEncodingView.java
|
GlyphCellRenderer
|
renderGlyph
|
class GlyphCellRenderer implements TableCellRenderer
{
private final double[] yBounds;
private GlyphCellRenderer(double[] yBounds)
{
this.yBounds = yBounds;
}
@Override
public Component getTableCellRendererComponent(JTable jTable, Object o, boolean b, boolean b1, int row, int col)
{
if (o instanceof GeneralPath)
{
GeneralPath path = (GeneralPath) o;
Rectangle2D bounds2D = path.getBounds2D();
if (bounds2D.isEmpty())
{
JLabel label = new JLabel(SimpleFont.NO_GLYPH, SwingConstants.CENTER);
int fontSize = Integer.parseInt(PDFDebugger.configuration.getProperty(
"encodingFontSize", Integer.toString(label.getFont().getSize())));
label.setFont(new Font(Font.DIALOG, Font.PLAIN, fontSize));
label.setForeground(Color.GRAY);
return label;
}
Rectangle cellRect = jTable.getCellRect(row, col, false);
BufferedImage bim = renderGlyph(path, bounds2D, cellRect);
return new JLabel(new HighResolutionImageIcon(
bim,
(int) Math.ceil(bim.getWidth() / DEFAULT_TRANSFORM.getScaleX()),
(int) Math.ceil(bim.getHeight() / DEFAULT_TRANSFORM.getScaleY())),
SwingConstants.CENTER);
}
if (o instanceof BufferedImage)
{
Rectangle cellRect = jTable.getCellRect(row, col, false);
BufferedImage glyphImage = (BufferedImage) o;
BufferedImage cellImage = new BufferedImage(
(int) (cellRect.getWidth() * DEFAULT_TRANSFORM.getScaleX()),
(int) (cellRect.getHeight() * DEFAULT_TRANSFORM.getScaleY()),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) cellImage.getGraphics();
g.setBackground(Color.white);
g.clearRect(0, 0, cellImage.getWidth(), cellImage.getHeight());
double scale = 1 / (glyphImage.getHeight() / cellRect.getHeight());
// horizontal center
g.translate((cellRect.getWidth() - glyphImage.getWidth() * scale) / 2 * DEFAULT_TRANSFORM.getScaleX(), 0);
// scale from the glyph to the cell
g.scale(scale * DEFAULT_TRANSFORM.getScaleX(), scale * DEFAULT_TRANSFORM.getScaleY());
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(glyphImage, 0, 0, null);
g.dispose();
return new JLabel(new HighResolutionImageIcon(
cellImage,
(int) Math.ceil(cellImage.getWidth() / DEFAULT_TRANSFORM.getScaleX()),
(int) Math.ceil(cellImage.getHeight() / DEFAULT_TRANSFORM.getScaleY())));
}
if (o != null)
{
JLabel label = new JLabel(o.toString(), SwingConstants.CENTER);
int fontSize = Integer.parseInt(PDFDebugger.configuration.getProperty(
"encodingFontSize", Integer.toString(label.getFont().getSize())));
label.setFont(new Font(Font.DIALOG, Font.PLAIN, fontSize));
if (SimpleFont.NO_GLYPH.equals(o) || ".notdef".equals(o))
{
label.setText(o.toString());
label.setForeground(Color.GRAY);
}
return label;
}
return new JLabel();
}
private BufferedImage renderGlyph(GeneralPath path, Rectangle2D bounds2D, Rectangle cellRect)
{<FILL_FUNCTION_BODY>}
}
|
BufferedImage bim = new BufferedImage(
(int) (cellRect.getWidth() * DEFAULT_TRANSFORM.getScaleX()),
(int) (cellRect.getHeight() * DEFAULT_TRANSFORM.getScaleY()),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bim.getGraphics();
g.setBackground(Color.white);
g.clearRect(0, 0, bim.getWidth(), bim.getHeight());
double scale = 1 / ((yBounds[1] - yBounds[0]) / cellRect.getHeight());
// flip
g.scale(1, -1);
g.translate(0, -bim.getHeight());
// horizontal center
g.translate((cellRect.getWidth() - bounds2D.getWidth() * scale) / 2 * DEFAULT_TRANSFORM.getScaleX(), 0);
// scale from the glyph to the cell
g.scale(scale * DEFAULT_TRANSFORM.getScaleX(), scale * DEFAULT_TRANSFORM.getScaleY());
// Adjust for negative y min bound
g.translate(0, -yBounds[0]);
g.setColor(Color.black);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.fill(path);
g.dispose();
return bim;
| 1,118
| 448
| 1,566
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/fontencodingpane/SimpleFont.java
|
SimpleFont
|
getGlyphs
|
class SimpleFont extends FontPane
{
private static final Logger LOG = LogManager.getLogger(SimpleFont.class);
public static final String NO_GLYPH = "None";
private final FontEncodingView view;
private int totalAvailableGlyph = 0;
/**
* Constructor.
* @param font PDSimpleFont instance, but not a type 3 font (must also be a PDVectorFont).
* @throws IOException If fails to parse unicode characters.
*/
SimpleFont(PDSimpleFont font) throws IOException
{
Object[][] tableData = getGlyphs(font);
double[] yBounds = getYBounds(tableData, 3);
Map<String, String> attributes = new LinkedHashMap<>();
attributes.put("Font", font.getName());
attributes.put("Encoding", getEncodingName(font));
attributes.put("Glyphs", Integer.toString(totalAvailableGlyph));
attributes.put("Standard 14", Boolean.toString(font.isStandard14()));
attributes.put("Embedded", Boolean.toString(font.isEmbedded()));
view = new FontEncodingView(tableData, attributes,
new String[] {"Code", "Glyph Name", "Unicode Character", "Glyph"}, yBounds);
}
private Object[][] getGlyphs(PDSimpleFont font) throws IOException
{<FILL_FUNCTION_BODY>}
private String getEncodingName(PDSimpleFont font)
{
return font.getEncoding().getClass().getSimpleName() + " / " + font.getEncoding().getEncodingName();
}
@Override
public JPanel getPanel()
{
return view.getPanel();
}
}
|
Object[][] glyphs = new Object[256][4];
for (int index = 0; index <= 255; index++)
{
glyphs[index][0] = index;
if (font.getEncoding().contains(index) || font.toUnicode(index) != null)
{
String glyphName = font.getEncoding().getName(index);
glyphs[index][1] = glyphName;
glyphs[index][2] = font.toUnicode(index);
try
{
// using names didn't work with the file from PDFBOX-3445
glyphs[index][3] = ((PDVectorFont) font).getPath(index);
}
catch (IOException ex)
{
LOG.error("Couldn't render code {} ('{}') of font {}", index, glyphName,
font.getName(), ex);
glyphs[index][3] = new GeneralPath();
}
totalAvailableGlyph++;
}
else
{
glyphs[index][1] = NO_GLYPH;
glyphs[index][2] = NO_GLYPH;
glyphs[index][3] = font.getPath(".notdef");
}
}
return glyphs;
| 433
| 333
| 766
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/fontencodingpane/Type0Font.java
|
Type0Font
|
getPanel
|
class Type0Font extends FontPane
{
public static final String NO_GLYPH = "No glyph";
private final FontEncodingView view;
private int totalAvailableGlyph = 0;
/**
* Constructor.
* @param descendantFont PDCIDFontType2 instance.
* @param parentFont PDFont instance.
* @throws IOException If fails to parse cidtogid map.
*/
Type0Font(PDCIDFont descendantFont, PDType0Font parentFont) throws IOException
{
Object[][] cidtogid = readCIDToGIDMap(descendantFont, parentFont);
if (cidtogid != null)
{
Map<String, String> attributes = new LinkedHashMap<>();
attributes.put("Font", descendantFont.getName());
attributes.put("CIDs", Integer.toString(cidtogid.length));
attributes.put("Embedded", Boolean.toString(descendantFont.isEmbedded()));
view = new FontEncodingView(cidtogid, attributes,
new String[]{"CID", "GID", "Unicode Character", "Glyph"}, getYBounds(cidtogid, 3));
}
else
{
Object[][] tab = readMap(descendantFont, parentFont);
Map<String, String> attributes = new LinkedHashMap<>();
attributes.put("Font", descendantFont.getName());
attributes.put("CIDs", Integer.toString(tab.length));
attributes.put("Glyphs", Integer.toString(totalAvailableGlyph));
attributes.put("Standard 14", Boolean.toString(parentFont.isStandard14()));
attributes.put("Embedded", Boolean.toString(descendantFont.isEmbedded()));
view = new FontEncodingView(tab, attributes,
new String[]{"Code", "CID", "GID", "Unicode Character", "Glyph"}, getYBounds(tab, 4));
}
}
private Object[][] readMap(PDCIDFont descendantFont, PDType0Font parentFont) throws IOException
{
int codes = 0;
for (int code = 0; code < 65535; ++code)
{
if (descendantFont.hasGlyph(code))
{
++codes;
}
}
Object[][] tab = new Object[codes][5];
int index = 0;
for (int code = 0; code < 65535; ++code)
{
if (descendantFont.hasGlyph(code))
{
tab[index][0] = code;
tab[index][1] = descendantFont.codeToCID(code);
tab[index][2] = descendantFont.codeToGID(code);
tab[index][3] = parentFont.toUnicode(code);
GeneralPath path = descendantFont.getPath(code);
tab[index][4] = path;
if (!path.getBounds2D().isEmpty())
{
++totalAvailableGlyph;
}
++index;
}
}
return tab;
}
private Object[][] readCIDToGIDMap(PDCIDFont font, PDFont parentFont) throws IOException
{
Object[][] cid2gid = null;
COSDictionary dict = font.getCOSObject();
COSStream stream = dict.getCOSStream(COSName.CID_TO_GID_MAP);
if (stream != null)
{
InputStream is = stream.createInputStream();
byte[] mapAsBytes = is.readAllBytes();
IOUtils.closeQuietly(is);
int numberOfInts = mapAsBytes.length / 2;
cid2gid = new Object[numberOfInts][4];
int offset = 0;
for (int index = 0; index < numberOfInts; index++)
{
int gid = (mapAsBytes[offset] & 0xff) << 8 | mapAsBytes[offset + 1] & 0xff;
cid2gid[index][0] = index;
cid2gid[index][1] = gid;
if (gid != 0 && parentFont.toUnicode(index) != null)
{
cid2gid[index][2] = parentFont.toUnicode(index);
}
GeneralPath path = font.getPath(index);
cid2gid[index][3] = path;
if (!path.getBounds2D().isEmpty())
{
++totalAvailableGlyph;
}
offset += 2;
}
}
return cid2gid;
}
@Override
public JPanel getPanel()
{<FILL_FUNCTION_BODY>}
}
|
if (view != null)
{
return view.getPanel();
}
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 500));
return panel;
| 1,216
| 63
| 1,279
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/fontencodingpane/Type3Font.java
|
Type3Font
|
renderType3Glyph
|
class Type3Font extends FontPane
{
public static final String NO_GLYPH = "No glyph";
private final FontEncodingView view;
private int totalAvailableGlyph = 0;
private PDRectangle fontBBox;
private final PDResources resources;
/**
* Constructor.
* @param font PDSimpleFont instance.
* @throws IOException If fails to parse unicode characters.
*/
Type3Font(PDType3Font font, PDResources resources) throws IOException
{
this.resources = resources;
calcBBox(font);
Object[][] tableData = getGlyphs(font);
Map<String, String> attributes = new LinkedHashMap<>();
attributes.put("Font", font.getName());
attributes.put("Encoding", getEncodingName(font));
attributes.put("Glyphs", Integer.toString(totalAvailableGlyph));
view = new FontEncodingView(tableData, attributes,
new String[] {"Code", "Glyph Name", "Unicode Character", "Glyph"}, null);
}
private void calcBBox(PDType3Font font) throws IOException
{
double minX = 0;
double maxX = 0;
double minY = 0;
double maxY = 0;
for (int index = 0; index <= 255; ++index)
{
PDType3CharProc charProc = font.getCharProc(index);
if (charProc == null)
{
continue;
}
PDRectangle glyphBBox = charProc.getGlyphBBox();
if (glyphBBox == null)
{
continue;
}
minX = Math.min(minX, glyphBBox.getLowerLeftX());
maxX = Math.max(maxX, glyphBBox.getUpperRightX());
minY = Math.min(minY, glyphBBox.getLowerLeftY());
maxY = Math.max(maxY, glyphBBox.getUpperRightY());
}
fontBBox = new PDRectangle((float) minX, (float) minY, (float) (maxX - minX), (float) (maxY - minY));
if (fontBBox.getWidth() <= 0 || fontBBox.getHeight() <= 0)
{
// less reliable, but good as a fallback solution for PDF.js issue 10717
BoundingBox boundingBox = font.getBoundingBox();
fontBBox = new PDRectangle(boundingBox.getLowerLeftX(),
boundingBox.getLowerLeftY(),
boundingBox.getWidth(),
boundingBox.getHeight());
}
}
private Object[][] getGlyphs(PDType3Font font) throws IOException
{
boolean isEmpty = fontBBox.toGeneralPath().getBounds2D().isEmpty();
Object[][] glyphs = new Object[256][4];
// map needed to lessen memory footprint for files with duplicates
// e.g. PDF.js issue 10717
Map<String, BufferedImage> map = new HashMap<>();
for (int index = 0; index <= 255; index++)
{
glyphs[index][0] = index;
if (font.getEncoding().contains(index) || font.toUnicode(index) != null)
{
String name = font.getEncoding().getName(index);
glyphs[index][1] = name;
glyphs[index][2] = font.toUnicode(index);
if (isEmpty)
{
glyphs[index][3] = NO_GLYPH;
}
else if (map.containsKey(name))
{
glyphs[index][3] = map.get(name);
}
else
{
BufferedImage image = renderType3Glyph(font, index);
map.put(name, image);
glyphs[index][3] = image;
}
totalAvailableGlyph++;
}
else
{
glyphs[index][1] = NO_GLYPH;
glyphs[index][2] = NO_GLYPH;
glyphs[index][3] = NO_GLYPH;
}
}
return glyphs;
}
// Kindof an overkill to create a PDF for one glyph, but there is no better way at this time.
// Isn't called if no bounds are available
private BufferedImage renderType3Glyph(PDType3Font font, int index) throws IOException
{<FILL_FUNCTION_BODY>}
private String getEncodingName(PDType3Font font)
{
return font.getEncoding().getClass().getSimpleName() + " / " + font.getEncoding().getEncodingName();
}
@Override
public JPanel getPanel()
{
return view.getPanel();
}
}
|
try (PDDocument doc = new PDDocument())
{
int scale = 1;
if (fontBBox.getWidth() < 72 || fontBBox.getHeight() < 72)
{
// e.g. T4 font of PDFBOX-2959
scale = (int) (72 / Math.min(fontBBox.getWidth(), fontBBox.getHeight()));
}
PDPage page = new PDPage(new PDRectangle(fontBBox.getWidth() * scale, fontBBox.getHeight() * scale));
page.setResources(resources);
try (PDPageContentStream cs = new PDPageContentStream(doc, page, AppendMode.APPEND, false))
{
// any changes here must be done carefully and each file must be tested again
// just inverting didn't work with
// https://www.treasury.gov/ofac/downloads/sdnlist.pdf (has rotated matrix)
// also test PDFBOX-4228-type3.pdf (identity matrix)
// Root/Pages/Kids/[0]/Resources/XObject/X1/Resources/XObject/X3/Resources/Font/F10
// PDFBOX-1794-vattenfall.pdf (scale 0.001)
float scalingFactorX = font.getFontMatrix().getScalingFactorX();
float scalingFactorY = font.getFontMatrix().getScalingFactorY();
float translateX = scalingFactorX > 0 ? -fontBBox.getLowerLeftX() : fontBBox.getUpperRightX();
float translateY = scalingFactorY > 0 ? -fontBBox.getLowerLeftY() : fontBBox.getUpperRightY();
cs.transform(Matrix.getTranslateInstance(translateX * scale, translateY * scale));
cs.beginText();
cs.setFont(font, scale / Math.min(Math.abs(scalingFactorX), Math.abs(scalingFactorY)));
// can't use showText() because there's no guarantee we have the unicode
cs.appendRawCommands(String.format("<%02X> Tj%n", index).getBytes(StandardCharsets.ISO_8859_1));
cs.endText();
}
doc.addPage(page);
// for debug you can save the PDF here
return new PDFRenderer(doc).renderImage(0);
}
| 1,262
| 622
| 1,884
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/hexviewer/ASCIIPane.java
|
ASCIIPane
|
paintInSelected
|
class ASCIIPane extends JComponent implements HexModelChangeListener
{
private final HexModel model;
private int selectedLine = -1;
private int selectedIndexInLine;
/**
* Constructor.
* @param model HexModel instance.
*/
ASCIIPane(HexModel model)
{
this.model = model;
setPreferredSize(new Dimension(HexView.ASCII_PANE_WIDTH, HexView.CHAR_HEIGHT * (model.totalLine()+1)));
model.addHexModelChangeListener(this);
setFont(HexView.FONT);
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHints(HexView.RENDERING_HINTS);
Rectangle bound = getVisibleRect();
int x = HexView.LINE_INSET;
int y = bound.y;
if (y == 0 || y%HexView.CHAR_HEIGHT != 0)
{
y += HexView.CHAR_HEIGHT - y%HexView.CHAR_HEIGHT;
}
int firstLine = y/HexView.CHAR_HEIGHT;
for (int line = firstLine; line < firstLine + bound.getHeight()/HexView.CHAR_HEIGHT; line++)
{
if (line > model.totalLine())
{
break;
}
if (line == selectedLine)
{
paintInSelected(g, x, y);
}
else
{
char[] chars = model.getLineChars(line);
g.drawChars(chars, 0, chars.length, x, y);
}
x = HexView.LINE_INSET;
y += HexView.CHAR_HEIGHT;
}
}
/**
* Paint a selected line
* @param g Graphics instance.
* @param x int. x axis value.
* @param y int. y axis value.
*/
private void paintInSelected(Graphics g, int x, int y)
{<FILL_FUNCTION_BODY>}
@Override
public void hexModelChanged(HexModelChangedEvent event)
{
repaint();
}
/**
* Updates the line text for a given index. It is used when a byte is
* selected in hex pane.
* @param index int.
*/
void setSelected(int index)
{
selectedLine = HexModel.lineNumber(index);
selectedIndexInLine = HexModel.elementIndexInLine(index);
repaint();
}
}
|
g.setFont(HexView.BOLD_FONT);
char[] content = model.getLineChars(selectedLine);
g.drawChars(content, 0, selectedIndexInLine - 0, x, y);
g.setColor(HexView.SELECTED_COLOR);
x += g.getFontMetrics().charsWidth(content, 0, selectedIndexInLine-0);
g.drawChars(content, selectedIndexInLine, 1, x, y);
g.setColor(Color.black);
x += g.getFontMetrics().charWidth(content[selectedIndexInLine]);
g.drawChars(content, selectedIndexInLine+1, (content.length-1)-selectedIndexInLine, x, y);
g.setFont(HexView.FONT);
| 714
| 203
| 917
|
<methods>public void <init>() ,public void addAncestorListener(javax.swing.event.AncestorListener) ,public void addNotify() ,public synchronized void addVetoableChangeListener(java.beans.VetoableChangeListener) ,public void computeVisibleRect(java.awt.Rectangle) ,public boolean contains(int, int) ,public javax.swing.JToolTip createToolTip() ,public void disable() ,public void enable() ,public void firePropertyChange(java.lang.String, boolean, boolean) ,public void firePropertyChange(java.lang.String, int, int) ,public void firePropertyChange(java.lang.String, char, char) ,public java.awt.event.ActionListener getActionForKeyStroke(javax.swing.KeyStroke) ,public final javax.swing.ActionMap getActionMap() ,public float getAlignmentX() ,public float getAlignmentY() ,public javax.swing.event.AncestorListener[] getAncestorListeners() ,public boolean getAutoscrolls() ,public int getBaseline(int, int) ,public java.awt.Component.BaselineResizeBehavior getBaselineResizeBehavior() ,public javax.swing.border.Border getBorder() ,public java.awt.Rectangle getBounds(java.awt.Rectangle) ,public final java.lang.Object getClientProperty(java.lang.Object) ,public javax.swing.JPopupMenu getComponentPopupMenu() ,public int getConditionForKeyStroke(javax.swing.KeyStroke) ,public int getDebugGraphicsOptions() ,public static java.util.Locale getDefaultLocale() ,public java.awt.FontMetrics getFontMetrics(java.awt.Font) ,public java.awt.Graphics getGraphics() ,public int getHeight() ,public boolean getInheritsPopupMenu() ,public final javax.swing.InputMap getInputMap() ,public final javax.swing.InputMap getInputMap(int) ,public javax.swing.InputVerifier getInputVerifier() ,public java.awt.Insets getInsets() ,public java.awt.Insets getInsets(java.awt.Insets) ,public T[] getListeners(Class<T>) ,public java.awt.Point getLocation(java.awt.Point) ,public java.awt.Dimension getMaximumSize() ,public java.awt.Dimension getMinimumSize() ,public java.awt.Component getNextFocusableComponent() ,public java.awt.Point getPopupLocation(java.awt.event.MouseEvent) ,public java.awt.Dimension getPreferredSize() ,public javax.swing.KeyStroke[] getRegisteredKeyStrokes() ,public javax.swing.JRootPane getRootPane() ,public java.awt.Dimension getSize(java.awt.Dimension) ,public java.awt.Point getToolTipLocation(java.awt.event.MouseEvent) ,public java.lang.String getToolTipText() ,public java.lang.String getToolTipText(java.awt.event.MouseEvent) ,public java.awt.Container getTopLevelAncestor() ,public javax.swing.TransferHandler getTransferHandler() ,public javax.swing.plaf.ComponentUI getUI() ,public java.lang.String getUIClassID() ,public boolean getVerifyInputWhenFocusTarget() ,public synchronized java.beans.VetoableChangeListener[] getVetoableChangeListeners() ,public java.awt.Rectangle getVisibleRect() ,public int getWidth() ,public int getX() ,public int getY() ,public void grabFocus() ,public void hide() ,public boolean isDoubleBuffered() ,public static boolean isLightweightComponent(java.awt.Component) ,public boolean isManagingFocus() ,public boolean isOpaque() ,public boolean isOptimizedDrawingEnabled() ,public final boolean isPaintingForPrint() ,public boolean isPaintingTile() ,public boolean isRequestFocusEnabled() ,public boolean isValidateRoot() ,public void paint(java.awt.Graphics) ,public void paintImmediately(java.awt.Rectangle) ,public void paintImmediately(int, int, int, int) ,public void print(java.awt.Graphics) ,public void printAll(java.awt.Graphics) ,public final void putClientProperty(java.lang.Object, java.lang.Object) ,public void registerKeyboardAction(java.awt.event.ActionListener, javax.swing.KeyStroke, int) ,public void registerKeyboardAction(java.awt.event.ActionListener, java.lang.String, javax.swing.KeyStroke, int) ,public void removeAncestorListener(javax.swing.event.AncestorListener) ,public void removeNotify() ,public synchronized void removeVetoableChangeListener(java.beans.VetoableChangeListener) ,public void repaint(java.awt.Rectangle) ,public void repaint(long, int, int, int, int) ,public boolean requestDefaultFocus() ,public void requestFocus() ,public boolean requestFocus(boolean) ,public boolean requestFocusInWindow() ,public void resetKeyboardActions() ,public void reshape(int, int, int, int) ,public void revalidate() ,public void scrollRectToVisible(java.awt.Rectangle) ,public final void setActionMap(javax.swing.ActionMap) ,public void setAlignmentX(float) ,public void setAlignmentY(float) ,public void setAutoscrolls(boolean) ,public void setBackground(java.awt.Color) ,public void setBorder(javax.swing.border.Border) ,public void setComponentPopupMenu(javax.swing.JPopupMenu) ,public void setDebugGraphicsOptions(int) ,public static void setDefaultLocale(java.util.Locale) ,public void setDoubleBuffered(boolean) ,public void setEnabled(boolean) ,public void setFocusTraversalKeys(int, Set<? extends java.awt.AWTKeyStroke>) ,public void setFont(java.awt.Font) ,public void setForeground(java.awt.Color) ,public void setInheritsPopupMenu(boolean) ,public final void setInputMap(int, javax.swing.InputMap) ,public void setInputVerifier(javax.swing.InputVerifier) ,public void setMaximumSize(java.awt.Dimension) ,public void setMinimumSize(java.awt.Dimension) ,public void setNextFocusableComponent(java.awt.Component) ,public void setOpaque(boolean) ,public void setPreferredSize(java.awt.Dimension) ,public void setRequestFocusEnabled(boolean) ,public void setToolTipText(java.lang.String) ,public void setTransferHandler(javax.swing.TransferHandler) ,public void setVerifyInputWhenFocusTarget(boolean) ,public void setVisible(boolean) ,public void unregisterKeyboardAction(javax.swing.KeyStroke) ,public void update(java.awt.Graphics) ,public void updateUI() <variables>private static final int ACTIONMAP_CREATED,private static final int ANCESTOR_INPUTMAP_CREATED,private static final int ANCESTOR_USING_BUFFER,private static final int AUTOSCROLLS_SET,private static final int COMPLETELY_OBSCURED,private static final int CREATED_DOUBLE_BUFFER,static boolean DEBUG_GRAPHICS_LOADED,private static final int FOCUS_INPUTMAP_CREATED,private static final int FOCUS_TRAVERSAL_KEYS_BACKWARD_SET,private static final int FOCUS_TRAVERSAL_KEYS_FORWARD_SET,private static final int INHERITS_POPUP_MENU,private static final java.lang.Object INPUT_VERIFIER_SOURCE_KEY,private static final int IS_DOUBLE_BUFFERED,private static final int IS_OPAQUE,private static final int IS_PAINTING_TILE,private static final int IS_PRINTING,private static final int IS_PRINTING_ALL,private static final int IS_REPAINTING,private static final java.lang.String KEYBOARD_BINDINGS_KEY,private static final int KEY_EVENTS_ENABLED,private static final java.lang.String NEXT_FOCUS,private static final int NOT_OBSCURED,private static final int OPAQUE_SET,private static final int PARTIALLY_OBSCURED,private static final int REQUEST_FOCUS_DISABLED,private static final int RESERVED_1,private static final int RESERVED_2,private static final int RESERVED_3,private static final int RESERVED_4,private static final int RESERVED_5,private static final int RESERVED_6,public static final java.lang.String TOOL_TIP_TEXT_KEY,public static final int UNDEFINED_CONDITION,public static final int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,public static final int WHEN_FOCUSED,public static final int WHEN_IN_FOCUSED_WINDOW,private static final java.lang.String WHEN_IN_FOCUSED_WINDOW_BINDINGS,private static final int WIF_INPUTMAP_CREATED,private static final int WRITE_OBJ_COUNTER_FIRST,private static final int WRITE_OBJ_COUNTER_LAST,private transient java.lang.Object aaHint,private javax.swing.ActionMap actionMap,private float alignmentX,private float alignmentY,private javax.swing.InputMap ancestorInputMap,private boolean autoscrolls,private javax.swing.border.Border border,private transient javax.swing.ArrayTable clientProperties,private static java.awt.Component componentObtainingGraphicsFrom,private static java.lang.Object componentObtainingGraphicsFromLock,private static final java.lang.String defaultLocale,private int flags,static final sun.awt.RequestFocusController focusController,private javax.swing.InputMap focusInputMap,private javax.swing.InputVerifier inputVerifier,private boolean isAlignmentXSet,private boolean isAlignmentYSet,private transient java.lang.Object lcdRenderingHint,protected javax.swing.event.EventListenerList listenerList,private static Set<javax.swing.KeyStroke> managingFocusBackwardTraversalKeys,private static Set<javax.swing.KeyStroke> managingFocusForwardTraversalKeys,transient java.awt.Component paintingChild,private javax.swing.JPopupMenu popupMenu,private static final Hashtable<java.io.ObjectInputStream,javax.swing.JComponent.ReadObjectCallback> readObjectCallbacks,private transient java.util.concurrent.atomic.AtomicBoolean revalidateRunnableScheduled,private static List<java.awt.Rectangle> tempRectangles,protected transient javax.swing.plaf.ComponentUI ui,private static final java.lang.String uiClassID,private boolean verifyInputWhenFocusTarget,private java.beans.VetoableChangeSupport vetoableChangeSupport,private javax.swing.ComponentInputMap windowInputMap
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/hexviewer/AddressPane.java
|
AddressPane
|
paintComponent
|
class AddressPane extends JComponent
{
private final int totalLine;
private int selectedLine = -1;
private int selectedIndex = -1;
/**
* Constructor.
* @param total int. Total line number needed to show all the bytes.
*/
AddressPane(int total)
{
totalLine = total;
setPreferredSize(new Dimension(HexView.ADDRESS_PANE_WIDTH, HexView.CHAR_HEIGHT * (totalLine+1)));
setFont(HexView.FONT);
}
@Override
protected void paintComponent(Graphics g)
{<FILL_FUNCTION_BODY>}
/**
* Paint a selected line
* @param g Graphics instance.
* @param x int. x axis value.
* @param y int. y axis value.
*/
private void paintSelected(Graphics g, int x, int y)
{
g.setColor(HexView.SELECTED_COLOR);
g.setFont(HexView.BOLD_FONT);
g.drawString(String.format("%08X", selectedIndex), x, y);
g.setColor(Color.black);
g.setFont(HexView.FONT);
}
/**
* Updates the line text (index in hexadecimal) for a given index. It is used when a byte is
* selected in hex pane.
* @param index int.
*/
void setSelected(int index)
{
if (index != selectedIndex)
{
selectedLine = HexModel.lineNumber(index);
selectedIndex = index;
repaint();
}
}
}
|
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHints(HexView.RENDERING_HINTS);
Rectangle bound = getVisibleRect();
int x = HexView.LINE_INSET;
int y = bound.y;
if (y == 0 || y%HexView.CHAR_HEIGHT != 0)
{
y += HexView.CHAR_HEIGHT - y%HexView.CHAR_HEIGHT;
}
int firstLine = y/HexView.CHAR_HEIGHT;
for (int line = firstLine; line < firstLine + bound.getHeight()/HexView.CHAR_HEIGHT; line++)
{
if (line > totalLine)
{
break;
}
if (line == selectedLine)
{
paintSelected(g, x, y);
}
else
{
g.drawString(String.format("%08X", (line - 1)*16), x, y);
}
x = HexView.LINE_INSET;
y += HexView.CHAR_HEIGHT;
}
| 431
| 310
| 741
|
<methods>public void <init>() ,public void addAncestorListener(javax.swing.event.AncestorListener) ,public void addNotify() ,public synchronized void addVetoableChangeListener(java.beans.VetoableChangeListener) ,public void computeVisibleRect(java.awt.Rectangle) ,public boolean contains(int, int) ,public javax.swing.JToolTip createToolTip() ,public void disable() ,public void enable() ,public void firePropertyChange(java.lang.String, boolean, boolean) ,public void firePropertyChange(java.lang.String, int, int) ,public void firePropertyChange(java.lang.String, char, char) ,public java.awt.event.ActionListener getActionForKeyStroke(javax.swing.KeyStroke) ,public final javax.swing.ActionMap getActionMap() ,public float getAlignmentX() ,public float getAlignmentY() ,public javax.swing.event.AncestorListener[] getAncestorListeners() ,public boolean getAutoscrolls() ,public int getBaseline(int, int) ,public java.awt.Component.BaselineResizeBehavior getBaselineResizeBehavior() ,public javax.swing.border.Border getBorder() ,public java.awt.Rectangle getBounds(java.awt.Rectangle) ,public final java.lang.Object getClientProperty(java.lang.Object) ,public javax.swing.JPopupMenu getComponentPopupMenu() ,public int getConditionForKeyStroke(javax.swing.KeyStroke) ,public int getDebugGraphicsOptions() ,public static java.util.Locale getDefaultLocale() ,public java.awt.FontMetrics getFontMetrics(java.awt.Font) ,public java.awt.Graphics getGraphics() ,public int getHeight() ,public boolean getInheritsPopupMenu() ,public final javax.swing.InputMap getInputMap() ,public final javax.swing.InputMap getInputMap(int) ,public javax.swing.InputVerifier getInputVerifier() ,public java.awt.Insets getInsets() ,public java.awt.Insets getInsets(java.awt.Insets) ,public T[] getListeners(Class<T>) ,public java.awt.Point getLocation(java.awt.Point) ,public java.awt.Dimension getMaximumSize() ,public java.awt.Dimension getMinimumSize() ,public java.awt.Component getNextFocusableComponent() ,public java.awt.Point getPopupLocation(java.awt.event.MouseEvent) ,public java.awt.Dimension getPreferredSize() ,public javax.swing.KeyStroke[] getRegisteredKeyStrokes() ,public javax.swing.JRootPane getRootPane() ,public java.awt.Dimension getSize(java.awt.Dimension) ,public java.awt.Point getToolTipLocation(java.awt.event.MouseEvent) ,public java.lang.String getToolTipText() ,public java.lang.String getToolTipText(java.awt.event.MouseEvent) ,public java.awt.Container getTopLevelAncestor() ,public javax.swing.TransferHandler getTransferHandler() ,public javax.swing.plaf.ComponentUI getUI() ,public java.lang.String getUIClassID() ,public boolean getVerifyInputWhenFocusTarget() ,public synchronized java.beans.VetoableChangeListener[] getVetoableChangeListeners() ,public java.awt.Rectangle getVisibleRect() ,public int getWidth() ,public int getX() ,public int getY() ,public void grabFocus() ,public void hide() ,public boolean isDoubleBuffered() ,public static boolean isLightweightComponent(java.awt.Component) ,public boolean isManagingFocus() ,public boolean isOpaque() ,public boolean isOptimizedDrawingEnabled() ,public final boolean isPaintingForPrint() ,public boolean isPaintingTile() ,public boolean isRequestFocusEnabled() ,public boolean isValidateRoot() ,public void paint(java.awt.Graphics) ,public void paintImmediately(java.awt.Rectangle) ,public void paintImmediately(int, int, int, int) ,public void print(java.awt.Graphics) ,public void printAll(java.awt.Graphics) ,public final void putClientProperty(java.lang.Object, java.lang.Object) ,public void registerKeyboardAction(java.awt.event.ActionListener, javax.swing.KeyStroke, int) ,public void registerKeyboardAction(java.awt.event.ActionListener, java.lang.String, javax.swing.KeyStroke, int) ,public void removeAncestorListener(javax.swing.event.AncestorListener) ,public void removeNotify() ,public synchronized void removeVetoableChangeListener(java.beans.VetoableChangeListener) ,public void repaint(java.awt.Rectangle) ,public void repaint(long, int, int, int, int) ,public boolean requestDefaultFocus() ,public void requestFocus() ,public boolean requestFocus(boolean) ,public boolean requestFocusInWindow() ,public void resetKeyboardActions() ,public void reshape(int, int, int, int) ,public void revalidate() ,public void scrollRectToVisible(java.awt.Rectangle) ,public final void setActionMap(javax.swing.ActionMap) ,public void setAlignmentX(float) ,public void setAlignmentY(float) ,public void setAutoscrolls(boolean) ,public void setBackground(java.awt.Color) ,public void setBorder(javax.swing.border.Border) ,public void setComponentPopupMenu(javax.swing.JPopupMenu) ,public void setDebugGraphicsOptions(int) ,public static void setDefaultLocale(java.util.Locale) ,public void setDoubleBuffered(boolean) ,public void setEnabled(boolean) ,public void setFocusTraversalKeys(int, Set<? extends java.awt.AWTKeyStroke>) ,public void setFont(java.awt.Font) ,public void setForeground(java.awt.Color) ,public void setInheritsPopupMenu(boolean) ,public final void setInputMap(int, javax.swing.InputMap) ,public void setInputVerifier(javax.swing.InputVerifier) ,public void setMaximumSize(java.awt.Dimension) ,public void setMinimumSize(java.awt.Dimension) ,public void setNextFocusableComponent(java.awt.Component) ,public void setOpaque(boolean) ,public void setPreferredSize(java.awt.Dimension) ,public void setRequestFocusEnabled(boolean) ,public void setToolTipText(java.lang.String) ,public void setTransferHandler(javax.swing.TransferHandler) ,public void setVerifyInputWhenFocusTarget(boolean) ,public void setVisible(boolean) ,public void unregisterKeyboardAction(javax.swing.KeyStroke) ,public void update(java.awt.Graphics) ,public void updateUI() <variables>private static final int ACTIONMAP_CREATED,private static final int ANCESTOR_INPUTMAP_CREATED,private static final int ANCESTOR_USING_BUFFER,private static final int AUTOSCROLLS_SET,private static final int COMPLETELY_OBSCURED,private static final int CREATED_DOUBLE_BUFFER,static boolean DEBUG_GRAPHICS_LOADED,private static final int FOCUS_INPUTMAP_CREATED,private static final int FOCUS_TRAVERSAL_KEYS_BACKWARD_SET,private static final int FOCUS_TRAVERSAL_KEYS_FORWARD_SET,private static final int INHERITS_POPUP_MENU,private static final java.lang.Object INPUT_VERIFIER_SOURCE_KEY,private static final int IS_DOUBLE_BUFFERED,private static final int IS_OPAQUE,private static final int IS_PAINTING_TILE,private static final int IS_PRINTING,private static final int IS_PRINTING_ALL,private static final int IS_REPAINTING,private static final java.lang.String KEYBOARD_BINDINGS_KEY,private static final int KEY_EVENTS_ENABLED,private static final java.lang.String NEXT_FOCUS,private static final int NOT_OBSCURED,private static final int OPAQUE_SET,private static final int PARTIALLY_OBSCURED,private static final int REQUEST_FOCUS_DISABLED,private static final int RESERVED_1,private static final int RESERVED_2,private static final int RESERVED_3,private static final int RESERVED_4,private static final int RESERVED_5,private static final int RESERVED_6,public static final java.lang.String TOOL_TIP_TEXT_KEY,public static final int UNDEFINED_CONDITION,public static final int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,public static final int WHEN_FOCUSED,public static final int WHEN_IN_FOCUSED_WINDOW,private static final java.lang.String WHEN_IN_FOCUSED_WINDOW_BINDINGS,private static final int WIF_INPUTMAP_CREATED,private static final int WRITE_OBJ_COUNTER_FIRST,private static final int WRITE_OBJ_COUNTER_LAST,private transient java.lang.Object aaHint,private javax.swing.ActionMap actionMap,private float alignmentX,private float alignmentY,private javax.swing.InputMap ancestorInputMap,private boolean autoscrolls,private javax.swing.border.Border border,private transient javax.swing.ArrayTable clientProperties,private static java.awt.Component componentObtainingGraphicsFrom,private static java.lang.Object componentObtainingGraphicsFromLock,private static final java.lang.String defaultLocale,private int flags,static final sun.awt.RequestFocusController focusController,private javax.swing.InputMap focusInputMap,private javax.swing.InputVerifier inputVerifier,private boolean isAlignmentXSet,private boolean isAlignmentYSet,private transient java.lang.Object lcdRenderingHint,protected javax.swing.event.EventListenerList listenerList,private static Set<javax.swing.KeyStroke> managingFocusBackwardTraversalKeys,private static Set<javax.swing.KeyStroke> managingFocusForwardTraversalKeys,transient java.awt.Component paintingChild,private javax.swing.JPopupMenu popupMenu,private static final Hashtable<java.io.ObjectInputStream,javax.swing.JComponent.ReadObjectCallback> readObjectCallbacks,private transient java.util.concurrent.atomic.AtomicBoolean revalidateRunnableScheduled,private static List<java.awt.Rectangle> tempRectangles,protected transient javax.swing.plaf.ComponentUI ui,private static final java.lang.String uiClassID,private boolean verifyInputWhenFocusTarget,private java.beans.VetoableChangeSupport vetoableChangeSupport,private javax.swing.ComponentInputMap windowInputMap
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/hexviewer/HexEditor.java
|
HexEditor
|
createJumpDialog
|
class HexEditor extends JPanel implements SelectionChangeListener
{
private final HexModel model;
private HexPane hexPane;
private ASCIIPane asciiPane;
private AddressPane addressPane;
private StatusPane statusPane;
private final Action jumpToIndex;
private int selectedIndex = -1;
/**
* Constructor.
* @param model HexModel instance.
*/
HexEditor(HexModel model)
{
super();
this.jumpToIndex = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
createJumpDialog().setVisible(true);
}
};
this.model = model;
createView();
}
private void createView()
{
setLayout(new GridBagLayout());
addressPane = new AddressPane(model.totalLine());
hexPane = new HexPane(model);
hexPane.addHexChangeListeners(model);
asciiPane = new ASCIIPane(model);
UpperPane upperPane = new UpperPane();
statusPane = new StatusPane();
model.addHexModelChangeListener(hexPane);
model.addHexModelChangeListener(asciiPane);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.setPreferredSize(new Dimension(HexView.TOTAL_WIDTH, HexView.CHAR_HEIGHT * (model.totalLine() + 1)));
panel.add(addressPane);
panel.add(hexPane);
panel.add(asciiPane);
JScrollPane scrollPane = getScrollPane();
scrollPane.setViewportView(panel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 0.02;
add(upperPane, gbc);
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridy = 1;
gbc.weighty = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
add(scrollPane, gbc);
gbc.gridy = 2;
gbc.weightx = 0.1;
gbc.weighty = 0.0;
gbc.anchor = GridBagConstraints.LAST_LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(statusPane, gbc);
hexPane.addSelectionChangeListener(this);
KeyStroke jumpKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_DOWN_MASK);
this.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(jumpKeyStroke, "jump");
this.getActionMap().put("jump", jumpToIndex);
}
private JScrollPane getScrollPane()
{
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBorder(new LineBorder(Color.LIGHT_GRAY));
Action blankAction = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
// do nothing
}
};
scrollPane.getActionMap().put("unitScrollDown", blankAction);
scrollPane.getActionMap().put("unitScrollLeft", blankAction);
scrollPane.getActionMap().put("unitScrollRight", blankAction);
scrollPane.getActionMap().put("unitScrollUp", blankAction);
JScrollBar verticalScrollBar = scrollPane.createVerticalScrollBar();
verticalScrollBar.setUnitIncrement(HexView.CHAR_HEIGHT);
verticalScrollBar.setBlockIncrement(HexView.CHAR_HEIGHT * 20);
verticalScrollBar.setValues(0, 1, 0, HexView.CHAR_HEIGHT * (model.totalLine()+1));
scrollPane.setVerticalScrollBar(verticalScrollBar);
return scrollPane;
}
@Override
public void selectionChanged(SelectEvent event)
{
int index = event.getHexIndex();
switch (event.getNavigation())
{
case SelectEvent.NEXT:
index += 1;
break;
case SelectEvent.PREVIOUS:
index -= 1;
break;
case SelectEvent.UP:
index -= 16;
break;
case SelectEvent.DOWN:
index += 16;
break;
default:
break;
}
if (index >= 0 && index <= model.size() - 1)
{
hexPane.setSelected(index);
addressPane.setSelected(index);
asciiPane.setSelected(index);
statusPane.updateStatus(index);
selectedIndex = index;
}
}
private JDialog createJumpDialog()
{<FILL_FUNCTION_BODY>}
}
|
final JDialog dialog = new JDialog(SwingUtilities.windowForComponent(this), "Jump to index");
dialog.setLocationRelativeTo(this);
final JLabel nowLabel = new JLabel("Present index: " + selectedIndex);
final JLabel label = new JLabel("Index to go:");
final JTextField field = new JFormattedTextField(NumberFormat.getIntegerInstance());
field.setPreferredSize(new Dimension(100, 20));
field.addActionListener(new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
int index = Integer.parseInt(field.getText(), 10);
if (index >= 0 && index <= model.size() - 1)
{
selectionChanged(new SelectEvent(index, SelectEvent.IN));
dialog.dispose();
}
}
});
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(nowLabel);
JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
inputPanel.add(label);
inputPanel.add(field);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
contentPanel.add(panel);
contentPanel.add(inputPanel);
dialog.getContentPane().add(contentPanel);
dialog.pack();
return dialog;
| 1,336
| 377
| 1,713
|
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/hexviewer/HexModel.java
|
HexModel
|
getLineChars
|
class HexModel implements HexChangeListener
{
private final List<Byte> data;
private final List<HexModelChangeListener> modelChangeListeners;
/**
* Constructor
* @param bytes Byte array.
*/
HexModel(byte[] bytes)
{
data = new ArrayList<>(bytes.length);
for (byte b: bytes)
{
data.add(b);
}
modelChangeListeners = new ArrayList<>();
}
/**
* provides the byte for a specific index of the byte array.
* @param index int.
* @return byte instance
*/
public byte getByte(int index)
{
return data.get(index);
}
/**
* Provides a character array of 16 characters on availability.
* @param lineNumber int. The line number of the characters. Line counting starts from 1.
* @return A char array.
*/
public char[] getLineChars(int lineNumber)
{<FILL_FUNCTION_BODY>}
public byte[] getBytesForLine(int lineNumber)
{
int index = (lineNumber-1) * 16;
int length = Math.min(data.size() - index, 16);
byte[] bytes = new byte[length];
for (int i = 0; i < bytes.length; i++)
{
bytes[i] = data.get(index);
index++;
}
return bytes;
}
/**
* Provides the size of the model i.e. size of the input.
* @return int value.
*/
public int size()
{
return data.size();
}
/**
*
* @return
*/
public int totalLine()
{
return size() % 16 != 0 ? size()/16 + 1 : size()/16;
}
public static int lineNumber(int index)
{
int elementNo = index + 1;
return elementNo % 16 != 0 ? elementNo/16 + 1 : elementNo/16;
}
public static int elementIndexInLine(int index)
{
return index%16;
}
private static boolean isAsciiPrintable(char ch)
{
return ch >= 32 && ch < 127;
}
public void addHexModelChangeListener(HexModelChangeListener listener)
{
modelChangeListeners.add(listener);
}
public void updateModel(int index, byte value)
{
if (!data.get(index).equals(value))
{
data.set(index, value);
fireModelChanged(index);
}
}
@Override
public void hexChanged(HexChangedEvent event)
{
int index = event.getByteIndex();
if (index != -1 && getByte(index) != event.getNewValue())
{
data.set(index, event.getNewValue());
}
fireModelChanged(index);
}
private void fireModelChanged(int index)
{
modelChangeListeners.forEach(listener ->
listener.hexModelChanged(new HexModelChangedEvent(index, HexModelChangedEvent.SINGLE_CHANGE)));
}
}
|
int start = (lineNumber-1) * 16;
int length = Math.min(data.size() - start, 16);
char[] chars = new char[length];
for (int i = 0; i < chars.length; i++)
{
char c = Character.toChars(data.get(start) & 0XFF)[0];
if (!isAsciiPrintable(c))
{
c = '.';
}
chars[i] = c;
start++;
}
return chars;
| 857
| 148
| 1,005
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/hexviewer/HexView.java
|
HexView
|
changeData
|
class HexView
{
private final JComponent mainPane;
static final int FONT_SIZE = ((Font)UIManager.get("Label.font")).getSize();
static final Font FONT = new Font("monospaced", Font.PLAIN, FONT_SIZE);
static final int CHAR_HEIGHT = 20;
static final int CHAR_WIDTH = 35;
static final int LINE_INSET = 20;
static final Color SELECTED_COLOR = UIManager.getColor("textHighlight");
static final Font BOLD_FONT = new Font("monospaced", Font.BOLD, FONT_SIZE);
static final int HEX_PANE_WIDTH = 600;
static final int ADDRESS_PANE_WIDTH = 120;
static final int ASCII_PANE_WIDTH = 270;
static final int TOTAL_WIDTH = HEX_PANE_WIDTH + ADDRESS_PANE_WIDTH +ASCII_PANE_WIDTH;
static final Map<RenderingHints.Key, Object> RENDERING_HINTS = new HashMap<>();
static
{
RENDERING_HINTS.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
RENDERING_HINTS.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
}
public HexView()
{
mainPane = new JPanel(new BorderLayout());
}
/**
* Constructor.
* @param bytes takes a byte array.
*/
public HexView(byte[] bytes)
{
mainPane = new JPanel(new BorderLayout());
mainPane.add(new HexEditor(new HexModel(bytes)));
}
public void changeData(byte[] bytes)
{<FILL_FUNCTION_BODY>}
public JComponent getPane()
{
return mainPane;
}
}
|
if (mainPane.getComponentCount() > 0)
{
mainPane.removeAll();
}
HexModel model = new HexModel(bytes);
mainPane.add(new HexEditor(model));
mainPane.validate();
| 538
| 66
| 604
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/hexviewer/StatusPane.java
|
StatusPane
|
createView
|
class StatusPane extends JPanel
{
private static final int HEIGHT = 20;
private JLabel lineLabel;
private JLabel colLabel;
private JLabel indexLabel;
StatusPane()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
createView();
}
private void createView()
{<FILL_FUNCTION_BODY>}
void updateStatus(int index)
{
lineLabel.setText(String.valueOf(HexModel.lineNumber(index)));
colLabel.setText(String.valueOf(HexModel.elementIndexInLine(index)+1));
indexLabel.setText(String.valueOf(index));
}
}
|
JLabel line = new JLabel("Line:");
JLabel column = new JLabel("Column:");
lineLabel = new JLabel("");
lineLabel.setPreferredSize(new Dimension(100, HEIGHT));
colLabel = new JLabel("");
colLabel.setPreferredSize(new Dimension(100, HEIGHT));
JLabel index = new JLabel("Index:");
indexLabel = new JLabel("");
add(line);
add(lineLabel);
add(column);
add(colLabel);
add(index);
add(indexLabel);
| 179
| 154
| 333
|
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/hexviewer/UpperPane.java
|
UpperPane
|
paintComponent
|
class UpperPane extends JPanel
{
UpperPane()
{
setFont(HexView.FONT);
setPreferredSize(new Dimension(HexView.TOTAL_WIDTH, 20));
setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.LIGHT_GRAY));
}
@Override
protected void paintComponent(Graphics g)
{<FILL_FUNCTION_BODY>}
}
|
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHints(HexView.RENDERING_HINTS);
int x = HexView.LINE_INSET-2;
int y = 16;
g.drawString("Offset", x, y);
x += HexView.ADDRESS_PANE_WIDTH + 2;
for (int i = 0; i <= 15; i++)
{
g.drawString(String.format("%02X", i), x, y);
x += HexView.CHAR_WIDTH;
}
x+=HexView.LINE_INSET*2;
g.drawString("Text", x, y);
| 121
| 205
| 326
|
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/streampane/Stream.java
|
Stream
|
getStream
|
class Stream
{
private static final Logger LOG = LogManager.getLogger(Stream.class);
public static final String DECODED = "Decoded (Plain Text)";
public static final String IMAGE = "Image";
private final COSStream strm;
private final boolean isThumb;
private final boolean isImage;
private final boolean isXmlMetadata;
private final Map<String, List<String>> filters;
/**
* Constructor.
*
* @param cosStream COSStream instance.
* @param isThumb boolean instance says if the stream is thumbnail image.
*/
Stream(COSStream cosStream, boolean isThumb)
{
this.strm = cosStream;
this.isThumb = isThumb;
this.isImage = isImageStream(cosStream, isThumb);
this.isXmlMetadata = isXmlMetadataStream(cosStream);
filters = createFilterList(cosStream);
}
/**
* Return if this is stream is an Image XObject.
*
* @return true if this an image and false otherwise.
*/
public boolean isImage()
{
return isImage;
}
/**
* Return if this is stream is an Metadata stream.
*
* @return true if this a metadata stream and false otherwise.
*/
public boolean isXmlMetadata()
{
return isXmlMetadata;
}
/**
* Return the available filter list. Only "Unfiltered" is returned if there is no filter and in
* case of XObject image type stream "Image" is also included in the list.
*
* @return An array of String.
*/
public List<String> getFilterList()
{
return new ArrayList<>(filters.keySet());
}
/**
* Returns the label for the "Unfiltered" menu item.
*/
private String getFilteredLabel()
{
StringJoiner sj = new StringJoiner(", ", "Encoded (", ")");
COSBase base = strm.getFilters();
if (base instanceof COSName)
{
sj.add(((COSName) base).getName());
}
else if (base instanceof COSArray)
{
COSArray filterArray = (COSArray) base;
for (int i = 0; i < filterArray.size(); i++)
{
sj.add(((COSName) filterArray.get(i)).getName());
}
}
return sj.toString();
}
/**
* Returns a InputStream of a partially filtered stream.
*
* @param key is an instance of String which tells which version of stream should be returned.
* @return an InputStream.
*/
public InputStream getStream(String key)
{<FILL_FUNCTION_BODY>}
/**
* Provide the image for stream. The stream must be image XObject.
*
* @param resources PDResources for the XObject.
* @return A BufferedImage.
*/
public BufferedImage getImage(PDResources resources)
{
try
{
PDImageXObject imageXObject;
if (isThumb)
{
imageXObject = PDImageXObject.createThumbnail(strm);
}
else
{
imageXObject = new PDImageXObject(new PDStream(strm), resources);
}
return imageXObject.getImage();
}
catch (IOException e)
{
LOG.error(e.getMessage(), e);
}
return null;
}
private Map<String, List<String>> createFilterList(COSStream stream)
{
Map<String, List<String>> filterList = new LinkedHashMap<>();
if (isImage)
{
filterList.put(IMAGE, null);
}
filterList.put(DECODED, null);
PDStream pdStream = new PDStream(stream);
int filtersSize = pdStream.getFilters().size();
for (int i = filtersSize - 1; i >= 1; i--)
{
filterList.put(getPartialStreamCommand(i), getStopFilterList(i));
}
filterList.put(getFilteredLabel(), null);
return filterList;
}
private String getPartialStreamCommand(final int indexOfStopFilter)
{
List<COSName> availableFilters = new PDStream(strm).getFilters();
StringBuilder nameListBuilder = new StringBuilder();
for (int i = indexOfStopFilter; i < availableFilters.size(); i++)
{
nameListBuilder.append(availableFilters.get(i).getName()).append(" & ");
}
nameListBuilder.delete(nameListBuilder.lastIndexOf("&"), nameListBuilder.length());
return "Keep " + nameListBuilder + "...";
}
private List<String> getStopFilterList(final int stopFilterIndex)
{
List<COSName> availableFilters = new PDStream(strm).getFilters();
final List<String> stopFilters = new ArrayList<>(1);
stopFilters.add(availableFilters.get(stopFilterIndex).getName());
return stopFilters;
}
private boolean isImageStream(COSDictionary dic, boolean isThumb)
{
if (isThumb)
{
return true;
}
return dic.containsKey(COSName.SUBTYPE) && dic.getCOSName(COSName.SUBTYPE).equals(COSName.IMAGE);
}
private boolean isXmlMetadataStream(COSDictionary dic)
{
return dic.containsKey(COSName.SUBTYPE) && dic.getCOSName(COSName.SUBTYPE).equals(COSName.getPDFName("XML"));
}
}
|
try
{
if (DECODED.equals(key))
{
return strm.createInputStream();
}
else if (getFilteredLabel().equals(key))
{
return strm.createRawInputStream();
}
else
{
return new PDStream(strm).createInputStream(filters.get(key));
}
}
catch (IOException e)
{
LOG.error(e.getMessage(), e);
}
return null;
| 1,510
| 130
| 1,640
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/streampane/StreamImageView.java
|
StreamImageView
|
addImage
|
class StreamImageView implements ActionListener, AncestorListener
{
private final BufferedImage image;
private JScrollPane scrollPane;
private JLabel label;
private ZoomMenu zoomMenu;
private RotationMenu rotationMenu;
/**
* constructor.
* @param image instance of BufferedImage.
*/
StreamImageView(BufferedImage image)
{
this.image = image;
initUI();
}
private void initUI()
{
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
zoomMenu = ZoomMenu.getInstance();
zoomMenu.changeZoomSelection(zoomMenu.getImageZoomScale());
label = new JLabel();
label.setBorder(new LineBorder(Color.BLACK));
label.setAlignmentX(Component.CENTER_ALIGNMENT);
addImage(zoomImage(image, zoomMenu.getImageZoomScale(), RotationMenu.getRotationDegrees()));
panel.add(Box.createVerticalGlue());
panel.add(label);
panel.add(Box.createVerticalGlue());
scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(300, 400));
scrollPane.addAncestorListener(this);
scrollPane.setViewportView(panel);
}
/**
* Returns the view i.e container containing image.
* @return A JComponent instance.
*/
JComponent getView()
{
return scrollPane;
}
private Image zoomImage(BufferedImage origin, float scale, int rotation)
{
BufferedImage rotatedImage = ImageUtil.getRotatedImage(origin, rotation);
int resizedWidth = (int) (rotatedImage.getWidth() * scale);
int resizedHeight = (int) (rotatedImage.getHeight() * scale);
return rotatedImage.getScaledInstance(resizedWidth, resizedHeight, Image.SCALE_SMOOTH);
}
@Override
public void actionPerformed(ActionEvent actionEvent)
{
String actionCommand = actionEvent.getActionCommand();
if (ZoomMenu.isZoomMenu(actionCommand) || RotationMenu.isRotationMenu(actionCommand))
{
addImage(zoomImage(image, ZoomMenu.getZoomScale(), RotationMenu.getRotationDegrees()));
zoomMenu.setImageZoomScale(ZoomMenu.getZoomScale());
}
}
private void addImage(Image img)
{<FILL_FUNCTION_BODY>}
@Override
public void ancestorAdded(AncestorEvent ancestorEvent)
{
zoomMenu.addMenuListeners(this);
zoomMenu.setEnableMenu(true);
rotationMenu = RotationMenu.getInstance();
rotationMenu.addMenuListeners(this);
rotationMenu.setRotationSelection(RotationMenu.ROTATE_0_DEGREES);
rotationMenu.setEnableMenu(true);
}
@Override
public void ancestorRemoved(AncestorEvent ancestorEvent)
{
zoomMenu.setEnableMenu(false);
rotationMenu.setEnableMenu(false);
}
@Override
public void ancestorMoved(AncestorEvent ancestorEvent)
{
}
}
|
// for JDK9; see explanation in PagePane
AffineTransform tx = GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration().getDefaultTransform();
label.setSize((int) Math.ceil(img.getWidth(null) / tx.getScaleX()),
(int) Math.ceil(img.getHeight(null) / tx.getScaleY()));
label.setIcon(new HighResolutionImageIcon(img, label.getWidth(), label.getHeight()));
label.revalidate();
| 869
| 130
| 999
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/streampane/StreamPaneView.java
|
StreamPaneView
|
showStreamText
|
class StreamPaneView
{
private final JPanel contentPanel;
/**
* Constructor.
*/
StreamPaneView()
{
contentPanel = new JPanel(new BorderLayout());
}
/**
* This shows the stream in text for any of it's filtered or unfiltered version.
* @param document StyledDocument instance that holds the text.
* @param toolTipController ToolTipController instance.
*/
void showStreamText(StyledDocument document, ToolTipController toolTipController)
{<FILL_FUNCTION_BODY>}
/**
* This shows the stream as image.
* @param image BufferedImage instance that holds the text.
*/
void showStreamImage(BufferedImage image)
{
contentPanel.removeAll();
contentPanel.add(new StreamImageView(image).getView(), BorderLayout.CENTER);
contentPanel.validate();
}
public JPanel getStreamPanel()
{
return contentPanel;
}
}
|
contentPanel.removeAll();
StreamTextView textView = new StreamTextView(document, toolTipController);
contentPanel.add(textView.getView(), BorderLayout.CENTER);
contentPanel.validate();
| 263
| 56
| 319
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/streampane/StreamTextView.java
|
StreamTextView
|
ancestorAdded
|
class StreamTextView implements MouseMotionListener, AncestorListener
{
private final ToolTipController tTController;
private JPanel mainPanel;
private JTextPane textPane;
private Searcher searcher;
/**
* Constructor.
* @param document StyledDocument instance which is supposed to be shown in the pane.
* @param controller ToolTipController instance.
*/
StreamTextView(StyledDocument document, ToolTipController controller)
{
tTController = controller;
initUI(document);
}
private void initUI(StyledDocument document)
{
mainPanel = new JPanel();
textPane = new JTextPane(document);
textPane.addMouseMotionListener(this);
textPane.setFont(new Font("monospaced", Font.PLAIN, 13));
searcher = new Searcher(textPane);
JScrollPane scrollPane = new JScrollPane(textPane);
BoxLayout boxLayout = new BoxLayout(mainPanel, BoxLayout.Y_AXIS);
mainPanel.setLayout(boxLayout);
mainPanel.add(searcher.getSearchPanel());
mainPanel.add(scrollPane);
searcher.getSearchPanel().setVisible(false);
mainPanel.addAncestorListener(this);
}
JComponent getView()
{
return mainPanel;
}
@Override
public void mouseDragged(MouseEvent mouseEvent)
{
// do nothing
}
@Override
public void mouseMoved(MouseEvent mouseEvent)
{
if (tTController != null)
{
int offset = textPane.viewToModel2D(mouseEvent.getPoint());
textPane.setToolTipText(tTController.getToolTip(offset, textPane));
}
}
@Override
public void ancestorAdded(AncestorEvent ancestorEvent)
{<FILL_FUNCTION_BODY>}
@Override
public void ancestorRemoved(AncestorEvent ancestorEvent)
{
if (ancestorEvent.getAncestor().equals(mainPanel))
{
PDFDebugger debugger = (PDFDebugger) SwingUtilities.getRoot(mainPanel);
debugger.getFindMenu().setEnabled(false);
searcher.removeMenuListeners(debugger);
}
}
@Override
public void ancestorMoved(AncestorEvent ancestorEvent)
{
// do nothing
}
}
|
if (ancestorEvent.getAncestor().equals(mainPanel))
{
PDFDebugger debugger = (PDFDebugger) SwingUtilities.getRoot(mainPanel);
debugger.getFindMenu().setEnabled(true);
searcher.addMenuListeners(debugger);
}
| 648
| 80
| 728
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/streampane/tooltip/ColorToolTip.java
|
ColorToolTip
|
getMarkUp
|
class ColorToolTip implements ToolTip
{
private String toolTipText;
/**
* provides the Hex value for a Color instance.
* @param color
* @return
*/
static String colorHexValue(Color color)
{
return String.format("%02x", color.getRed()) + String.format("%02x", color.getGreen()) +
String.format("%02x", color.getBlue());
}
/**
* Extract Color values from the row for which tooltip is going to be shown.
* @param rowtext String instance,
* @return float array containing color values.
*/
float[] extractColorValues(String rowtext)
{
List<String> words = ToolTipController.getWords(rowtext);
words.remove(words.size()-1);
float[] values = new float[words.size()];
int index = 0;
try
{
for (String word : words)
{
values[index++] = Float.parseFloat(word);
}
}
catch (NumberFormatException e)
{
return null;
}
return values;
}
/**
* Create a html string that actually shows a colored rect.
* @param hexValue
* @return String instance, In html format.
*/
String getMarkUp(String hexValue)
{<FILL_FUNCTION_BODY>}
public void setToolTipText(String toolTip)
{
this.toolTipText = toolTip;
}
@Override
public String getToolTipText()
{
return toolTipText;
}
}
|
return "<html>\n" +
"<body bgcolor=#ffffff>\n" +
"<div style=\"width:50px;height:20px;border:1px; background-color:#"+hexValue+";\"></div></body>\n" +
"</html>";
| 421
| 84
| 505
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/streampane/tooltip/FontToolTip.java
|
FontToolTip
|
initUI
|
class FontToolTip implements ToolTip
{
private static final Logger LOG = LogManager.getLogger(FontToolTip.class);
private String markup;
/**
* Constructor.
* @param resources PDResources instance. Which corresponds the resource dictionary containing
* the concern font.
* @param rowText String instance of the tooltip row.
*/
FontToolTip(PDResources resources, String rowText)
{
initUI(extractFontReference(rowText), resources);
}
private void initUI(String fontReferenceName, PDResources resources)
{<FILL_FUNCTION_BODY>}
private String extractFontReference(String rowText)
{
return rowText.trim().split(" ")[0].substring(1);
}
@Override
public String getToolTipText()
{
return markup;
}
}
|
PDFont font = null;
for (COSName name: resources.getFontNames())
{
if (name.getName().equals(fontReferenceName))
{
try
{
font = resources.getFont(name);
}
catch (IOException e)
{
LOG.error(e.getMessage(), e);
}
}
}
if (font != null)
{
markup = "<html>" + font.getName() + "</html>";
}
| 225
| 134
| 359
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/streampane/tooltip/GToolTip.java
|
GToolTip
|
createMarkUp
|
class GToolTip extends ColorToolTip
{
/**
* Constructor.
* @param rowText String instance.
*/
GToolTip(String rowText)
{
createMarkUp(rowText);
}
private void createMarkUp(String rowText)
{<FILL_FUNCTION_BODY>}
}
|
float[] colorValues = extractColorValues(rowText);
if (colorValues != null)
{
Color color = new Color(colorValues[0], colorValues[0], colorValues[0]);
setToolTipText(getMarkUp(colorHexValue(color)));
}
| 88
| 74
| 162
|
<methods>public java.lang.String getToolTipText() ,public void setToolTipText(java.lang.String) <variables>private java.lang.String toolTipText
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/streampane/tooltip/KToolTip.java
|
KToolTip
|
getICCProfile
|
class KToolTip extends ColorToolTip
{
private static final Logger LOG = LogManager.getLogger(KToolTip.class);
/**
* Constructor.
* @param rowText String instance.
*/
KToolTip(String rowText)
{
createMarkUp(rowText);
}
private void createMarkUp(String rowText)
{
float[] colorValues = extractColorValues(rowText);
if (colorValues != null)
{
try
{
float[] rgbValues = getICCColorSpace().toRGB(colorValues);
setToolTipText(getMarkUp(colorHexValue(new Color(rgbValues[0], rgbValues[1], rgbValues[2]))));
}
catch (IOException e)
{
LOG.error(e.getMessage(), e);
}
}
}
ICC_ColorSpace getICCColorSpace() throws IOException
{
// loads the ICC color profile for CMYK
ICC_Profile iccProfile = getICCProfile();
if (iccProfile == null)
{
throw new IOException("Default CMYK color profile could not be loaded");
}
return new ICC_ColorSpace(iccProfile);
}
ICC_Profile getICCProfile() throws IOException
{<FILL_FUNCTION_BODY>}
}
|
// Adobe Acrobat uses "U.S. Web Coated (SWOP) v2" as the default
// CMYK profile, however it is not available under an open license.
// Instead, the "ISO Coated v2 300% (basICColor)" is used, which
// is an open alternative to the "ISO Coated v2 300% (ECI)" profile.
String name = "/org/apache/pdfbox/resources/icc/ISOcoated_v2_300_bas.icc";
URL url = PDDeviceCMYK.class.getResource(name);
if (url == null)
{
throw new IOException("Error loading resource: " + name);
}
try (InputStream input = url.openStream())
{
return ICC_Profile.getInstance(input);
}
| 351
| 214
| 565
|
<methods>public java.lang.String getToolTipText() ,public void setToolTipText(java.lang.String) <variables>private java.lang.String toolTipText
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/streampane/tooltip/RGToolTip.java
|
RGToolTip
|
createMarkUp
|
class RGToolTip extends ColorToolTip
{
/**
* Constructor.
* @param rowText String instance.
*/
RGToolTip(String rowText)
{
createMarkUp(rowText);
}
private void createMarkUp(String rowText)
{<FILL_FUNCTION_BODY>}
}
|
float[] rgbValues = extractColorValues(rowText);
if (rgbValues != null)
{
Color color = new Color(rgbValues[0], rgbValues[1], rgbValues[2]);
setToolTipText(getMarkUp(colorHexValue(color)));
}
| 90
| 79
| 169
|
<methods>public java.lang.String getToolTipText() ,public void setToolTipText(java.lang.String) <variables>private java.lang.String toolTipText
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/streampane/tooltip/SCNToolTip.java
|
SCNToolTip
|
createMarkUp
|
class SCNToolTip extends ColorToolTip
{
private static final Logger LOG = LogManager.getLogger(SCNToolTip.class);
/**
* Constructor.
* @param rowText String instance.
*/
SCNToolTip(PDResources resources, String colorSpaceName, String rowText)
{
createMarkUp(resources, colorSpaceName.substring(1).trim(), rowText);
}
private void createMarkUp(PDResources resources, String colorSpaceName, String rowText)
{<FILL_FUNCTION_BODY>}
}
|
PDColorSpace colorSpace = null;
try
{
colorSpace = resources.getColorSpace(COSName.getPDFName(colorSpaceName));
}
catch (IOException e)
{
LOG.error(e.getMessage(), e);
}
if (colorSpace instanceof PDPattern)
{
setToolTipText("<html>Pattern</html>");
return;
}
if (colorSpace != null)
{
try
{
float[] rgbValues = colorSpace.toRGB(extractColorValues(rowText));
if (rgbValues != null)
{
Color color = new Color(rgbValues[0], rgbValues[1], rgbValues[2]);
setToolTipText(getMarkUp(colorHexValue(color)));
}
}
catch (IOException e)
{
LOG.error(e.getMessage(), e);
}
}
| 144
| 242
| 386
|
<methods>public java.lang.String getToolTipText() ,public void setToolTipText(java.lang.String) <variables>private java.lang.String toolTipText
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/stringpane/StringPane.java
|
StringPane
|
getTextString
|
class StringPane
{
private static final String TEXT_TAB = "Text View";
private static final String HEX_TAB = "Hex view";
private final JTabbedPane tabbedPane;
public StringPane(COSString cosString)
{
tabbedPane = new JTabbedPane();
tabbedPane.setPreferredSize(new Dimension(300, 500));
tabbedPane.addTab(TEXT_TAB, createTextView(cosString));
tabbedPane.addTab(HEX_TAB, createHexView(cosString));
}
private JTextPane createTextView(COSString cosString)
{
JTextPane textPane = new JTextPane();
textPane.setText(getTextString(cosString));
textPane.setEditable(false);
return textPane;
}
private JComponent createHexView(COSString cosString)
{
HexView hexView = new HexView(cosString.getBytes());
return hexView.getPane();
}
private String getTextString(COSString cosString)
{<FILL_FUNCTION_BODY>}
public JTabbedPane getPane()
{
return tabbedPane;
}
}
|
String text = cosString.getString();
for (char c : text.toCharArray())
{
if (Character.isISOControl(c) && c != '\n' && c != '\r' && c != '\t')
{
text = "<" + cosString.toHexString() + ">";
break;
}
}
return text;
| 323
| 100
| 423
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/treestatus/TreeStatus.java
|
TreeStatus
|
generatePath
|
class TreeStatus
{
private Object rootNode;
private TreeStatus()
{
}
/**
* Constructor.
*
* @param rootNode the root node of the tree which will be used to construct a treepath from a
* tree status string.
*/
public TreeStatus(Object rootNode)
{
this.rootNode = rootNode;
}
/**
* Provides status string for a TreePath instance.
* @param path TreePath instance.
* @return pathString.
*/
public String getStringForPath(TreePath path)
{
return generatePathString(path);
}
/**
* Provides TreePath for a given status string. In case of invalid string returns null.
*
* @param statusString the status string of the TreePath
* @return path.
*/
public TreePath getPathForString(String statusString)
{
return generatePath(statusString);
}
/**
* Constructs a status string from the path.
* @param path
* @return the status string.
*/
private String generatePathString(TreePath path)
{
StringBuilder pathStringBuilder = new StringBuilder();
while (path.getParentPath() != null)
{
Object object = path.getLastPathComponent();
pathStringBuilder.insert(0, "/" + getObjectName(object));
path = path.getParentPath();
}
pathStringBuilder.delete(0, 1);
return pathStringBuilder.toString();
}
/**
* Constructs TreePath from Status String.
* @param pathString
* @return a TreePath, or null if there is an error.
*/
private TreePath generatePath(String pathString)
{<FILL_FUNCTION_BODY>}
/**
* Get the object name of a tree node. If the given node of the tree is a MapEntry, its key is
* used as node identifier; if it is an ArrayEntry, then its index is used as identifier.
*
* @param treeNode node of a tree.
* @return the name of the node.
* @throws IllegalArgumentException if there is an unknown treeNode type.
*/
private String getObjectName(Object treeNode)
{
if (treeNode instanceof MapEntry)
{
MapEntry entry = (MapEntry) treeNode;
COSName key = entry.getKey();
return key.getName();
}
else if (treeNode instanceof ArrayEntry)
{
ArrayEntry entry = (ArrayEntry) treeNode;
return "[" + entry.getIndex() + "]";
}
else if (treeNode instanceof PageEntry)
{
PageEntry entry = (PageEntry) treeNode;
return entry.getPath();
}
else if (treeNode instanceof XrefEntry)
{
XrefEntry entry = (XrefEntry) treeNode;
return entry.getPath();
}
throw new IllegalArgumentException("Unknown treeNode type: " + treeNode.getClass().getName());
}
/**
* Parses a string and lists all the nodes.
*
* @param path a tree path.
* @return a list of nodes, or null if there is an empty node.
*/
private List<String> parsePathString(String path)
{
List<String> nodes = new ArrayList<>();
for (String node : path.split("/"))
{
node = node.trim();
if (node.startsWith("["))
{
node = node.replace("]", "").replace("[", "").trim();
}
if (node.isEmpty())
{
return null;
}
nodes.add(node);
}
return nodes;
}
/**
* An object is searched in the tree structure using the identifiers parsed earlier step.
* @param obj
* @param searchStr
* @return
*/
private Object searchNode(Object obj, String searchStr)
{
if (obj instanceof MapEntry)
{
obj = ((MapEntry) obj).getValue();
}
else if (obj instanceof ArrayEntry)
{
obj = ((ArrayEntry) obj).getValue();
}
else if (obj instanceof XrefEntry)
{
obj = ((XrefEntry) obj).getObject();
}
if (obj instanceof COSObject)
{
obj = ((COSObject) obj).getObject();
}
if (obj instanceof COSDictionary)
{
COSDictionary dic = (COSDictionary) obj;
if (dic.containsKey(searchStr))
{
MapEntry entry = new MapEntry();
entry.setKey(COSName.getPDFName(searchStr));
entry.setValue(dic.getDictionaryObject(searchStr));
entry.setItem(dic.getItem(searchStr));
return entry;
}
}
else if (obj instanceof COSArray)
{
int index = Integer.parseInt(searchStr);
COSArray array = (COSArray) obj;
if (index <= array.size() - 1)
{
ArrayEntry entry = new ArrayEntry();
entry.setIndex(index);
entry.setValue(array.getObject(index));
entry.setItem(array.get(index));
return entry;
}
}
return null;
}
}
|
List<String> nodes = parsePathString(pathString);
if (nodes == null)
{
return null;
}
Object obj = rootNode;
TreePath treePath = new TreePath(obj);
for (String node : nodes)
{
obj = searchNode(obj, node);
if (obj == null)
{
return null;
}
treePath = treePath.pathByAddingChild(obj);
}
return treePath;
| 1,373
| 125
| 1,498
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/treestatus/TreeStatusPane.java
|
TreeStatusPane
|
init
|
class TreeStatusPane implements TreeSelectionListener
{
private TreeStatus statusObj;
private final JTree tree;
private JTextField statusField;
private JPanel panel;
private Border defaultBorder;
private Border errorBorder;
private final Action textInputAction = new AbstractAction()
{
private static final long serialVersionUID = 3547209849264145654L;
@Override
public void actionPerformed(ActionEvent actionEvent)
{
TreePath path = statusObj.getPathForString(statusField.getText());
if (path != null)
{
tree.setSelectionPath(path);
tree.scrollPathToVisible(path);
tree.requestFocusInWindow();
}
else
{
statusField.setBorder(errorBorder);
}
}
};
/**
* Constructor.
* @param targetTree The tree instance that this status pane will correspond.
*/
public TreeStatusPane(JTree targetTree)
{
tree = targetTree;
init();
}
private void init()
{<FILL_FUNCTION_BODY>}
/**
* Return the panel of this TreeStatusPane.
* @return JPanel instance.
*/
public JPanel getPanel()
{
return panel;
}
/**
* In case of document changing this should be called to update TreeStatus value of the pane.
* @param statusObj TreeStatus instance.
*/
public void updateTreeStatus(TreeStatus statusObj)
{
statusField.setEditable(true);
this.statusObj = statusObj;
updateText(null);
}
private void updateText(String statusString)
{
statusField.setText(statusString);
if (!statusField.getBorder().equals(defaultBorder))
{
statusField.setBorder(defaultBorder);
}
}
/**
* Tree selection change listener which updates status string.
*
* @param treeSelectionEvent the selection event
*/
@Override
public void valueChanged(TreeSelectionEvent treeSelectionEvent)
{
TreePath path = treeSelectionEvent.getPath();
updateText(statusObj.getStringForPath(path));
}
}
|
panel = new JPanel(new BorderLayout());
statusField = new JTextField();
statusField.setEditable(false);
int treePathFontHeight = Integer.parseInt(PDFDebugger.configuration.getProperty(
"treePathFontHeight", Integer.toString(statusField.getFont().getSize())));
statusField.setFont(statusField.getFont().deriveFont((float) treePathFontHeight));
panel.add(statusField);
defaultBorder = new BevelBorder(BevelBorder.LOWERED);
errorBorder = new BevelBorder(BevelBorder.LOWERED, Color.RED, Color.RED);
statusField.setAction(textInputAction);
tree.addTreeSelectionListener(this);
| 582
| 182
| 764
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/DebugLogAppender.java
|
DebugLogAppender
|
setupCustomLogger
|
class DebugLogAppender extends AbstractAppender
{
protected DebugLogAppender(String name, Filter filter, Layout<? extends Serializable> layout,
final boolean ignoreExceptions)
{
super(name, filter, layout, ignoreExceptions, Property.EMPTY_ARRAY);
}
@PluginFactory
public static DebugLogAppender createAppender(@PluginAttribute("name") String name,
@PluginElement("Filter") Filter filter,
@PluginElement("Layout") Layout<? extends Serializable> layout,
@PluginAttribute("ignoreExceptions") boolean ignoreExceptions) {
return new DebugLogAppender(name, filter, layout, ignoreExceptions);
}
@Override
public void append(LogEvent event)
{
// forward to your logging dialog box here.
LogDialog.instance().log(event.getLoggerName(), event.getLevel().name(),
event.getMessage().getFormattedMessage(), event.getThrown());
}
public static void setupCustomLogger()
{<FILL_FUNCTION_BODY>}
}
|
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory
.newConfigurationBuilder();
AppenderComponentBuilder appenderBuilder = builder.newAppender("Custom", "DebugLogAppender");
appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute("pattern",
"%d [%t] %-5level: %msg%n%throwable"));
builder.add(appenderBuilder);
builder.add(builder.newRootLogger(Level.INFO).add(builder.newAppenderRef("Custom")));
Configurator.initialize(builder.build());
| 264
| 144
| 408
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/DocumentEntry.java
|
DocumentEntry
|
getPage
|
class DocumentEntry
{
private final PDDocument doc;
private final String filename;
public DocumentEntry(PDDocument doc, String filename)
{
this.doc = doc;
this.filename = filename;
}
public int getPageCount()
{
return doc.getPages().getCount();
}
public PageEntry getPage(int index)
{<FILL_FUNCTION_BODY>}
public int indexOf(PageEntry page)
{
return page.getPageNum() - 1;
}
@Override
public String toString()
{
return filename;
}
}
|
PDPage page = doc.getPages().get(index);
String pageLabel = PDFDebugger.getPageLabel(doc, index);
return new PageEntry(page.getCOSObject(), index + 1, pageLabel);
| 172
| 58
| 230
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/FileOpenSaveDialog.java
|
FileOpenSaveDialog
|
saveFile
|
class FileOpenSaveDialog
{
private final Component mainUI;
private static final JFileChooser FILE_CHOOSER = new JFileChooser()
{
@Override
public void approveSelection()
{
File selectedFile = getSelectedFile();
if (selectedFile.exists() && getDialogType() == JFileChooser.SAVE_DIALOG)
{
int result = JOptionPane.showConfirmDialog(this,
"Do you want to overwrite?",
"File already exists",
JOptionPane.YES_NO_OPTION);
if (result != JOptionPane.YES_OPTION)
{
cancelSelection();
return;
}
}
super.approveSelection();
}
};
/**
* Constructor.
* @param parentUI the main UI (JFrame) on top of which File open/save dialog should open.
* @param fileFilter file Filter, null is allowed when no filter is applicable.
*/
public FileOpenSaveDialog(Component parentUI, FileFilter fileFilter)
{
mainUI = parentUI;
FILE_CHOOSER.resetChoosableFileFilters();
FILE_CHOOSER.setFileFilter(fileFilter);
}
/**
* Saves data into a file after the user is prompted to choose the destination.
*
* @param bytes byte array to be saved in a file.
* @param extension file extension.
* @return true if the file is saved successfully or false if failed.
* @throws IOException if there is an error in creation of the file.
*/
public boolean saveFile(byte[] bytes, String extension) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Saves document into a .pdf file after the user is prompted to choose the destination.
*
* @param document document to be saved in a .pdf file.
* @param extension file extension.
* @return true if the file is saved successfully or false if failed.
* @throws IOException if there is an error in creation of the file.
*/
public boolean saveDocument(PDDocument document, String extension) throws IOException
{
int result = FILE_CHOOSER.showSaveDialog(mainUI);
if (result == JFileChooser.APPROVE_OPTION)
{
String filename = FILE_CHOOSER.getSelectedFile().getAbsolutePath();
if (!filename.endsWith(extension))
{
filename += "." + extension;
}
document.setAllSecurityToBeRemoved(true);
document.save(filename);
return true;
}
return false;
}
/**
* open a file prompting user to select the file.
* @return the file opened.
* @throws IOException if there is error in opening the file.
*/
public File openFile() throws IOException
{
int result = FILE_CHOOSER.showOpenDialog(mainUI);
if (result == JFileChooser.APPROVE_OPTION)
{
return FILE_CHOOSER.getSelectedFile();
}
return null;
}
}
|
int result = FILE_CHOOSER.showSaveDialog(mainUI);
if (result == JFileChooser.APPROVE_OPTION)
{
String filename = FILE_CHOOSER.getSelectedFile().getAbsolutePath();
if (extension != null && !filename.endsWith(extension))
{
filename += "." + extension;
}
Files.write(Paths.get(filename), bytes);
return true;
}
return false;
| 799
| 125
| 924
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/ImageTypeMenu.java
|
ImageTypeMenu
|
getImageType
|
class ImageTypeMenu extends MenuBase
{
public static final String IMAGETYPE_RGB = "RGB";
public static final String IMAGETYPE_ARGB = "ARGB";
public static final String IMAGETYPE_GRAY = "Gray";
public static final String IMAGETYPE_BITONAL = "Bitonal";
private static ImageTypeMenu instance;
private JRadioButtonMenuItem rgbItem;
private JRadioButtonMenuItem argbItem;
private JRadioButtonMenuItem grayItem;
private JRadioButtonMenuItem bitonalItem;
/**
* Constructor.
*/
private ImageTypeMenu()
{
setMenu(createMenu());
}
/**
* Provides the ImageTypeMenu instance.
* @return ImageTypeMenu instance.
*/
public static ImageTypeMenu getInstance()
{
if (instance == null)
{
instance = new ImageTypeMenu();
}
return instance;
}
/**
* Set the image type selection.
* @param selection String instance.
*/
public void setImageTypeSelection(String selection)
{
switch (selection)
{
case IMAGETYPE_RGB:
rgbItem.setSelected(true);
break;
case IMAGETYPE_ARGB:
argbItem.setSelected(true);
break;
case IMAGETYPE_GRAY:
grayItem.setSelected(true);
break;
case IMAGETYPE_BITONAL:
bitonalItem.setSelected(true);
break;
default:
throw new IllegalArgumentException("Invalid ImageType selection: " + selection);
}
}
public static boolean isImageTypeMenu(String actionCommand)
{
return IMAGETYPE_RGB.equals(actionCommand) || IMAGETYPE_ARGB.equals(actionCommand) ||
IMAGETYPE_GRAY.equals(actionCommand) || IMAGETYPE_BITONAL.equals(actionCommand);
}
public static ImageType getImageType()
{
if (instance.argbItem.isSelected())
{
return ImageType.ARGB;
}
if (instance.grayItem.isSelected())
{
return ImageType.GRAY;
}
if (instance.bitonalItem.isSelected())
{
return ImageType.BINARY;
}
return ImageType.RGB;
}
public static ImageType getImageType(String actionCommand)
{<FILL_FUNCTION_BODY>}
private JMenu createMenu()
{
JMenu menu = new JMenu();
menu.setText("Image type");
rgbItem = new JRadioButtonMenuItem();
argbItem = new JRadioButtonMenuItem();
grayItem = new JRadioButtonMenuItem();
bitonalItem = new JRadioButtonMenuItem();
rgbItem.setSelected(true);
ButtonGroup bg = new ButtonGroup();
bg.add(rgbItem);
bg.add(argbItem);
bg.add(grayItem);
bg.add(bitonalItem);
rgbItem.setText(IMAGETYPE_RGB);
argbItem.setText(IMAGETYPE_ARGB);
grayItem.setText(IMAGETYPE_GRAY);
bitonalItem.setText(IMAGETYPE_BITONAL);
menu.add(rgbItem);
menu.add(argbItem);
menu.add(grayItem);
menu.add(bitonalItem);
return menu;
}
}
|
switch (actionCommand)
{
case IMAGETYPE_RGB:
return ImageType.RGB;
case IMAGETYPE_ARGB:
return ImageType.ARGB;
case IMAGETYPE_GRAY:
return ImageType.GRAY;
case IMAGETYPE_BITONAL:
return ImageType.BINARY;
default:
throw new IllegalArgumentException("Invalid ImageType actionCommand: " + actionCommand);
}
| 919
| 120
| 1,039
|
<methods>public void addMenuListeners(java.awt.event.ActionListener) ,public javax.swing.JMenu getMenu() ,public void setEnableMenu(boolean) <variables>private javax.swing.JMenu menu
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/ImageUtil.java
|
ImageUtil
|
getRotatedImage
|
class ImageUtil
{
private ImageUtil()
{
}
/**
* Return an image rotated by a multiple of 90°.
*
* @param image The image to rotate.
* @param rotation The rotation in degrees.
* @return The rotated image.
* @throws IllegalArgumentException if the angle isn't a multiple of 90°.
*/
public static BufferedImage getRotatedImage(BufferedImage image, int rotation)
{<FILL_FUNCTION_BODY>}
}
|
int width = image.getWidth();
int height = image.getHeight();
int x = 0;
int y = 0;
BufferedImage rotatedImage;
switch ((rotation + 360) % 360)
{
case 0:
return image;
case 90:
x = height;
rotatedImage = new BufferedImage(height, width, image.getType());
break;
case 270:
y = width;
rotatedImage = new BufferedImage(height, width, image.getType());
break;
case 180:
x = width;
y = height;
rotatedImage = new BufferedImage(width, height, image.getType());
break;
default:
throw new IllegalArgumentException("Only multiple of 90° are supported");
}
Graphics2D g = (Graphics2D) rotatedImage.getGraphics();
g.translate(x, y);
g.rotate(Math.toRadians(rotation));
g.drawImage(image, 0, 0, null);
g.dispose();
return rotatedImage;
| 136
| 296
| 432
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/LogDialog.java
|
LogDialog
|
log
|
class LogDialog extends JDialog
{
private static LogDialog instance;
private final JLabel logLabel;
private final JTextPane textPane;
private final JScrollPane scrollPane;
private int fatalCount = 0;
private int errorCount = 0;
private int warnCount = 0;
private int otherCount = 0;
private int exceptionCount = 0;
private LogDialog(Frame owner, JLabel logLabel)
{
super(owner);
this.logLabel = logLabel;
textPane = new JTextPane();
scrollPane = new JScrollPane(textPane);
getContentPane().add(scrollPane);
this.pack();
}
public static void init(Frame owner, JLabel logLabel)
{
instance = new LogDialog(owner, logLabel);
}
public static LogDialog instance()
{
return instance;
}
public void log(String name, String level, Object o, Throwable throwable)
{<FILL_FUNCTION_BODY>}
private void updateStatusBar()
{
List<String> infos = new ArrayList<>();
if (exceptionCount > 0)
{
infos.add(exceptionCount + " exception" + (errorCount > 1 ? "s" : ""));
}
if (fatalCount > 0)
{
infos.add(errorCount + " error" + (errorCount > 1 ? "s" : ""));
}
if (errorCount > 0)
{
infos.add(errorCount + " error" + (errorCount > 1 ? "s" : ""));
}
if (warnCount > 0)
{
infos.add(warnCount + " warning" + (warnCount > 1 ? "s" : ""));
}
if (otherCount > 0)
{
infos.add(otherCount + " message" + (otherCount > 1 ? "s" : ""));
}
String info = String.join(", ", infos);
logLabel.setText(info);
}
public void clear()
{
fatalCount = 0;
errorCount = 0;
warnCount = 0;
otherCount = 0;
exceptionCount = 0;
textPane.setText("");
logLabel.setText("");
}
// these two just to avoid the "overridable method call in constructor" warning
@Override
public final Container getContentPane()
{
return super.getContentPane();
}
@Override
public final void pack()
{
super.pack();
}
}
|
StyledDocument doc = textPane.getStyledDocument();
String levelText;
SimpleAttributeSet levelStyle = new SimpleAttributeSet();
switch (level)
{
case "FATAL":
levelText = "Fatal";
StyleConstants.setForeground(levelStyle, Color.WHITE);
StyleConstants.setBackground(levelStyle, Color.BLACK);
fatalCount++;
break;
case "ERROR":
levelText = "Error";
StyleConstants.setForeground(levelStyle, new Color(0xFF291F));
StyleConstants.setBackground(levelStyle, new Color(0xFFF0F0));
errorCount++;
break;
case "WARN":
levelText = "Warning";
StyleConstants.setForeground(levelStyle, new Color(0x614201));
StyleConstants.setBackground(levelStyle, new Color(0xFFFCE5));
warnCount++;
break;
case "INFO":
levelText = "Info";
StyleConstants.setForeground(levelStyle, new Color(0x203261));
StyleConstants.setBackground(levelStyle, new Color(0xE2E8FF));
otherCount++;
break;
case "DEBUG":
levelText = "Debug";
StyleConstants.setForeground(levelStyle, new Color(0x32612E));
StyleConstants.setBackground(levelStyle, new Color(0xF4FFEC));
otherCount++;
break;
case "TRACE":
levelText = "Trace";
StyleConstants.setForeground(levelStyle, new Color(0x64438D));
StyleConstants.setBackground(levelStyle, new Color(0xFEF3FF));
otherCount++;
break;
default:
throw new Error(level);
}
SimpleAttributeSet nameStyle = new SimpleAttributeSet();
StyleConstants.setForeground(nameStyle, new Color(0x6A6A6A));
String shortName = name.substring(name.lastIndexOf('.') + 1);
String message = o == null ? "(null)" : o.toString();
if (throwable != null)
{
StringWriter sw = new StringWriter();
throwable.printStackTrace(new PrintWriter(sw));
message += "\n " + sw;
exceptionCount++;
}
try
{
doc.insertString(doc.getLength(), " " + levelText + " ", levelStyle);
doc.insertString(doc.getLength(), " [" + shortName + "]", nameStyle);
doc.insertString(doc.getLength(), " " + message + "\n", null);
}
catch (BadLocationException e)
{
throw new Error(e);
}
textPane.setCaretPosition(doc.getLength());
// update status bar with new counts
updateStatusBar();
| 672
| 744
| 1,416
|
<methods>public void <init>() ,public void <init>(java.awt.Frame) ,public void <init>(java.awt.Dialog) ,public void <init>(java.awt.Window) ,public void <init>(java.awt.Frame, boolean) ,public void <init>(java.awt.Frame, java.lang.String) ,public void <init>(java.awt.Dialog, boolean) ,public void <init>(java.awt.Dialog, java.lang.String) ,public void <init>(java.awt.Window, java.awt.Dialog.ModalityType) ,public void <init>(java.awt.Window, java.lang.String) ,public void <init>(java.awt.Frame, java.lang.String, boolean) ,public void <init>(java.awt.Dialog, java.lang.String, boolean) ,public void <init>(java.awt.Window, java.lang.String, java.awt.Dialog.ModalityType) ,public void <init>(java.awt.Frame, java.lang.String, boolean, java.awt.GraphicsConfiguration) ,public void <init>(java.awt.Dialog, java.lang.String, boolean, java.awt.GraphicsConfiguration) ,public void <init>(java.awt.Window, java.lang.String, java.awt.Dialog.ModalityType, java.awt.GraphicsConfiguration) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.awt.Container getContentPane() ,public int getDefaultCloseOperation() ,public java.awt.Component getGlassPane() ,public java.awt.Graphics getGraphics() ,public javax.swing.JMenuBar getJMenuBar() ,public javax.swing.JLayeredPane getLayeredPane() ,public javax.swing.JRootPane getRootPane() ,public javax.swing.TransferHandler getTransferHandler() ,public static boolean isDefaultLookAndFeelDecorated() ,public void remove(java.awt.Component) ,public void repaint(long, int, int, int, int) ,public void setContentPane(java.awt.Container) ,public void setDefaultCloseOperation(int) ,public static void setDefaultLookAndFeelDecorated(boolean) ,public void setGlassPane(java.awt.Component) ,public void setJMenuBar(javax.swing.JMenuBar) ,public void setLayeredPane(javax.swing.JLayeredPane) ,public void setLayout(java.awt.LayoutManager) ,public void setTransferHandler(javax.swing.TransferHandler) ,public void update(java.awt.Graphics) <variables>protected javax.accessibility.AccessibleContext accessibleContext,private int defaultCloseOperation,private static final java.lang.Object defaultLookAndFeelDecoratedKey,protected javax.swing.JRootPane rootPane,protected boolean rootPaneCheckingEnabled,private javax.swing.TransferHandler transferHandler
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/MapEntry.java
|
MapEntry
|
toString
|
class MapEntry
{
private COSName key;
private COSBase value;
private COSBase item;
/**
* Get the key for this entry.
*
* @return The entry's key.
*/
public COSName getKey()
{
return key;
}
/**
* This will set the key for this entry.
*
* @param k the new key for this entry.
*/
public void setKey(COSName k)
{
key = k;
}
/**
* This will get the value for this entry.
*
* @return The value for this entry.
*/
public COSBase getValue()
{
return value;
}
/**
* This will get the value for this entry.
*
* @return The value for this entry.
*/
public COSBase getItem()
{
return item;
}
/**
* This will set the value for this entry.
*
* @param val the new value for this entry.
*/
public void setValue(COSBase val)
{
this.value = val;
}
/**
* This will set the value for this entry.
*
* @param val the new value for this entry.
*/
public void setItem(COSBase val)
{
this.item = val;
}
/**
* This will output a string representation of this class.
*
* @return A string representation of this class.
*/
@Override
public String toString()
{<FILL_FUNCTION_BODY>}
}
|
if (key != null)
{
return key.getName();
}
return "(null)";
| 431
| 33
| 464
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/MenuBase.java
|
MenuBase
|
addMenuListeners
|
class MenuBase
{
private JMenu menu = null;
final void setMenu(JMenu menu)
{
this.menu = menu;
}
/**
* Provide the JMenu instance of the ZoomMenu.
*
* @return JMenu instance.
*/
public JMenu getMenu()
{
return this.menu;
}
/**
* Set if the menu should be enabled or disabled.
*
* @param isEnable boolean instance.
*/
public void setEnableMenu(boolean isEnable)
{
menu.setEnabled(isEnable);
}
/**
* Add the ActionListener for the menu items.
*
* @param listener ActionListener.
*/
public void addMenuListeners(ActionListener listener)
{<FILL_FUNCTION_BODY>}
private void removeActionListeners(JMenuItem menuItem)
{
for (ActionListener listener : menuItem.getActionListeners())
{
menuItem.removeActionListener(listener);
}
}
}
|
for (Component comp : menu.getMenuComponents())
{
JMenuItem menuItem = (JMenuItem) comp;
removeActionListeners(menuItem);
menuItem.addActionListener(listener);
}
| 276
| 60
| 336
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/PageEntry.java
|
PageEntry
|
getPath
|
class PageEntry
{
private final COSDictionary dict;
private final int pageNum;
private final String pageLabel;
public PageEntry(COSDictionary page, int pageNum, String pageLabel)
{
dict = page;
this.pageNum = pageNum;
this.pageLabel = pageLabel;
}
public COSDictionary getDict()
{
return dict;
}
public int getPageNum()
{
return pageNum;
}
@Override
public String toString()
{
return "Page: " + pageNum + (pageLabel == null ? "" : " - " + pageLabel);
}
public String getPath()
{<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append("Root/Pages");
COSDictionary node = dict;
while (node.containsKey(COSName.PARENT))
{
COSDictionary parent = node.getCOSDictionary(COSName.PARENT);
if (parent == null)
{
return "";
}
COSArray kids = parent.getCOSArray(COSName.KIDS);
if (kids == null)
{
return "";
}
int idx = kids.indexOfObject(node);
sb.append("/Kids/[").append(idx).append("]");
node = parent;
}
return sb.toString();
| 199
| 179
| 378
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/PrintDpiMenu.java
|
PrintDpiMenuItem
|
getInstance
|
class PrintDpiMenuItem extends JRadioButtonMenuItem
{
private static final long serialVersionUID = -475209538362541000L;
private final int dpi;
PrintDpiMenuItem(String text, int dpi)
{
super(text);
this.dpi = dpi;
}
}
private static final int[] DPIS = { 0, 100, 200, 300, 600, 1200 };
private static PrintDpiMenu instance;
private final JMenu menu;
/**
* Constructor.
*/
private PrintDpiMenu()
{
menu = new JMenu("Print dpi");
ButtonGroup bg = new ButtonGroup();
for (int dpi : DPIS)
{
PrintDpiMenuItem printDpiMenuItem = new PrintDpiMenuItem(dpi == 0 ? "auto" : "" + dpi, dpi);
bg.add(printDpiMenuItem);
menu.add(printDpiMenuItem);
}
changeDpiSelection(0);
setMenu(menu);
}
/**
* Provides the DpiMenu instance.
*
* @return DpiMenu instance.
*/
public static PrintDpiMenu getInstance()
{<FILL_FUNCTION_BODY>
|
if (instance == null)
{
instance = new PrintDpiMenu();
}
return instance;
| 358
| 32
| 390
|
<methods>public void addMenuListeners(java.awt.event.ActionListener) ,public javax.swing.JMenu getMenu() ,public void setEnableMenu(boolean) <variables>private javax.swing.JMenu menu
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/ReaderBottomPanel.java
|
ReaderBottomPanel
|
mouseClicked
|
class ReaderBottomPanel extends JPanel
{
private JLabel statusLabel = null;
private JLabel logLabel = null;
public ReaderBottomPanel()
{
BorderLayout layout = new BorderLayout();
this.setLayout(layout);
statusLabel = new JLabel();
statusLabel.setText("Ready");
this.add(statusLabel, BorderLayout.WEST);
logLabel = new JLabel();
logLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
logLabel.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{<FILL_FUNCTION_BODY>}
});
this.add(logLabel, BorderLayout.EAST);
this.setBorder(new EmptyBorder(0, 5, 0, 5));
this.setPreferredSize(new Dimension(1000, 24));
}
public JLabel getStatusLabel()
{
return statusLabel;
}
public JLabel getLogLabel()
{
return logLabel;
}
}
|
Window viewer = LogDialog.instance().getOwner();
// show the log window
LogDialog.instance().setSize(800, 400);
LogDialog.instance().setVisible(true);
LogDialog.instance().setLocation(viewer.getLocationOnScreen().x + viewer.getWidth() / 2,
viewer.getLocationOnScreen().y + viewer.getHeight() / 2);
| 292
| 110
| 402
|
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/RecentFiles.java
|
RecentFiles
|
readHistoryFromPref
|
class RecentFiles
{
private static final String KEY = "recent_files_";
private static final String PATH_KEY = "recent_files_%d_%d";
private static final String PIECES_LENGTH_KEY = "recent_files_%d_length";
private static final String HISTORY_LENGTH = "history_length";
private final Preferences pref;
private Queue<String> filePaths;
private final int maximum;
/**
* Constructor.
*
* @param className the class for which this Recentfiles object is created and it will be used
* to create preference instance.
* @param maximumFile the number of recent files to remember.
*/
public RecentFiles(Class<?> className, int maximumFile)
{
this.maximum = maximumFile;
this.pref = Preferences.userNodeForPackage(className);
filePaths = readHistoryFromPref();
if (filePaths == null)
{
filePaths = new ArrayDeque<>();
}
}
/**
* Clear the previous recent file history.
*/
public void removeAll()
{
filePaths.clear();
}
/**
* Check if file history is empty.
*
* @return if history is empty return true otherwise return false.
*/
public boolean isEmpty()
{
return filePaths.isEmpty();
}
/**
* Add a new file in recent file history.
*
* @param path path to the file. this path means File#getPath() method returned String.
*/
public void addFile(String path)
{
if (filePaths.size() >= maximum + 1 && path != null)
{
filePaths.remove();
}
filePaths.add(path);
}
/**
* Remove a file from recent file history.
*
* @param path path string to the file. this path means File#getPath() method returned String.
*/
public void removeFile(String path)
{
filePaths.remove(path);
}
/**
* This gives the file in descending order where order is according to the time it is added.
* This checks for file's existence in file history.
*
* @return return the file paths in a List.
*/
public List<String> getFiles()
{
if (!isEmpty())
{
List<String> files = filePaths.stream().
filter(path -> new File(path).exists()).
collect(Collectors.toList());
if (files.size() > maximum)
{
files.remove(0);
}
return files;
}
return null;
}
/**
* This method save the present recent file history in the preference. To get the recent file
* history in next session this method must be called.
*
* @throws IOException if saving in preference doesn't success.
*/
public void close() throws IOException
{
writeHistoryToPref(filePaths);
}
private String[] breakString(String fullPath)
{
int allowedStringLength = Preferences.MAX_VALUE_LENGTH;
List<String> pieces = new ArrayList<>();
int beginIndex = 0;
int remainingLength = fullPath.length();
int endIndex = 0;
while (remainingLength > 0)
{
endIndex += Math.min(remainingLength, allowedStringLength);
pieces.add(fullPath.substring(beginIndex, endIndex));
beginIndex = endIndex;
remainingLength = fullPath.length() - endIndex;
}
return pieces.toArray(String[]::new);
}
private void writeHistoryToPref(Queue<String> filePaths)
{
if (filePaths.isEmpty())
{
return;
}
Preferences node = pref.node(KEY);
node.putInt(HISTORY_LENGTH, filePaths.size());
int fileCount = 1;
for (String path : filePaths)
{
String[] pieces = breakString(path);
node.putInt(String.format(PIECES_LENGTH_KEY, fileCount), pieces.length);
for (int i = 0; i < pieces.length; i++)
{
node.put(String.format(PATH_KEY, fileCount, i), pieces[i]);
}
fileCount++;
}
}
private Queue<String> readHistoryFromPref()
{<FILL_FUNCTION_BODY>}
}
|
Preferences node = pref.node(KEY);
int historyLength = node.getInt(HISTORY_LENGTH, 0);
if (historyLength == 0)
{
return null;
}
Queue<String> history = new ArrayDeque<>();
for (int i = 1; i <= historyLength; i++)
{
int totalPieces = node.getInt(String.format(PIECES_LENGTH_KEY, i), 0);
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < totalPieces; j++)
{
String piece = node.get(String.format(PATH_KEY, i, j), "");
stringBuilder.append(piece);
}
history.add(stringBuilder.toString());
}
return history;
| 1,162
| 210
| 1,372
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/RenderDestinationMenu.java
|
RenderDestinationMenu
|
setRenderDestinationSelection
|
class RenderDestinationMenu extends MenuBase
{
public static final String RENDER_DESTINATION_EXPORT = "Export";
public static final String RENDER_DESTINATION_PRINT = "Print";
public static final String RENDER_DESTINATION_VIEW = "View";
private static RenderDestinationMenu instance;
private JRadioButtonMenuItem exportItem;
private JRadioButtonMenuItem printItem;
private JRadioButtonMenuItem viewItem;
/**
* Constructor.
*/
private RenderDestinationMenu()
{
setMenu(createMenu());
}
/**
* Provides the RenderDestination instance.
* @return RenderDestination instance.
*/
public static RenderDestinationMenu getInstance()
{
if (instance == null)
{
instance = new RenderDestinationMenu();
}
return instance;
}
/**
* Set the render destination selection.
* @param selection String instance.
*/
public void setRenderDestinationSelection(String selection)
{<FILL_FUNCTION_BODY>}
public static boolean isRenderDestinationMenu(String actionCommand)
{
return RENDER_DESTINATION_EXPORT.equals(actionCommand) || RENDER_DESTINATION_PRINT.equals(actionCommand) ||
RENDER_DESTINATION_VIEW.equals(actionCommand);
}
public static RenderDestination getRenderDestination()
{
if (instance.printItem.isSelected())
{
return RenderDestination.PRINT;
}
if (instance.viewItem.isSelected())
{
return RenderDestination.VIEW;
}
return RenderDestination.EXPORT;
}
public static RenderDestination getRenderDestination(String actionCommand)
{
switch (actionCommand)
{
case RENDER_DESTINATION_EXPORT:
return RenderDestination.EXPORT;
case RENDER_DESTINATION_PRINT:
return RenderDestination.PRINT;
case RENDER_DESTINATION_VIEW:
return RenderDestination.VIEW;
default:
throw new IllegalArgumentException("Invalid RenderDestination actionCommand: " + actionCommand);
}
}
private JMenu createMenu()
{
JMenu menu = new JMenu();
menu.setText("Render destination");
exportItem = new JRadioButtonMenuItem();
printItem = new JRadioButtonMenuItem();
viewItem = new JRadioButtonMenuItem();
exportItem.setSelected(true);
ButtonGroup bg = new ButtonGroup();
bg.add(exportItem);
bg.add(printItem);
bg.add(viewItem);
exportItem.setText(RENDER_DESTINATION_EXPORT);
printItem.setText(RENDER_DESTINATION_PRINT);
viewItem.setText(RENDER_DESTINATION_VIEW);
menu.add(exportItem);
menu.add(printItem);
menu.add(viewItem);
return menu;
}
}
|
switch (selection)
{
case RENDER_DESTINATION_EXPORT:
exportItem.setSelected(true);
break;
case RENDER_DESTINATION_PRINT:
printItem.setSelected(true);
break;
case RENDER_DESTINATION_VIEW:
viewItem.setSelected(true);
break;
default:
throw new IllegalArgumentException("Invalid RenderDestination selection: " + selection);
}
| 818
| 124
| 942
|
<methods>public void addMenuListeners(java.awt.event.ActionListener) ,public javax.swing.JMenu getMenu() ,public void setEnableMenu(boolean) <variables>private javax.swing.JMenu menu
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/RotationMenu.java
|
RotationMenu
|
getRotationDegrees
|
class RotationMenu extends MenuBase
{
public static final String ROTATE_0_DEGREES = "0°";
public static final String ROTATE_90_DEGREES = "90°";
public static final String ROTATE_180_DEGREES = "180°";
public static final String ROTATE_270_DEGREES = "270°";
private static RotationMenu instance;
private JRadioButtonMenuItem rotate0Item;
private JRadioButtonMenuItem rotate90Item;
private JRadioButtonMenuItem rotate180Item;
private JRadioButtonMenuItem rotate270Item;
/**
* Constructor.
*/
private RotationMenu()
{
setMenu(createRotationMenu());
}
/**
* Provides the RotationMenu instance.
* @return RotationMenu instance.
*/
public static RotationMenu getInstance()
{
if (instance == null)
{
instance = new RotationMenu();
}
return instance;
}
/**
* Set the rotation selection.
* @param selection String instance.
*/
public void setRotationSelection(String selection)
{
switch (selection)
{
case ROTATE_0_DEGREES:
rotate0Item.setSelected(true);
break;
case ROTATE_90_DEGREES:
rotate90Item.setSelected(true);
break;
case ROTATE_180_DEGREES:
rotate180Item.setSelected(true);
break;
case ROTATE_270_DEGREES:
rotate270Item.setSelected(true);
break;
default:
throw new IllegalArgumentException("Invalid rotation selection: " + selection);
}
}
public static boolean isRotationMenu(String actionCommand)
{
return ROTATE_0_DEGREES.equals(actionCommand) || ROTATE_90_DEGREES.equals(actionCommand) ||
ROTATE_180_DEGREES.equals(actionCommand) || ROTATE_270_DEGREES.equals(actionCommand);
}
public static int getRotationDegrees()
{
if (instance.rotate90Item.isSelected())
{
return 90;
}
if (instance.rotate180Item.isSelected())
{
return 180;
}
if (instance.rotate270Item.isSelected())
{
return 270;
}
return 0;
}
public static int getRotationDegrees(String actionCommand)
{<FILL_FUNCTION_BODY>}
private JMenu createRotationMenu()
{
JMenu menu = new JMenu();
menu.setText("Rotation");
rotate0Item = new JRadioButtonMenuItem();
rotate90Item = new JRadioButtonMenuItem();
rotate180Item = new JRadioButtonMenuItem();
rotate270Item = new JRadioButtonMenuItem();
rotate0Item.setSelected(true);
ButtonGroup bg = new ButtonGroup();
bg.add(rotate0Item);
bg.add(rotate90Item);
bg.add(rotate180Item);
bg.add(rotate270Item);
rotate0Item.setText(ROTATE_0_DEGREES);
rotate90Item.setText(ROTATE_90_DEGREES);
rotate180Item.setText(ROTATE_180_DEGREES);
rotate270Item.setText(ROTATE_270_DEGREES);
menu.add(rotate0Item);
menu.add(rotate90Item);
menu.add(rotate180Item);
menu.add(rotate270Item);
return menu;
}
}
|
switch (actionCommand)
{
case ROTATE_0_DEGREES:
return 0;
case ROTATE_90_DEGREES:
return 90;
case ROTATE_180_DEGREES:
return 180;
case ROTATE_270_DEGREES:
return 270;
default:
throw new IllegalArgumentException("Invalid RotationDegrees actionCommand " + actionCommand);
}
| 1,039
| 130
| 1,169
|
<methods>public void addMenuListeners(java.awt.event.ActionListener) ,public javax.swing.JMenu getMenu() ,public void setEnableMenu(boolean) <variables>private javax.swing.JMenu menu
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/TreeViewMenu.java
|
TreeViewMenu
|
createTreeViewMenu
|
class TreeViewMenu extends MenuBase
{
public static final String VIEW_PAGES = "Show pages";
public static final String VIEW_STRUCTURE = "Internal structure";
public static final String VIEW_CROSS_REF_TABLE = "Cross reference table";
private static final List<String> validTreeModes = Arrays.asList(VIEW_PAGES, VIEW_STRUCTURE,
VIEW_CROSS_REF_TABLE);
private static TreeViewMenu instance;
private JRadioButtonMenuItem pagesItem;
private JRadioButtonMenuItem structureItem;
private JRadioButtonMenuItem crtItem;
/**
* Constructor.
*/
private TreeViewMenu()
{
setMenu(createTreeViewMenu());
}
/**
* Provides the TreeViewMenu instance.
*
* @return TreeViewMenu instance.
*/
public static TreeViewMenu getInstance()
{
if (instance == null)
{
instance = new TreeViewMenu();
}
return instance;
}
/**
* Set the tree view selection.
*
* @param selection String instance.
*/
public void setTreeViewSelection(String selection)
{
switch (selection)
{
case VIEW_PAGES:
pagesItem.setSelected(true);
break;
case VIEW_STRUCTURE:
structureItem.setSelected(true);
break;
case VIEW_CROSS_REF_TABLE:
crtItem.setSelected(true);
break;
default:
throw new IllegalArgumentException("Invalid tree view selection: " + selection);
}
}
/**
* Provide the current tree view selection.
*
* @return the selection String instance
*/
public String getTreeViewSelection()
{
if (pagesItem.isSelected())
{
return VIEW_PAGES;
}
if (structureItem.isSelected())
{
return VIEW_STRUCTURE;
}
if (crtItem.isSelected())
{
return VIEW_CROSS_REF_TABLE;
}
return null;
}
/**
* Checks if the given viewMode value is a valid one.
*
* @param viewMode the view mode to be checked
* @return true if the given value is a valid view mode, otherwise false
*/
public static boolean isValidViewMode(String viewMode)
{
return validTreeModes.contains(viewMode);
}
private JMenu createTreeViewMenu()
{<FILL_FUNCTION_BODY>}
}
|
JMenu menu = new JMenu();
menu.setText("Tree view");
pagesItem = new JRadioButtonMenuItem();
structureItem = new JRadioButtonMenuItem();
crtItem = new JRadioButtonMenuItem();
pagesItem.setSelected(true);
ButtonGroup bg = new ButtonGroup();
bg.add(pagesItem);
bg.add(structureItem);
bg.add(crtItem);
pagesItem.setText(VIEW_PAGES);
structureItem.setText(VIEW_STRUCTURE);
crtItem.setText(VIEW_CROSS_REF_TABLE);
menu.add(pagesItem);
menu.add(structureItem);
menu.add(crtItem);
return menu;
| 686
| 196
| 882
|
<methods>public void addMenuListeners(java.awt.event.ActionListener) ,public javax.swing.JMenu getMenu() ,public void setEnableMenu(boolean) <variables>private javax.swing.JMenu menu
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/ViewMenu.java
|
ViewMenu
|
createViewMenu
|
class ViewMenu extends MenuBase
{
private static ViewMenu instance;
private static final String SHOW_TEXT_STRIPPER = "Show TextStripper TextPositions";
private static final String SHOW_TEXT_STRIPPER_BEADS = "Show TextStripper Beads";
private static final String SHOW_FONT_BBOX = "Show Approximate Text Bounds";
private static final String SHOW_GLYPH_BOUNDS = "Show Glyph Bounds";
private static final String ALLOW_SUBSAMPLING = "Allow subsampling";
private static final String EXTRACT_TEXT = "Extract Text";
private static final String REPAIR_ACROFORM = "Repair AcroForm";
private JCheckBoxMenuItem showTextStripper;
private JCheckBoxMenuItem showTextStripperBeads;
private JCheckBoxMenuItem showFontBBox;
private JCheckBoxMenuItem showGlyphBounds;
private JCheckBoxMenuItem allowSubsampling;
private JMenuItem extractTextMenuItem;
private JCheckBoxMenuItem repairAcroFormMenuItem;
private final PDFDebugger pdfDebugger;
/**
* Constructor.
*/
private ViewMenu(PDFDebugger pdfDebugger)
{
this.pdfDebugger = pdfDebugger;
setMenu(createViewMenu());
}
/**
* Provides the ViewMenu instance.
*
* @param pdfDebugger PDFDebugger instance.
*
* @return ViewMenu instance.
*/
public static ViewMenu getInstance(PDFDebugger pdfDebugger)
{
if (instance == null)
{
instance = new ViewMenu(pdfDebugger);
}
return instance;
}
/**
* Test if the one of the rendering options has been selected
*
* @param actionCommand the actioCommand of the menu event
* @return true if the actionCommand matches one of the rendering options
*/
public static boolean isRenderingOption(String actionCommand)
{
return SHOW_TEXT_STRIPPER.equals(actionCommand) ||
SHOW_TEXT_STRIPPER_BEADS.equals(actionCommand) ||
SHOW_FONT_BBOX.equals(actionCommand) ||
SHOW_GLYPH_BOUNDS.equals(actionCommand) ||
ALLOW_SUBSAMPLING.equals(actionCommand);
}
/**
* State if the TextStripper TextPositions shall be shown.
*
* @return the selection state
*/
public static boolean isShowTextStripper()
{
return instance.showTextStripper.isSelected();
}
/**
* State if the article beads shall be shown.
*
* @return the selection state
*/
public static boolean isShowTextStripperBeads()
{
return instance.showTextStripperBeads.isSelected();
}
/**
* State if the fonts bounding box shall be shown.
*
* @return the selection state
*/
public static boolean isShowFontBBox()
{
return instance.showFontBBox.isSelected();
}
/**
* State if the bounds of individual glyphs shall be shown.
*
* @return the selection state
*/
public static boolean isShowGlyphBounds()
{
return instance.showGlyphBounds.isSelected();
}
/**
* Tell whether the "Extract Text" menu entry was hit.
*
* @param actionEvent the action event
* @return true if the "Extract Text" menu entry was hit.
*/
public static boolean isExtractTextEvent(ActionEvent actionEvent)
{
return EXTRACT_TEXT.equals(actionEvent.getActionCommand());
}
/**
* State if subsampling for image rendering shall be used.
*
* @return the selection state
*/
public static boolean isAllowSubsampling()
{
return instance.allowSubsampling.isSelected();
}
/**
* Tell whether the "Repair AcroForm" menu entry was hit.
*
* @param actionEvent the action event
* @return true if the "Repair AcroForm" menu entry was hit.
*/
public static boolean isRepairAcroformEvent(ActionEvent actionEvent)
{
return REPAIR_ACROFORM.equals(actionEvent.getActionCommand());
}
/**
* State if acroForm shall be repaired.
*
* @return the repair state
*/
public static boolean isRepairAcroformSelected()
{
return instance.repairAcroFormMenuItem.isSelected();
}
private JMenu createViewMenu()
{<FILL_FUNCTION_BODY>}
}
|
JMenu viewMenu = new JMenu("View");
viewMenu.setMnemonic('V');
TreeViewMenu treeViewMenu = TreeViewMenu.getInstance();
treeViewMenu.setEnableMenu(false);
viewMenu.add(treeViewMenu.getMenu());
treeViewMenu.addMenuListeners(actionEvent ->
{
pdfDebugger.setTreeViewMode(treeViewMenu.getTreeViewSelection());
if (pdfDebugger.hasDocument())
{
pdfDebugger.initTree();
}
});
ZoomMenu zoomMenu = ZoomMenu.getInstance();
zoomMenu.setEnableMenu(false);
viewMenu.add(zoomMenu.getMenu());
RotationMenu rotationMenu = RotationMenu.getInstance();
rotationMenu.setEnableMenu(false);
viewMenu.add(rotationMenu.getMenu());
ImageTypeMenu imageTypeMenu = ImageTypeMenu.getInstance();
imageTypeMenu.setEnableMenu(false);
viewMenu.add(imageTypeMenu.getMenu());
RenderDestinationMenu renderDestinationMenu = RenderDestinationMenu.getInstance();
renderDestinationMenu.setEnableMenu(false);
viewMenu.add(renderDestinationMenu.getMenu());
viewMenu.addSeparator();
showTextStripper = new JCheckBoxMenuItem(SHOW_TEXT_STRIPPER);
showTextStripper.setEnabled(false);
viewMenu.add(showTextStripper);
showTextStripperBeads = new JCheckBoxMenuItem(SHOW_TEXT_STRIPPER_BEADS);
showTextStripperBeads.setEnabled(false);
viewMenu.add(showTextStripperBeads);
showFontBBox = new JCheckBoxMenuItem(SHOW_FONT_BBOX);
showFontBBox.setEnabled(false);
viewMenu.add(showFontBBox);
showGlyphBounds = new JCheckBoxMenuItem(SHOW_GLYPH_BOUNDS);
showGlyphBounds.setEnabled(false);
viewMenu.add(showGlyphBounds);
viewMenu.addSeparator();
allowSubsampling = new JCheckBoxMenuItem(ALLOW_SUBSAMPLING);
allowSubsampling.setEnabled(false);
viewMenu.add(allowSubsampling);
viewMenu.addSeparator();
extractTextMenuItem = new JMenuItem(EXTRACT_TEXT);
extractTextMenuItem.setEnabled(false);
viewMenu.add(extractTextMenuItem);
viewMenu.addSeparator();
repairAcroFormMenuItem = new JCheckBoxMenuItem(REPAIR_ACROFORM);
repairAcroFormMenuItem.setEnabled(false);
viewMenu.add(repairAcroFormMenuItem);
return viewMenu;
| 1,235
| 718
| 1,953
|
<methods>public void addMenuListeners(java.awt.event.ActionListener) ,public javax.swing.JMenu getMenu() ,public void setEnableMenu(boolean) <variables>private javax.swing.JMenu menu
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/WindowPrefs.java
|
WindowPrefs
|
setBounds
|
class WindowPrefs
{
private static final String KEY = "window_prefs_";
private final Preferences pref;
public WindowPrefs(Class<?> className)
{
this.pref = Preferences.userNodeForPackage(className);
}
public void setBounds(Rectangle rect)
{<FILL_FUNCTION_BODY>}
public Rectangle getBounds()
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Preferences node = pref.node(KEY);
int x = node.getInt("X", screenSize.width / 4);
int y = node.getInt("Y", screenSize.height / 4);
int w = node.getInt("W", screenSize.width / 2);
int h = node.getInt("H", screenSize.height / 2);
return new Rectangle(x, y, w, h);
}
public void setDividerLocation(int divider)
{
Preferences node = pref.node(KEY);
node.putInt("DIV", divider);
}
public int getDividerLocation()
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Preferences node = pref.node(KEY);
return node.getInt("DIV", screenSize.width / 8);
}
public void setExtendedState(int extendedState)
{
Preferences node = pref.node(KEY);
node.putInt("EXTSTATE", extendedState);
}
public int getExtendedState()
{
Preferences node = pref.node(KEY);
return node.getInt("EXTSTATE", Frame.NORMAL);
}
}
|
Preferences node = pref.node(KEY);
node.putInt("X", rect.x);
node.putInt("Y", rect.y);
node.putInt("W", rect.width);
node.putInt("H", rect.height);
| 430
| 66
| 496
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/XrefEntries.java
|
XrefEntries
|
getXrefEntry
|
class XrefEntries
{
public static final String PATH = "CRT";
private final List<Entry<COSObjectKey, Long>> entries;
private final COSDocument document;
public XrefEntries(PDDocument document)
{
Map<COSObjectKey, Long> xrefTable = document.getDocument().getXrefTable();
entries = xrefTable.entrySet().stream()
.sorted(Comparator.comparingLong(e -> e.getKey().getNumber()))
.collect(Collectors.toList());
this.document = document.getDocument();
}
public int getXrefEntryCount()
{
return entries.size();
}
public XrefEntry getXrefEntry(int index)
{<FILL_FUNCTION_BODY>}
public int indexOf(XrefEntry xrefEntry)
{
COSObjectKey key = xrefEntry.getKey();
Entry<COSObjectKey, Long> entry = entries.stream().filter(e -> key.equals(e.getKey()))
.findFirst().orElse(null);
return entry != null ? entries.indexOf(entry) : 0;
}
@Override
public String toString()
{
return PATH;
}
}
|
Entry<COSObjectKey, Long> entry = entries.get(index);
COSObject objectFromPool = document.getObjectFromPool(entry.getKey());
return new XrefEntry(index, entry.getKey(), entry.getValue(), objectFromPool);
| 332
| 66
| 398
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/XrefEntry.java
|
XrefEntry
|
toString
|
class XrefEntry
{
private final int index;
private final COSObjectKey key;
private final long offset;
private final COSObject cosObject;
public XrefEntry(int index, COSObjectKey key, long offset, COSObject cosObject)
{
this.index = index;
this.key = key;
this.offset = offset;
this.cosObject = cosObject;
}
public COSObjectKey getKey()
{
return key;
}
public int getIndex()
{
return index;
}
public COSObject getCOSObject()
{
return cosObject;
}
public COSBase getObject()
{
return cosObject != null ? cosObject.getObject() : null;
}
public String getPath()
{
return XrefEntries.PATH + "/" + toString();
}
@Override
public String toString()
{<FILL_FUNCTION_BODY>}
}
|
if (key == null)
{
return "(null)";
}
return offset >= 0 ? //
"Offset: " + offset + " [" + key + "]" : //
"Compressed object stream: " + (-offset) + " [" + key + "]";
| 267
| 73
| 340
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/ZoomMenu.java
|
ZoomMenuItem
|
getZoomScale
|
class ZoomMenuItem extends JRadioButtonMenuItem
{
private final int zoom;
ZoomMenuItem(String text, int zoom)
{
super(text);
this.zoom = zoom;
}
}
private float pageZoomScale = 1;
private float imageZoomScale = 1;
private static final int[] ZOOMS = { 25, 50, 100, 150, 200, 400, 1000, 2000 };
private static ZoomMenu instance;
private final JMenu menu;
/**
* Constructor.
*/
private ZoomMenu()
{
menu = new JMenu("Zoom");
ButtonGroup bg = new ButtonGroup();
for (int zoom : ZOOMS)
{
ZoomMenuItem zoomItem = new ZoomMenuItem(zoom + "%", zoom);
bg.add(zoomItem);
menu.add(zoomItem);
}
setMenu(menu);
}
/**
* Provides the ZoomMenu instance.
*
* @return ZoomMenu instance.
*/
public static ZoomMenu getInstance()
{
if (instance == null)
{
instance = new ZoomMenu();
}
return instance;
}
/**
* Set the zoom selection.
*
* @param zoomValue the zoom factor, e.g. 1, 0.25, 4.
*
* @throws IllegalArgumentException if the parameter doesn't belong to a zoom menu item.
*/
public void changeZoomSelection(float zoomValue)
{
int selection = (int) (zoomValue * 100);
for (Component comp : menu.getMenuComponents())
{
ZoomMenuItem menuItem = (ZoomMenuItem) comp;
if (menuItem.zoom == selection)
{
menuItem.setSelected(true);
return;
}
}
throw new IllegalArgumentException("no zoom menu item found for: " + selection + "%");
}
/**
* Tell whether the command belongs to the zoom menu.
*
* @param actionCommand a menu command string.
* @return true if the command is a zoom menu command, e.g. "100%", false if not.
*/
public static boolean isZoomMenu(String actionCommand)
{
if (!actionCommand.matches("^\\d+%$"))
{
return false;
}
int zoom = Integer.parseInt(actionCommand.substring(0, actionCommand.length() - 1));
return Arrays.binarySearch(ZOOMS, zoom) >= 0;
}
/**
* Tell the current zoom scale.
*
* @return the current zoom scale.
* @throws IllegalStateException if no zoom menu item is selected.
*/
public static float getZoomScale()
{<FILL_FUNCTION_BODY>
|
for (Component comp : instance.menu.getMenuComponents())
{
ZoomMenuItem menuItem = (ZoomMenuItem) comp;
if (menuItem.isSelected())
{
return menuItem.zoom / 100f;
}
}
throw new IllegalStateException("no zoom menu item is selected");
| 759
| 87
| 846
|
<methods>public void addMenuListeners(java.awt.event.ActionListener) ,public javax.swing.JMenu getMenu() ,public void setEnableMenu(boolean) <variables>private javax.swing.JMenu menu
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/textsearcher/SearchEngine.java
|
SearchEngine
|
search
|
class SearchEngine
{
private static final Logger LOG = LogManager.getLogger(SearchEngine.class);
private final Document document;
private final Highlighter highlighter;
private final Highlighter.HighlightPainter painter;
/**
* Constructor.
* @param textComponent JTextComponent that is to be searched.
* @param painter Highlighter.HighlightPainter instance to paint the highlights.
*/
SearchEngine(JTextComponent textComponent, Highlighter.HighlightPainter painter)
{
this.document = textComponent.getDocument();
this.highlighter = textComponent.getHighlighter();
this.painter = painter;
}
/**
* Search the word.
* @param searchKey String. Search word.
* @param isCaseSensitive boolean. If search is case sensitive.
* @return ArrayList<Highlighter.Highlight>.
*/
public List<Highlighter.Highlight> search(String searchKey, boolean isCaseSensitive)
{<FILL_FUNCTION_BODY>}
}
|
List<Highlighter.Highlight> highlights = new ArrayList<>();
if (searchKey != null)
{
highlighter.removeAllHighlights();
if (searchKey.isEmpty())
{
return highlights;
}
String textContent;
try
{
textContent = document.getText(0, document.getLength());
}
catch (BadLocationException e)
{
LOG.error(e.getMessage(), e);
return highlights;
}
if (!isCaseSensitive)
{
textContent = textContent.toLowerCase();
searchKey = searchKey.toLowerCase();
}
int searchKeyLength = searchKey.length();
int startAt = 0;
int resultantOffset;
int indexOfHighLight = 0;
while ((resultantOffset = textContent.indexOf(searchKey, startAt)) != -1)
{
try
{
highlighter.addHighlight(resultantOffset, resultantOffset + searchKeyLength, painter);
highlights.add(highlighter.getHighlights()[indexOfHighLight++]);
startAt = resultantOffset + searchKeyLength;
}
catch (BadLocationException e)
{
LOG.error(e.getMessage(), e);
}
}
}
return highlights;
| 279
| 341
| 620
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/textsearcher/SearchPanel.java
|
SearchPanel
|
initUI
|
class SearchPanel
{
private final Action nextAction;
private final Action previousAction;
private JCheckBox caseSensitive;
private JTextField searchField;
private JLabel counterLabel;
private JPanel panel;
private final Action closeAction = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
panel.setVisible(false);
closeAction.setEnabled(false);
panel.getParent().transferFocus();
}
};
private final Action findAction = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
if (!panel.isVisible())
{
panel.setVisible(true);
panel.getParent().validate();
return;
}
reFocus();
}
};
/**
* Constructor.
* @param documentListener DocumentListener instance.
* @param changeListener ChangeListener instance.
* @param compListener ComponentListener instance.
* @param nextAction Action instance for next find.
* @param previousAction Action instance for previous find.
*/
SearchPanel(DocumentListener documentListener, ChangeListener changeListener,
ComponentListener compListener, Action nextAction, Action previousAction)
{
this.nextAction = nextAction;
this.previousAction = previousAction;
initUI(documentListener, changeListener, compListener);
}
private void initUI(DocumentListener documentListener, ChangeListener changeListener,
ComponentListener compListener)
{<FILL_FUNCTION_BODY>}
boolean isCaseSensitive()
{
return caseSensitive.isSelected();
}
String getSearchWord()
{
return searchField.getText();
}
void reset()
{
counterLabel.setVisible(false);
}
void updateCounterLabel(int now, int total)
{
if (!counterLabel.isVisible())
{
counterLabel.setVisible(true);
}
if (total == 0)
{
counterLabel.setText(" No match found ");
nextAction.setEnabled(false);
return;
}
counterLabel.setText(" " + now + " of " + total + " ");
}
JPanel getPanel()
{
return panel;
}
public void reFocus()
{
searchField.requestFocus();
String searchKey = searchField.getText();
searchField.setText(searchKey);
searchField.setSelectionStart(0);
searchField.setSelectionEnd(searchField.getText().length());
closeAction.setEnabled(true);
}
public void addMenuListeners(PDFDebugger frame)
{
frame.getFindMenu().setEnabled(true);
frame.getFindMenuItem().addActionListener(findAction);
frame.getFindNextMenuItem().addActionListener(nextAction);
frame.getFindPreviousMenuItem().addActionListener(previousAction);
}
public void removeMenuListeners(PDFDebugger frame)
{
frame.getFindMenu().setEnabled(false);
frame.getFindMenuItem().removeActionListener(findAction);
frame.getFindNextMenuItem().removeActionListener(nextAction);
frame.getFindPreviousMenuItem().removeActionListener(previousAction);
}
}
|
searchField = new JTextField();
searchField.getDocument().addDocumentListener(documentListener);
counterLabel = new JLabel();
counterLabel.setVisible(false);
JButton nextButton = new JButton();
nextButton.setAction(nextAction);
nextButton.setText("Next");
JButton previousButton = new JButton();
previousButton.setAction(previousAction);
previousButton.setText("Previous");
caseSensitive = new JCheckBox("Match case");
caseSensitive.setSelected(false);
caseSensitive.addChangeListener(changeListener);
caseSensitive.setToolTipText("Check for case sensitive search");
JButton crossButton = new JButton();
crossButton.setAction(closeAction);
crossButton.setText("Done");
closeAction.setEnabled(false);
panel = new JPanel();
panel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.LIGHT_GRAY));
panel.setBackground(new Color(230, 230, 230));
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(Box.createHorizontalGlue());
panel.add(searchField);
panel.add(counterLabel);
panel.add(previousButton);
panel.add(nextButton);
panel.add(caseSensitive);
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(crossButton);
panel.addComponentListener(compListener);
searchField.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), closeAction);
| 839
| 460
| 1,299
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/debugger/src/main/java/org/apache/pdfbox/debugger/ui/textsearcher/Searcher.java
|
Searcher
|
updateNavigationButtons
|
class Searcher implements DocumentListener, ChangeListener, ComponentListener
{
private static final Logger LOG = LogManager.getLogger(Searcher.class);
private static final Highlighter.HighlightPainter PAINTER =
new DefaultHighlighter.DefaultHighlightPainter(Color.yellow);
private static final Highlighter.HighlightPainter SELECTION_PAINTER =
new DefaultHighlighter.DefaultHighlightPainter(new Color(109, 216, 26));
private final SearchEngine searchEngine;
private final SearchPanel searchPanel;
private final JTextComponent textComponent;
private int totalMatch = 0;
private int currentMatch = -1;
private List<Highlighter.Highlight> highlights;
private final Action previousAction = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
if (totalMatch != 0 && currentMatch != 0)
{
currentMatch = currentMatch - 1;
int offset = highlights.get(currentMatch).getStartOffset();
scrollToWord(offset);
updateHighLighter(currentMatch, currentMatch + 1);
updateNavigationButtons();
}
}
};
private final Action nextAction = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent actionEvent)
{
if (totalMatch != 0 && currentMatch != totalMatch - 1)
{
currentMatch = currentMatch + 1;
int offset = highlights.get(currentMatch).getStartOffset();
scrollToWord(offset);
updateHighLighter(currentMatch, currentMatch - 1);
updateNavigationButtons();
}
}
};
/**
* Constructor.
* @param textComponent JTextComponent instance.
*/
public Searcher(JTextComponent textComponent)
{
this.textComponent = textComponent;
searchPanel = new SearchPanel(this, this, this, nextAction, previousAction);
searchEngine = new SearchEngine(textComponent, PAINTER);
nextAction.setEnabled(false);
previousAction.setEnabled(false);
}
public JPanel getSearchPanel()
{
return searchPanel.getPanel();
}
@Override
public void insertUpdate(DocumentEvent documentEvent)
{
search(documentEvent);
}
@Override
public void removeUpdate(DocumentEvent documentEvent)
{
search(documentEvent);
}
@Override
public void changedUpdate(DocumentEvent documentEvent)
{
search(documentEvent);
}
private void search(DocumentEvent documentEvent)
{
try
{
String word = documentEvent.getDocument().getText(0, documentEvent.getDocument().getLength());
if (word.isEmpty())
{
nextAction.setEnabled(false);
previousAction.setEnabled(false);
searchPanel.reset();
textComponent.getHighlighter().removeAllHighlights();
return;
}
search(word);
}
catch (BadLocationException e)
{
LOG.error(e.getMessage(), e);
}
}
private void search(String word)
{
highlights = searchEngine.search(word, searchPanel.isCaseSensitive());
if (!highlights.isEmpty())
{
totalMatch = highlights.size();
currentMatch = 0;
scrollToWord(highlights.get(0).getStartOffset());
updateHighLighter(currentMatch, currentMatch - 1);
updateNavigationButtons();
}
else
{
searchPanel.updateCounterLabel(0, 0);
}
}
private void updateNavigationButtons()
{<FILL_FUNCTION_BODY>}
private void scrollToWord(int offset)
{
try
{
textComponent.scrollRectToVisible((Rectangle) textComponent.modelToView2D(offset));
}
catch (BadLocationException e)
{
LOG.error(e.getMessage(), e);
}
}
private void updateHighLighter(final int presentIndex, final int previousIndex)
{
if (previousIndex != -1)
{
changeHighlighter(previousIndex, PAINTER);
}
changeHighlighter(presentIndex, SELECTION_PAINTER);
}
private void changeHighlighter(int index, Highlighter.HighlightPainter newPainter)
{
Highlighter highlighter = textComponent.getHighlighter();
Highlighter.Highlight highLight = highlights.get(index);
highlighter.removeHighlight(highLight);
try
{
highlighter.addHighlight(highLight.getStartOffset(), highLight.getEndOffset(), newPainter);
highlights.set(index, highlighter.getHighlights()[highlighter.getHighlights().length - 1]);
}
catch (BadLocationException e)
{
LOG.error(e.getMessage(), e);
}
}
@Override
public void stateChanged(ChangeEvent changeEvent)
{
if (changeEvent.getSource() instanceof JCheckBox)
{
search(searchPanel.getSearchWord());
}
}
@Override
public void componentResized(ComponentEvent componentEvent)
{
// do nothing
}
@Override
public void componentMoved(ComponentEvent componentEvent)
{
// do nothing
}
@Override
public void componentShown(ComponentEvent componentEvent)
{
searchPanel.reFocus();
}
@Override
public void componentHidden(ComponentEvent componentEvent)
{
textComponent.getHighlighter().removeAllHighlights();
}
public void addMenuListeners(PDFDebugger frame)
{
searchPanel.addMenuListeners(frame);
}
public void removeMenuListeners(PDFDebugger frame)
{
searchPanel.removeMenuListeners(frame);
}
}
|
if (currentMatch == 0)
{
previousAction.setEnabled(false);
}
else if (currentMatch >= 1 && currentMatch <= (totalMatch - 1))
{
previousAction.setEnabled(true);
}
if (currentMatch == (totalMatch - 1))
{
nextAction.setEnabled(false);
}
else if (currentMatch < (totalMatch - 1))
{
nextAction.setEnabled(true);
}
searchPanel.updateCounterLabel(currentMatch + 1, totalMatch);
| 1,536
| 143
| 1,679
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/ant/PDFToTextTask.java
|
PDFToTextTask
|
execute
|
class PDFToTextTask extends Task
{
private final List<FileSet> fileSets = new ArrayList<>();
/**
* Adds a set of files (nested fileset attribute).
*
* @param set Another fileset to add.
*/
public void addFileset( FileSet set )
{
fileSets.add( set );
}
/**
* This will perform the execution.
*/
@Override
public void execute()
{<FILL_FUNCTION_BODY>}
}
|
log( "PDFToTextTask executing" );
fileSets.stream().
map(fileSet -> fileSet.getDirectoryScanner(getProject())).
forEachOrdered(dirScanner ->
{
dirScanner.scan();
for (String file : dirScanner.getIncludedFiles())
{
File f = new File(dirScanner.getBasedir(), file);
log("processing: " + f.getAbsolutePath());
String pdfFile = f.getAbsolutePath();
if (pdfFile.toUpperCase().endsWith(".PDF"))
{
String textFile = pdfFile.substring(0, pdfFile.length() - 3) + "txt";
ExtractText.main(new String[] {pdfFile, textFile});
}
}
});
| 136
| 206
| 342
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/AddBorderToField.java
|
AddBorderToField
|
main
|
class AddBorderToField
{
static final String RESULT_FILENAME = "target/AddBorderToField.pdf";
private AddBorderToField()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
// Load the PDF document created by SimpleForm.java
try (PDDocument document = Loader.loadPDF(new File(CreateSimpleForm.DEFAULT_FILENAME)))
{
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
// Get the field and the widget associated to it.
// Note: there might be multiple widgets
PDField field = acroForm.getField("SampleField");
PDAnnotationWidget widget = field.getWidgets().get(0);
// Create the definition for a red border
PDAppearanceCharacteristicsDictionary fieldAppearance =
new PDAppearanceCharacteristicsDictionary(new COSDictionary());
PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE);
fieldAppearance.setBorderColour(red);
// Set the information to be used by the widget which is responsible
// for the visual style of the form field.
widget.setAppearanceCharacteristics(fieldAppearance);
document.save(RESULT_FILENAME);
}
| 76
| 283
| 359
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/CreateMultiWidgetsForm.java
|
CreateMultiWidgetsForm
|
main
|
class CreateMultiWidgetsForm
{
private CreateMultiWidgetsForm()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
// Create a new document with 2 empty pages.
try (PDDocument document = new PDDocument())
{
PDPage page1 = new PDPage(PDRectangle.A4);
document.addPage(page1);
PDPage page2 = new PDPage(PDRectangle.A4);
document.addPage(page2);
// Adobe Acrobat uses Helvetica as a default font and
// stores that under the name '/Helv' in the resources dictionary
PDFont font = new PDType1Font(FontName.HELVETICA);
PDResources resources = new PDResources();
resources.put(COSName.HELV, font);
// Add a new AcroForm and add that to the document
PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);
// Add and set the resources and default appearance at the form level
acroForm.setDefaultResources(resources);
// Acrobat sets the font size on the form level to be
// auto sized as default. This is done by setting the font size to '0'
String defaultAppearanceString = "/Helv 0 Tf 0 g";
acroForm.setDefaultAppearance(defaultAppearanceString);
// Add a form field to the form.
PDTextField textBox = new PDTextField(acroForm);
textBox.setPartialName("SampleField");
// Acrobat sets the font size to 12 as default
// This is done by setting the font size to '12' on the
// field level.
// The text color is set to blue in this example.
// To use black, replace "0 0 1 rg" with "0 0 0 rg" or "0 g".
defaultAppearanceString = "/Helv 12 Tf 0 0 1 rg";
textBox.setDefaultAppearance(defaultAppearanceString);
// add the field to the AcroForm
acroForm.getFields().add(textBox);
// Specify 1st annotation associated with the field
PDAnnotationWidget widget1 = new PDAnnotationWidget();
PDRectangle rect = new PDRectangle(50, 750, 250, 50);
widget1.setRectangle(rect);
widget1.setPage(page1);
widget1.setParent(textBox);
// Specify 2nd annotation associated with the field
PDAnnotationWidget widget2 = new PDAnnotationWidget();
PDRectangle rect2 = new PDRectangle(200, 650, 100, 50);
widget2.setRectangle(rect2);
widget2.setPage(page2);
widget2.setParent(textBox);
// set green border and yellow background for 1st widget
// if you prefer defaults, delete this code block
PDAppearanceCharacteristicsDictionary fieldAppearance1
= new PDAppearanceCharacteristicsDictionary(new COSDictionary());
fieldAppearance1.setBorderColour(new PDColor(new float[]{0,1,0}, PDDeviceRGB.INSTANCE));
fieldAppearance1.setBackground(new PDColor(new float[]{1,1,0}, PDDeviceRGB.INSTANCE));
widget1.setAppearanceCharacteristics(fieldAppearance1);
// set red border and green background for 2nd widget
// if you prefer defaults, delete this code block
PDAppearanceCharacteristicsDictionary fieldAppearance2
= new PDAppearanceCharacteristicsDictionary(new COSDictionary());
fieldAppearance2.setBorderColour(new PDColor(new float[]{1,0,0}, PDDeviceRGB.INSTANCE));
fieldAppearance2.setBackground(new PDColor(new float[]{0,1,0}, PDDeviceRGB.INSTANCE));
widget2.setAppearanceCharacteristics(fieldAppearance2);
List <PDAnnotationWidget> widgets = new ArrayList<>();
widgets.add(widget1);
widgets.add(widget2);
textBox.setWidgets(widgets);
// make sure the annotations are visible on screen and paper
widget1.setPrinted(true);
widget2.setPrinted(true);
// Add the annotations to the pages
page1.getAnnotations().add(widget1);
page2.getAnnotations().add(widget2);
// set the field value
textBox.setValue("Sample field");
document.save("target/MultiWidgetsForm.pdf");
}
| 55
| 1,198
| 1,253
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/CreatePushButton.java
|
CreatePushButton
|
main
|
class CreatePushButton
{
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
PDAcroForm acroForm = new PDAcroForm(doc);
doc.getDocumentCatalog().setAcroForm(acroForm);
PDPushButton pushButton = new PDPushButton(acroForm);
pushButton.setPartialName("push");
acroForm.getFields().add(pushButton);
PDAnnotationWidget widget = pushButton.getWidgets().get(0);
page.getAnnotations().add(widget);
widget.setRectangle(new PDRectangle(50, 500, 100, 100)); // position on the page
widget.setPrinted(true);
widget.setPage(page);
PDActionJavaScript javascriptAction = new PDActionJavaScript("app.alert(\"button pressed\")");
PDAnnotationAdditionalActions actions = new PDAnnotationAdditionalActions();
actions.setU(javascriptAction);
widget.setActions(actions);
// Create a PDFormXObject
PDFormXObject form = new PDFormXObject(doc);
form.setResources(new PDResources());
form.setBBox(new PDRectangle(100, 100));
form.setFormType(1);
PDAppearanceDictionary appearanceDictionary = new PDAppearanceDictionary(new COSDictionary());
widget.setAppearance(appearanceDictionary);
PDAppearanceStream appearanceStream = new PDAppearanceStream(form.getCOSObject());
appearanceDictionary.setNormalAppearance(appearanceStream);
// Create the content stream
BufferedImage bim = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); // black
PDImageXObject image = LosslessFactory.createFromImage(doc, bim);
try (PDAppearanceContentStream cs = new PDAppearanceContentStream(appearanceStream))
{
cs.drawImage(image, 0, 0);
}
doc.save("target/PushButtonSample.pdf");
}
| 38
| 555
| 593
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/CreateRadioButtons.java
|
CreateRadioButtons
|
createAppearanceStream
|
class CreateRadioButtons
{
private CreateRadioButtons()
{
}
public static void main(String[] args) throws IOException
{
try (PDDocument document = new PDDocument())
{
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
PDAcroForm acroForm = new PDAcroForm(document);
// if you want to see what Adobe does, activate this, open with Adobe
// save the file, and then open it with PDFDebugger
//acroForm.setNeedAppearances(true)
document.getDocumentCatalog().setAcroForm(acroForm);
List<String> options = Arrays.asList("a", "b", "c");
PDRadioButton radioButton = new PDRadioButton(acroForm);
radioButton.setPartialName("MyRadioButton");
radioButton.setExportValues(options);
PDAppearanceCharacteristicsDictionary appearanceCharacteristics = new PDAppearanceCharacteristicsDictionary(new COSDictionary());
appearanceCharacteristics.setBorderColour(new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE));
appearanceCharacteristics.setBackground(new PDColor(new float[]{0, 1, 0.3f}, PDDeviceRGB.INSTANCE));
// no caption => round
// with caption => see checkbox example
List<PDAnnotationWidget> widgets = new ArrayList<>();
for (int i = 0; i < options.size(); i++)
{
PDAnnotationWidget widget = new PDAnnotationWidget();
widget.setRectangle(new PDRectangle(30, PDRectangle.A4.getHeight() - 40 - i * 35, 30, 30));
widget.setPrinted(true);
widget.setAppearanceCharacteristics(appearanceCharacteristics);
PDBorderStyleDictionary borderStyleDictionary = new PDBorderStyleDictionary();
borderStyleDictionary.setWidth(2);
borderStyleDictionary.setStyle(PDBorderStyleDictionary.STYLE_SOLID);
widget.setBorderStyle(borderStyleDictionary);
widget.setPage(page);
COSDictionary apNDict = new COSDictionary();
apNDict.setItem(COSName.Off, createAppearanceStream(document, widget, false));
apNDict.setItem(options.get(i), createAppearanceStream(document, widget, true));
PDAppearanceDictionary appearance = new PDAppearanceDictionary();
PDAppearanceEntry appearanceNEntry = new PDAppearanceEntry(apNDict);
appearance.setNormalAppearance(appearanceNEntry);
widget.setAppearance(appearance);
widget.setAppearanceState("Off"); // don't forget this, or button will be invisible
widgets.add(widget);
page.getAnnotations().add(widget);
}
radioButton.setWidgets(widgets);
acroForm.getFields().add(radioButton);
// Set the texts
PDType1Font helvetica = new PDType1Font(FontName.HELVETICA);
try (PDPageContentStream contents = new PDPageContentStream(document, page))
{
for (int i = 0; i < options.size(); i++)
{
contents.beginText();
contents.setFont(helvetica, 15);
contents.newLineAtOffset(70, PDRectangle.A4.getHeight() - 30 - i * 35);
contents.showText(options.get(i));
contents.endText();
}
}
radioButton.setValue("c");
document.save("target/RadioButtonsSample.pdf");
}
}
private static PDAppearanceStream createAppearanceStream(
final PDDocument document, PDAnnotationWidget widget, boolean on) throws IOException
{<FILL_FUNCTION_BODY>}
static float getLineWidth(PDAnnotationWidget widget)
{
PDBorderStyleDictionary bs = widget.getBorderStyle();
if (bs != null)
{
return bs.getWidth();
}
return 1;
}
static void drawCircle(PDAppearanceContentStream cs, float x, float y, float r) throws IOException
{
// http://stackoverflow.com/a/2007782/535646
float magic = r * 0.551784f;
cs.moveTo(x, y + r);
cs.curveTo(x + magic, y + r, x + r, y + magic, x + r, y);
cs.curveTo(x + r, y - magic, x + magic, y - r, x, y - r);
cs.curveTo(x - magic, y - r, x - r, y - magic, x - r, y);
cs.curveTo(x - r, y + magic, x - magic, y + r, x, y + r);
cs.closePath();
}
}
|
PDRectangle rect = widget.getRectangle();
PDAppearanceStream onAP = new PDAppearanceStream(document);
onAP.setBBox(new PDRectangle(rect.getWidth(), rect.getHeight()));
try (PDAppearanceContentStream onAPCS = new PDAppearanceContentStream(onAP))
{
PDAppearanceCharacteristicsDictionary appearanceCharacteristics = widget.getAppearanceCharacteristics();
PDColor backgroundColor = appearanceCharacteristics.getBackground();
PDColor borderColor = appearanceCharacteristics.getBorderColour();
float lineWidth = getLineWidth(widget);
onAPCS.setBorderLine(lineWidth, widget.getBorderStyle(), widget.getBorder());
onAPCS.setNonStrokingColor(backgroundColor);
float radius = Math.min(rect.getWidth() / 2, rect.getHeight() / 2);
drawCircle(onAPCS, rect.getWidth() / 2, rect.getHeight() / 2, radius);
onAPCS.fill();
onAPCS.setStrokingColor(borderColor);
drawCircle(onAPCS, rect.getWidth() / 2, rect.getHeight() / 2, radius - lineWidth / 2);
onAPCS.stroke();
if (on)
{
onAPCS.setNonStrokingColor(0f);
drawCircle(onAPCS, rect.getWidth() / 2, rect.getHeight() / 2, (radius - lineWidth) / 2);
onAPCS.fill();
}
}
return onAP;
| 1,329
| 407
| 1,736
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/CreateSimpleForm.java
|
CreateSimpleForm
|
main
|
class CreateSimpleForm
{
static final String DEFAULT_FILENAME = "target/SimpleForm.pdf";
private CreateSimpleForm()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
// Create a new document with an empty page.
try (PDDocument document = new PDDocument())
{
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
// Adobe Acrobat uses Helvetica as a default font and
// stores that under the name '/Helv' in the resources dictionary
PDFont font = new PDType1Font(FontName.HELVETICA);
PDResources resources = new PDResources();
resources.put(COSName.HELV, font);
// Add a new AcroForm and add that to the document
PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);
// Add and set the resources and default appearance at the form level
acroForm.setDefaultResources(resources);
// Acrobat sets the font size on the form level to be
// auto sized as default. This is done by setting the font size to '0'
String defaultAppearanceString = "/Helv 0 Tf 0 g";
acroForm.setDefaultAppearance(defaultAppearanceString);
// Add a form field to the form.
PDTextField textBox = new PDTextField(acroForm);
textBox.setPartialName("SampleField");
// Acrobat sets the font size to 12 as default
// This is done by setting the font size to '12' on the
// field level.
// The text color is set to blue in this example.
// To use black, replace "0 0 1 rg" with "0 0 0 rg" or "0 g".
defaultAppearanceString = "/Helv 12 Tf 0 0 1 rg";
textBox.setDefaultAppearance(defaultAppearanceString);
// add the field to the acroform
acroForm.getFields().add(textBox);
// Specify the widget annotation associated with the field
PDAnnotationWidget widget = textBox.getWidgets().get(0);
PDRectangle rect = new PDRectangle(50, 750, 200, 50);
widget.setRectangle(rect);
widget.setPage(page);
// set green border and yellow background
// if you prefer defaults, delete this code block
PDAppearanceCharacteristicsDictionary fieldAppearance
= new PDAppearanceCharacteristicsDictionary(new COSDictionary());
fieldAppearance.setBorderColour(new PDColor(new float[]{0,1,0}, PDDeviceRGB.INSTANCE));
fieldAppearance.setBackground(new PDColor(new float[]{1,1,0}, PDDeviceRGB.INSTANCE));
widget.setAppearanceCharacteristics(fieldAppearance);
// make sure the widget annotation is visible on screen and paper
widget.setPrinted(true);
// Add the widget annotation to the page
page.getAnnotations().add(widget);
// set the alignment ("quadding")
textBox.setQ(PDVariableText.QUADDING_CENTERED);
// set the field value
textBox.setValue("Sample field content");
// put some text near the field
try (PDPageContentStream cs = new PDPageContentStream(document, page))
{
cs.beginText();
cs.setFont(new PDType1Font(FontName.HELVETICA), 15);
cs.newLineAtOffset(50, 810);
cs.showText("Field:");
cs.endText();
}
if (args == null || args.length == 0)
{
document.save(DEFAULT_FILENAME);
}
else
{
document.save(args[0]); // used for concurrent build tests
}
}
| 71
| 1,000
| 1,071
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/CreateSimpleFormWithEmbeddedFont.java
|
CreateSimpleFormWithEmbeddedFont
|
main
|
class CreateSimpleFormWithEmbeddedFont
{
private CreateSimpleFormWithEmbeddedFont()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
// Create a new document with an empty page.
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage(PDRectangle.A4);
doc.addPage(page);
PDAcroForm acroForm = new PDAcroForm(doc);
doc.getDocumentCatalog().setAcroForm(acroForm);
// Note that the font is fully embedded. If you use a different font, make sure that
// its license allows full embedding.
PDFont formFont = PDType0Font.load(doc, CreateSimpleFormWithEmbeddedFont.class.getResourceAsStream(
"/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"), false);
// Add and set the resources and default appearance at the form level
final PDResources resources = new PDResources();
acroForm.setDefaultResources(resources);
final String fontName = resources.add(formFont).getName();
// Acrobat sets the font size on the form level to be
// auto sized as default. This is done by setting the font size to '0'
acroForm.setDefaultResources(resources);
String defaultAppearanceString = "/" + fontName + " 0 Tf 0 g";
PDTextField textBox = new PDTextField(acroForm);
textBox.setPartialName("SampleField");
textBox.setDefaultAppearance(defaultAppearanceString);
acroForm.getFields().add(textBox);
// Specify the widget annotation associated with the field
PDAnnotationWidget widget = textBox.getWidgets().get(0);
PDRectangle rect = new PDRectangle(50, 700, 200, 50);
widget.setRectangle(rect);
widget.setPage(page);
page.getAnnotations().add(widget);
// set green border and yellow background
// if you prefer defaults, delete this code block
PDAppearanceCharacteristicsDictionary fieldAppearance
= new PDAppearanceCharacteristicsDictionary(new COSDictionary());
fieldAppearance.setBorderColour(new PDColor(new float[]{0,1,0}, PDDeviceRGB.INSTANCE));
fieldAppearance.setBackground(new PDColor(new float[]{1,1,0}, PDDeviceRGB.INSTANCE));
widget.setAppearanceCharacteristics(fieldAppearance);
// set the field value. Note that the last character is a turkish capital I with a dot,
// which is not part of WinAnsiEncoding
textBox.setValue("Sample field İ");
// put some text near the field
try (PDPageContentStream cs = new PDPageContentStream(doc, page))
{
cs.beginText();
cs.setFont(new PDType1Font(FontName.HELVETICA), 15);
cs.newLineAtOffset(50, 760);
cs.showText("Field:");
cs.endText();
}
doc.save("target/SimpleFormWithEmbeddedFont.pdf");
}
| 63
| 808
| 871
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/DetermineTextFitsField.java
|
DetermineTextFitsField
|
main
|
class DetermineTextFitsField
{
private DetermineTextFitsField()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
try (PDDocument document = Loader.loadPDF(new File("target/SimpleForm.pdf")))
{
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
// Get the field and the widget associated to it.
// Note: there might be multiple widgets
PDField field = acroForm.getField("SampleField");
PDAnnotationWidget widget = field.getWidgets().get(0);
// Get the width of the fields box
float widthOfField = widget.getRectangle().getWidth();
// Get the font and the font size setting
// This is currently a little awkward and needs improvement to have a better API
// for that. In many cases the string will be built like that:
// /Helv 12 Tf 0 g
// We could use PDFStreamParser to do the parsing. For the sample we split the
// string.
String defaultAppearance = ((PDTextField) field).getDefaultAppearance();
String[] parts = defaultAppearance.split(" ");
// Get the font name
COSName fontName = COSName.getPDFName(parts[0].substring(1));
float fontSize = Float.parseFloat(parts[1]);
// Get the font resource.
// First look up the font from the widgets appearance stream.
// This will be the case if there is already a value.
// If the value hasn't been set yet the font resource needs to be looked up from
// the AcroForm default resources
PDFont font = null;
PDResources resources = widget.getNormalAppearanceStream().getResources();
if (resources != null)
{
font = resources.getFont(fontName);
}
if (font == null)
{
font = acroForm.getDefaultResources().getFont(fontName);
}
String willFit = "short string";
String willNotFit = "this is a very long string which will not fit the width of the widget";
// calculate the string width at a certain font size
float willFitWidth = font.getStringWidth(willFit) * fontSize / 1000;
float willNotFitWidth = font.getStringWidth(willNotFit) * fontSize / 1000;
assert willFitWidth < widthOfField;
assert willNotFitWidth > widthOfField;
}
| 58
| 613
| 671
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/FieldTriggers.java
|
FieldTriggers
|
main
|
class FieldTriggers
{
private FieldTriggers()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
// Load the PDF document created by SimpleForm.java
try (PDDocument document = Loader.loadPDF(new File("target/SimpleForm.pdf")))
{
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
// Get the field and the widget associated to it.
// Note: there might be multiple widgets
PDField field = acroForm.getField("SampleField");
PDAnnotationWidget widget = field.getWidgets().get(0);
// Some of the actions are available to the widget, some are available to the form field.
// See Table 8.44 and Table 8.46 in the PDF 1.7 specification
// Actions for the widget
PDAnnotationAdditionalActions annotationActions = new PDAnnotationAdditionalActions();
// Create an action when entering the annotations active area
PDActionJavaScript jsEnterAction = new PDActionJavaScript();
jsEnterAction.setAction("app.alert(\"On 'enter' action\")");
annotationActions.setE(jsEnterAction);
// Create an action when exiting the annotations active area
PDActionJavaScript jsExitAction = new PDActionJavaScript();
jsExitAction.setAction("app.alert(\"On 'exit' action\")");
annotationActions.setX(jsExitAction);
// Create an action when the mouse button is pressed inside the annotations active area
PDActionJavaScript jsMouseDownAction = new PDActionJavaScript();
jsMouseDownAction.setAction("app.alert(\"On 'mouse down' action\")");
annotationActions.setD(jsMouseDownAction);
// Create an action when the mouse button is released inside the annotations active area
PDActionJavaScript jsMouseUpAction = new PDActionJavaScript();
jsMouseUpAction.setAction("app.alert(\"On 'mouse up' action\")");
annotationActions.setU(jsMouseUpAction);
// Create an action when the annotation gets the input focus
PDActionJavaScript jsFocusAction = new PDActionJavaScript();
jsFocusAction.setAction("app.alert(\"On 'focus' action\")");
annotationActions.setFo(jsFocusAction);
// Create an action when the annotation loses the input focus
PDActionJavaScript jsBlurredAction = new PDActionJavaScript();
jsBlurredAction.setAction("app.alert(\"On 'blurred' action\")");
annotationActions.setBl(jsBlurredAction);
widget.setActions(annotationActions);
// Actions for the field
PDFormFieldAdditionalActions fieldActions = new PDFormFieldAdditionalActions();
// Create an action when the user types a keystroke in the field
PDActionJavaScript jsKeystrokeAction = new PDActionJavaScript();
jsKeystrokeAction.setAction("app.alert(\"On 'keystroke' action\")");
fieldActions.setK(jsKeystrokeAction);
// Create an action when the field is formatted to display the current value
PDActionJavaScript jsFormattedAction = new PDActionJavaScript();
jsFormattedAction.setAction("app.alert(\"On 'formatted' action\")");
fieldActions.setF(jsFormattedAction);
// Create an action when the field value changes
PDActionJavaScript jsChangedAction = new PDActionJavaScript();
jsChangedAction.setAction("app.alert(\"On 'change' action\")");
// fieldActions.setV(jsChangedAction);
// Create an action when the field value changes
PDActionJavaScript jsRecalculateAction = new PDActionJavaScript();
jsRecalculateAction.setAction("app.alert(\"On 'recalculate' action\")");
fieldActions.setC(jsRecalculateAction);
// Set the Additional Actions entry for the field
// Note: this is a workaround as if there is only one widget the widget
// and the form field may share the same dictionary. Now setting the
// fields Additional Actions entry directly will overwrite the settings done for
// the widget.
// https://issues.apache.org/jira/browse/PDFBOX-3036
field.getActions().getCOSObject().addAll(fieldActions.getCOSObject());
document.save("target/FieldTriggers.pdf");
}
| 54
| 1,111
| 1,165
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/FillFormField.java
|
FillFormField
|
main
|
class FillFormField
{
private FillFormField()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
String formTemplate = "src/main/resources/org/apache/pdfbox/examples/interactive/form/FillFormField.pdf";
try (PDDocument pdfDocument = Loader.loadPDF(new File(formTemplate)))
{
// get the document catalog
PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
// as there might not be an AcroForm entry a null check is necessary
if (acroForm != null)
{
// Retrieve an individual field and set its value.
PDTextField field = (PDTextField) acroForm.getField( "sampleField" );
field.setValue("Text Entry");
// If a field is nested within the form tree a fully qualified name
// might be provided to access the field.
field = (PDTextField) acroForm.getField( "fieldsContainer.nestedSampleField" );
field.setValue("Text Entry");
}
// Save and close the filled out form.
pdfDocument.save("target/FillFormField.pdf");
}
| 54
| 275
| 329
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/PrintFields.java
|
PrintFields
|
printFields
|
class PrintFields
{
/**
* This will print all the fields from the document.
*
* @param pdfDocument The PDF to get the fields from.
*
* @throws IOException If there is an error getting the fields.
*/
public void printFields(PDDocument pdfDocument) throws IOException
{<FILL_FUNCTION_BODY>}
private void processField(PDField field, String sLevel, String sParent) throws IOException
{
String partialName = field.getPartialName();
if (field instanceof PDNonTerminalField)
{
if (!sParent.equals(field.getPartialName()) && partialName != null)
{
sParent = sParent + "." + partialName;
}
System.out.println(sLevel + sParent);
for (PDField child : ((PDNonTerminalField)field).getChildren())
{
processField(child, "| " + sLevel, sParent);
}
}
else
{
String fieldValue = field.getValueAsString();
StringBuilder outputString = new StringBuilder(sLevel);
outputString.append(sParent);
if (partialName != null)
{
outputString.append(".").append(partialName);
}
outputString.append(" = ").append(fieldValue);
outputString.append(", type=").append(field.getClass().getName());
System.out.println(outputString);
}
}
/**
* This will read a PDF file and print out the form elements. <br>
* see usage() for commandline
*
* @param args command line arguments
*
* @throws IOException If there is an error importing the FDF document.
*/
public static void main(String[] args) throws IOException
{
PDDocument pdf = null;
try
{
if (args.length != 1)
{
usage();
}
else
{
pdf = Loader.loadPDF(new File(args[0]));
PrintFields exporter = new PrintFields();
exporter.printFields(pdf);
}
}
finally
{
if (pdf != null)
{
pdf.close();
}
}
}
/**
* This will print out a message telling how to use this example.
*/
private static void usage()
{
System.err.println("usage: org.apache.pdfbox.examples.interactive.form.PrintFields <pdf-file>");
}
}
|
PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
List<PDField> fields = acroForm.getFields();
System.out.println(fields.size() + " top-level fields were found on the form");
for (PDField field : fields)
{
processField(field, "|--", field.getPartialName());
}
| 655
| 118
| 773
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/SetField.java
|
SetField
|
setField
|
class SetField
{
/**
* This will set a single field in the document.
*
* @param pdfDocument The PDF to set the field in.
* @param name The name of the field to set.
* @param value The new value of the field.
*
* @throws IOException If there is an error setting the field.
*/
public void setField(PDDocument pdfDocument, String name, String value) throws IOException
{
PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
PDField field = acroForm.getField(name);
if (field != null)
{
if (field instanceof PDCheckBox)
{
PDCheckBox checkbox = (PDCheckBox) field;
if (value.isEmpty())
{
checkbox.unCheck();
}
else
{
checkbox.check();
}
}
else if (field instanceof PDComboBox)
{
field.setValue(value);
}
else if (field instanceof PDListBox)
{
field.setValue(value);
}
else if (field instanceof PDRadioButton)
{
field.setValue(value);
}
else if (field instanceof PDTextField)
{
field.setValue(value);
}
}
else
{
System.err.println("No field found with name:" + name);
}
}
/**
* This will read a PDF file and set a field and then write it the pdf out
* again. <br>
* see usage() for commandline
*
* @param args command line arguments
*
* @throws IOException If there is an error importing the FDF document.
*/
public static void main(String[] args) throws IOException
{
SetField setter = new SetField();
setter.setField(args);
}
private void setField(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
private static String calculateOutputFilename(String filename)
{
String outputFilename;
if (filename.toLowerCase().endsWith(".pdf"))
{
outputFilename = filename.substring(0, filename.length() - 4);
}
else
{
outputFilename = filename;
}
outputFilename += "_filled.pdf";
return outputFilename;
}
/**
* This will print out a message telling how to use this example.
*/
private static void usage()
{
System.err.println("usage: org.apache.pdfbox.examples.interactive.form.SetField <pdf-file> <field-name> <field-value>");
}
}
|
PDDocument pdf = null;
try
{
if (args.length != 3)
{
usage();
}
else
{
SetField example = new SetField();
pdf = Loader.loadPDF(new File(args[0]));
example.setField(pdf, args[1], args[2]);
pdf.save(calculateOutputFilename(args[0]));
}
}
finally
{
if (pdf != null)
{
pdf.close();
}
}
| 721
| 143
| 864
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/interactive/form/UpdateFieldOnDocumentOpen.java
|
UpdateFieldOnDocumentOpen
|
main
|
class UpdateFieldOnDocumentOpen
{
private UpdateFieldOnDocumentOpen()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
// Load the PDF document created by SimpleForm.java
try (PDDocument document = Loader.loadPDF(new File("target/SimpleForm.pdf")))
{
// Note that the JavaScript will depend on the reader application.
// The classes and methods available to Adobe Reader and Adobe Acrobat
// are documented in the Acrobat SDK.
String javaScript = "var now = util.printd('yyyy-mm-dd', new Date());"
+ "var oField = this.getField('SampleField');"
+ "oField.value = now;";
// Create an action as JavaScript action
PDActionJavaScript jsAction = new PDActionJavaScript();
jsAction.setAction(javaScript);
// Set the action to be executed when the document is opened
document.getDocumentCatalog().setOpenAction(jsAction);
document.save("target/UpdateFieldOnDocumentOpen.pdf");
}
| 56
| 235
| 291
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/lucene/IndexPDFFiles.java
|
IndexPDFFiles
|
indexDocs
|
class IndexPDFFiles
{
private IndexPDFFiles()
{
}
/**
* Index all text files under a directory.
*
* @param args command line arguments
*
*/
public static void main(String[] args)
{
String usage = "java org.apache.pdfbox.lucene.IndexPDFFiles"
+ " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n"
+ "This indexes all PDF documents in DOCS_PATH, creating a Lucene index"
+ "in INDEX_PATH that can be searched with SearchFiles";
String indexPath = "index";
String docsPath = null;
boolean create = true;
for (int i = 0; i < args.length; i++)
{
if ("-index".equals(args[i]) && i + 1 < args.length)
{
indexPath = args[i + 1];
i++;
}
else if ("-docs".equals(args[i]) && i + 1 < args.length)
{
docsPath = args[i + 1];
i++;
}
else if ("-update".equals(args[i]))
{
create = false;
}
}
if (docsPath == null)
{
System.err.println("Usage: " + usage);
System.exit(1);
}
final File docDir = new File(docsPath);
if (!docDir.exists() || !docDir.canRead())
{
System.out.println("Document directory '" + docDir.getAbsolutePath()
+ "' does not exist or is not readable, please check the path");
System.exit(1);
}
Date start = new Date();
try
{
System.out.println("Indexing to directory '" + indexPath + "'...");
try (Directory dir = FSDirectory.open(new File(indexPath).toPath()))
{
Analyzer analyzer = new StandardAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
if (create)
{
// Create a new index in the directory, removing any
// previously indexed documents:
iwc.setOpenMode(OpenMode.CREATE);
}
else
{
// Add new documents to an existing index:
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
}
// Optional: for better indexing performance, if you
// are indexing many documents, increase the RAM
// buffer. But if you do this, increase the max heap
// size to the JVM (eg add -Xmx512m or -Xmx1g):
//
// iwc.setRAMBufferSizeMB(256.0);
try (final IndexWriter writer = new IndexWriter(dir, iwc))
{
indexDocs(writer, docDir);
// NOTE: if you want to maximize search performance,
// you can optionally call forceMerge here. This can be
// a terribly costly operation, so generally it's only
// worth it when your index is relatively static (ie
// you're done adding documents to it):
//
// writer.forceMerge(1);
}
}
Date end = new Date();
System.out.println(end.getTime() - start.getTime() + " total milliseconds");
}
catch (IOException e)
{
System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
}
}
/**
* Indexes the given file using the given writer, or if a directory is given, recurses over files and directories
* found under the given directory.
*
* NOTE: This method indexes one document per input file. This is slow. For good throughput, put multiple documents
* into your input file(s). An example of this is in the benchmark module, which can create "line doc" files, one
* document per line, using the <a
* href="../../../../../contrib-benchmark/org/apache/lucene/benchmark/byTask/tasks/WriteLineDocTask.html"
* >WriteLineDocTask</a>.
*
* @param writer Writer to the index where the given file/dir info will be stored
* @param file The file to index, or the directory to recurse into to find files to index
* @throws IOException If there is a low-level I/O error
*/
static void indexDocs(IndexWriter writer, File file) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
// do not try to index files that cannot be read
if (file.canRead())
{
if (file.isDirectory())
{
String[] files = file.list();
// an IO error could occur
if (files != null)
{
for (String fileName : files)
{
indexDocs(writer, new File(file, fileName));
}
}
}
else
{
FileInputStream fis;
try
{
fis = new FileInputStream(file);
}
catch (FileNotFoundException fnfe)
{
// at least on windows, some temporary files raise this exception with an "access denied" message
// checking if the file can be read doesn't help
return;
}
try
{
String path = file.getName().toUpperCase();
Document doc;
if (path.toLowerCase().endsWith(".pdf"))
{
System.out.println("Indexing PDF document: " + file);
doc = LucenePDFDocument.getDocument(file);
}
else
{
System.out.println("Skipping " + file);
return;
}
if (writer.getConfig().getOpenMode() == OpenMode.CREATE)
{
// New index, so we just add the document (no old document can be there):
System.out.println("adding " + file);
writer.addDocument(doc);
}
else
{
// Existing index (an old copy of this document may have been indexed) so
// we use updateDocument instead to replace the old one matching the exact
// path, if present:
System.out.println("updating " + file);
writer.updateDocument(new Term("uid", LucenePDFDocument.createUID(file)), doc);
}
}
finally
{
fis.close();
}
}
}
| 1,175
| 485
| 1,660
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/AddImageToPDF.java
|
AddImageToPDF
|
createPDFFromImage
|
class AddImageToPDF
{
/**
* Add an image to an existing PDF document.
*
* @param inputFile The input PDF to add the image to.
* @param imagePath The filename of the image to put in the PDF.
* @param outputFile The file to write to the pdf to.
*
* @throws IOException If there is an error writing the data.
*/
public void createPDFFromImage( String inputFile, String imagePath, String outputFile )
throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will load a PDF document and add a single image on it.
* <br>
* see usage() for commandline
*
* @param args Command line arguments.
*/
public static void main(String[] args) throws IOException
{
AddImageToPDF app = new AddImageToPDF();
if( args.length != 3 )
{
app.usage();
}
else
{
app.createPDFFromImage( args[0], args[1], args[2] );
}
}
/**
* This will print out a message telling how to use this example.
*/
private void usage()
{
System.err.println( "usage: " + this.getClass().getName() + " <input-pdf> <image> <output-pdf>" );
}
}
|
try (PDDocument doc = Loader.loadPDF(new File(inputFile)))
{
//we will add the image to the first page.
PDPage page = doc.getPage(0);
// createFromFile is the easiest way with an image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true))
{
// contentStream.drawImage(ximage, 20, 20 );
// better method inspired by http://stackoverflow.com/a/22318681/535646
// reduce this value if the image is too large
float scale = 1f;
contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth() * scale, pdImage.getHeight() * scale);
}
doc.save(outputFile);
}
| 350
| 287
| 637
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.