http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxComponent.java ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxComponent.java b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxComponent.java new file mode 100644 index 0000000..70d3344 --- /dev/null +++ b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxComponent.java @@ -0,0 +1,115 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.box; + +import com.box.sdk.BoxAPIConnection; + +import org.apache.camel.CamelContext; +import org.apache.camel.Endpoint; +import org.apache.camel.component.box.internal.BoxConnectionHelper; +import org.apache.camel.component.box.internal.BoxApiCollection; +import org.apache.camel.component.box.internal.BoxApiName; +import org.apache.camel.spi.Metadata; +import org.apache.camel.util.component.AbstractApiComponent; + +/** + * Represents the component that manages {@link BoxEndpoint}. + * + * + * + */ +// @UriEndpoint(scheme = "box", consumerClass = BoxConsumer.class, +// consumerPrefix = "consumer", syntax = "", title = "Box Component") +public class BoxComponent extends AbstractApiComponent<BoxApiName, BoxConfiguration, BoxApiCollection> { + + @Metadata(label = "advanced") + BoxAPIConnection boxConnection; + + public BoxComponent() { + super(BoxEndpoint.class, BoxApiName.class, BoxApiCollection.getCollection()); + } + + public BoxComponent(CamelContext context) { + super(context, BoxEndpoint.class, BoxApiName.class, BoxApiCollection.getCollection()); + } + + @Override + protected BoxApiName getApiName(String apiNameStr) throws IllegalArgumentException { + return BoxApiName.fromValue(apiNameStr); + } + + /** + * To use the shared configuration + */ + @Override + public void setConfiguration(BoxConfiguration configuration) { + super.setConfiguration(configuration); + } + + /** + * To use the shared configuration + */ + @Override + public BoxConfiguration getConfiguration() { + return super.getConfiguration(); + } + + /** + * To use a shared connection + * + * @return the shared connection + */ + public BoxAPIConnection getBoxConnection() { + return boxConnection; + } + + @Override + protected Endpoint createEndpoint(String uri, String methodName, BoxApiName apiName, + BoxConfiguration endpointConfiguration) { + endpointConfiguration.setApiName(apiName); + endpointConfiguration.setMethodName(methodName); + return new BoxEndpoint(uri, this, apiName, methodName, endpointConfiguration); + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + + if (boxConnection == null) { + if (configuration != null) { + boxConnection = BoxConnectionHelper.createConnection(configuration); + } else { + throw new IllegalArgumentException("Unable to connect, Box component configuration is missing"); + } + } + } + + @Override + protected void doStop() throws Exception { + if (boxConnection != null) { + boxConnection = null; + } + } + + @Override + public void doShutdown() throws Exception { + if (boxConnection != null) { + boxConnection = null; + } + super.doShutdown(); + } +}
http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxConfiguration.java ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxConfiguration.java b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxConfiguration.java new file mode 100644 index 0000000..242fff7 --- /dev/null +++ b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxConfiguration.java @@ -0,0 +1,475 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.box; + +import java.util.Map; + +import com.box.sdk.EncryptionAlgorithm; +import com.box.sdk.IAccessTokenCache; + +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.component.box.internal.BoxApiName; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriParams; +import org.apache.camel.spi.UriPath; +import org.apache.camel.util.jsse.SSLContextParameters; + +/** + * Component configuration for Box component. + * + * + * + */ +@UriParams +public class BoxConfiguration { + + /** + * Authentication Types for Connection + */ + public static final String APP_ENTERPRISE_AUTHENTICATION = "APP_ENTERPRISE_AUTHENTICATION"; + public static final String APP_USER_AUTHENTICATION = "APP_USER_AUTHENTICATION"; + public static final String STANDARD_AUTHENTICATION = "STANDARD_AUTHENTICATION"; + + /** + * Encryption Algorithm Types for Server Authentication. + */ + public static final String RSA_SHA_512 = "RSA_SHA_512"; + public static final String RSA_SHA_384 = "RSA_SHA_384"; + public static final String RSA_SHA_256 = "RSA_SHA_256"; + + @UriPath + @Metadata(required = "true") + private BoxApiName apiName; + + @UriPath + @Metadata(required = "true") + private String methodName; + + @UriParam + private String enterpriseId; + + @UriParam + private String userId; + + @UriParam + private String clientId; + + @UriParam(label = "security", secret = true) + private String publicKeyId; + + @UriParam(label = "security", secret = true) + private String privateKeyFile; + + @UriParam(label = "security", secret = true) + private String privateKeyPassword; + + @UriParam(label = "security", secret = true) + private String clientSecret; + @UriParam(label = "security", secret = true) + private String userName; + @UriParam(label = "security", secret = true) + private String userPassword; + + @UriParam(label = "advanced,security") + private IAccessTokenCache accessTokenCache; + + @UriParam(label = "advanced,security", defaultValue = "100") + private int maxCacheEntries; + + @UriParam(label = "advanced,security", defaultValue = RSA_SHA_256) + private EncryptionAlgorithm encryptionAlgorithm; + + @UriParam(label = "authentication", defaultValue = APP_USER_AUTHENTICATION) + private String authenticationType; + + @UriParam(label = "advanced") + private Map<String, Object> httpParams; + @UriParam(label = "security") + private SSLContextParameters sslContextParameters; + + /** + * What kind of operation to perform + * + * @return the API Name + */ + public BoxApiName getApiName() { + return apiName; + } + + /** + * What kind of operation to perform + * + * @param apiName + * the API Name to set + */ + public void setApiName(BoxApiName apiName) { + this.apiName = apiName; + } + + /** + * What sub operation to use for the selected operation + * + * @return the methodName + */ + public String getMethodName() { + return methodName; + } + + /** + * What sub operation to use for the selected operation + * + * @param methodName + * the methodName to set + */ + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + /** + * The enterprise ID to use for an App Enterprise. + * + * @return the enterpriseId + */ + public String getEnterpriseId() { + return enterpriseId; + } + + /** + * The enterprise ID to use for an App Enterprise. + * + * @param enterpriseId + * the enterpriseId to set + */ + public void setEnterpriseId(String enterpriseId) { + this.enterpriseId = enterpriseId; + } + + /** + * The user ID to use for an App User. + * + * @return the userId + */ + public String getUserId() { + return userId; + } + + /** + * The user ID to use for an App User. + * + * @param userId + * the userId to set + */ + public void setUserId(String userId) { + this.userId = userId; + } + + /** + * The ID for public key for validating the JWT signature. + * + * @return the publicKeyId + */ + public String getPublicKeyId() { + return publicKeyId; + } + + /** + * The ID for public key for validating the JWT signature. + * + * @param publicKeyId + * the publicKeyId to set + */ + public void setPublicKeyId(String publicKeyId) { + this.publicKeyId = publicKeyId; + } + + /** + * The private key for generating the JWT signature. + * + * @return the privateKey + */ + public String getPrivateKeyFile() { + return privateKeyFile; + } + + /** + * The private key for generating the JWT signature. + * + * @param privateKey + * the privateKey to set + */ + public void setPrivateKeyFile(String privateKey) { + this.privateKeyFile = privateKey; + } + + /** + * The password for the private key. + * + * @return the privateKeyPassword + */ + public String getPrivateKeyPassword() { + return privateKeyPassword; + } + + /** + * The password for the private key. + * + * @param privateKeyPassword + * the privateKeyPassword to set + */ + public void setPrivateKeyPassword(String privateKeyPassword) { + this.privateKeyPassword = privateKeyPassword; + } + + /** + * The maximum number of access tokens in cache. + * + * @return the maxCacheEntries + */ + public int getMaxCacheEntries() { + return maxCacheEntries; + } + + /** + * The maximum number of access tokens in cache. + * + * @param maxCacheEntries + * the maxCacheEntries to set + */ + public void setMaxCacheEntries(String maxCacheEntries) { + try { + this.maxCacheEntries = Integer.decode(maxCacheEntries); + } catch (NumberFormatException e) { + throw new RuntimeCamelException(String.format("Invalid 'maxCacheEntries' value: %s", maxCacheEntries), e); + } + } + + /** + * The type of encryption algorithm for JWT. + * + * @return the encryptionAlgorithm + */ + public EncryptionAlgorithm getEncryptionAlgorithm() { + return encryptionAlgorithm; + } + + /** + * The type of encryption algorithm for JWT. + * + * <p> + * Supported Algorithms: + * <ul> + * <li>RSA_SHA_256</li> + * <li>RSA_SHA_384</li> + * <li>RSA_SHA_512</li> + * </ul> + * + * @param encryptionAlgorithm + * the encryptionAlgorithm to set + */ + public void setEncryptionAlgorithm(String encryptionAlgorithm) { + switch (encryptionAlgorithm) { + case RSA_SHA_256: + this.encryptionAlgorithm = EncryptionAlgorithm.RSA_SHA_256; + return; + case RSA_SHA_384: + this.encryptionAlgorithm = EncryptionAlgorithm.RSA_SHA_384; + return; + case RSA_SHA_512: + this.encryptionAlgorithm = EncryptionAlgorithm.RSA_SHA_512; + return; + default: + throw new RuntimeCamelException(String.format("Invalid Encryption Algorithm: %s", encryptionAlgorithm)); + } + } + + /** + * The type of authentication for connection. + * + * <p> + * Types of Authentication: + * <ul> + * <li>STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged)</li> + * <li>SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens</li> + * </ul> + * + * @return the authenticationType + */ + public String getAuthenticationType() { + return authenticationType; + } + + /** + * The type of authentication for connection. + * + * <p> + * Types of Authentication: + * <ul> + * <li>STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged)</li> + * <li>SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens</li> + * </ul> + * + * @param authenticationType + * the authenticationType to set + */ + public void setAuthenticationType(String authenticationType) { + switch (authenticationType) { + case STANDARD_AUTHENTICATION: + case APP_USER_AUTHENTICATION: + case APP_ENTERPRISE_AUTHENTICATION: + this.authenticationType = authenticationType; + return; + default: + throw new RuntimeCamelException(String.format("Invalid Authentication Type: %s", authenticationType)); + } + } + + /** + * Box application client ID + * + * @return the clientId + */ + public String getClientId() { + return clientId; + } + + /** + * Box application client ID + * + * @param clientId + * the clientId to set + */ + public void setClientId(String clientId) { + this.clientId = clientId; + } + + /** + * Box application client secret + * + * @return the clientSecret + */ + public String getClientSecret() { + return clientSecret; + } + + /** + * Box application client secret + * + * @param clientSecret + * the clientSecret to set + */ + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + /** + * Box user name, MUST be provided + * + * @return the userName + */ + public String getUserName() { + return userName; + } + + /** + * Box user name, MUST be provided + * + * @param userName + * the userName to set + */ + public void setUserName(String userName) { + this.userName = userName; + } + + /** + * Box user password, MUST be provided if authSecureStorage is not set, or + * returns null on first call + * + * @return the userPassword + */ + public String getUserPassword() { + return userPassword; + } + + /** + * Box user password, MUST be provided if authSecureStorage is not set, or + * returns null on first call + * + * @param userPassword + * the userPassword to set + */ + public void setUserPassword(String userPassword) { + this.userPassword = userPassword; + } + + /** + * Custom HTTP params for settings like proxy host + * + * @return the httpParams + */ + public Map<String, Object> getHttpParams() { + return httpParams; + } + + /** + * Custom HTTP params for settings like proxy host + * + * @param httpParams + * the httpParams to set + */ + public void setHttpParams(Map<String, Object> httpParams) { + this.httpParams = httpParams; + } + + /** + * To configure security using SSLContextParameters. + * + * @return the sslContextParameters + */ + public SSLContextParameters getSslContextParameters() { + return sslContextParameters; + } + + /** + * To configure security using SSLContextParameters. + * + * @param sslContextParameters + * the sslContextParameters to set + */ + public void setSslContextParameters(SSLContextParameters sslContextParameters) { + this.sslContextParameters = sslContextParameters; + } + + /** + * Custom Access Token Cache for storing and retrieving access tokens. + * + * @return Custom Access Token Cache + */ + public IAccessTokenCache getAccessTokenCache() { + return accessTokenCache; + } + + /** + * Custom Access Token Cache for storing and retrieving access tokens. + * + * @param accessTokenCache + * - the Custom Access Token Cache + */ + public void setAccessTokenCache(IAccessTokenCache accessTokenCache) { + this.accessTokenCache = accessTokenCache; + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxConsumer.java ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxConsumer.java b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxConsumer.java new file mode 100644 index 0000000..888b676 --- /dev/null +++ b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxConsumer.java @@ -0,0 +1,111 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.box; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.box.sdk.BoxAPIConnection; +import com.box.sdk.BoxEvent; +import com.box.sdk.EventListener; + +import org.apache.camel.Processor; +import org.apache.camel.component.box.api.BoxEventsManager; +import org.apache.camel.component.box.internal.BoxApiName; +import org.apache.camel.util.ObjectHelper; +import org.apache.camel.util.component.AbstractApiConsumer; +import org.apache.camel.util.component.ApiConsumerHelper; +import org.apache.camel.util.component.ApiMethod; +import org.apache.camel.util.component.ApiMethodHelper; + +/** + * The Box consumer. + * + * + * + */ +public class BoxConsumer extends AbstractApiConsumer<BoxApiName, BoxConfiguration> implements EventListener { + + private static final String LISTENER_PROPERTY = "listener"; + + private BoxAPIConnection boxConnection; + + private BoxEventsManager apiProxy; + + private final ApiMethod apiMethod; + + private final Map<String, Object> properties; + + public BoxConsumer(BoxEndpoint endpoint, Processor processor) { + super(endpoint, processor); + + apiMethod = ApiConsumerHelper.findMethod(endpoint, this); + + // Add listener property to register this consumer as listener for + // events. + properties = new HashMap<String, Object>(); + properties.putAll(endpoint.getEndpointProperties()); + properties.put(LISTENER_PROPERTY, this); + + boxConnection = endpoint.getBoxConnection(); + + apiProxy = new BoxEventsManager(boxConnection); + } + + @Override + public void interceptPropertyNames(Set<String> propertyNames) { + propertyNames.add(LISTENER_PROPERTY); + } + + @Override + public void onEvent(BoxEvent event) { + try { + // Convert Events to exchange and process + log.debug("Processed {} event for {}", ApiConsumerHelper.getResultsProcessed(this, event, false), + boxConnection); + } catch (Exception e) { + log.info("Received exception consuming event: ", e); + } + } + + @Override + public void onNextPosition(long position) { + } + + @Override + public boolean onException(Throwable e) { + getExceptionHandler().handleException(ObjectHelper.wrapRuntimeCamelException(e)); + return true; + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + + // invoke the API method to start listening + ApiMethodHelper.invokeMethod(apiProxy, apiMethod, properties); + } + + @Override + protected void doStop() throws Exception { + apiProxy.stopListening(); + + super.doStop(); + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxEndpoint.java ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxEndpoint.java b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxEndpoint.java new file mode 100644 index 0000000..fd7ecde --- /dev/null +++ b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxEndpoint.java @@ -0,0 +1,214 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.box; + +import java.util.Map; + +import com.box.sdk.BoxAPIConnection; + +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.component.box.api.BoxFilesManager; +import org.apache.camel.component.box.api.BoxCollaborationsManager; +import org.apache.camel.component.box.api.BoxCommentsManager; +import org.apache.camel.component.box.api.BoxEventLogsManager; +import org.apache.camel.component.box.api.BoxEventsManager; +import org.apache.camel.component.box.api.BoxFoldersManager; +import org.apache.camel.component.box.api.BoxGroupsManager; +import org.apache.camel.component.box.api.BoxSearchManager; +import org.apache.camel.component.box.api.BoxTasksManager; +import org.apache.camel.component.box.api.BoxUsersManager; +import org.apache.camel.component.box.internal.BoxApiCollection; +import org.apache.camel.component.box.internal.BoxApiName; +import org.apache.camel.component.box.internal.BoxConnectionHelper; +import org.apache.camel.component.box.internal.BoxConstants; +import org.apache.camel.component.box.internal.BoxPropertiesHelper; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.util.component.AbstractApiEndpoint; +import org.apache.camel.util.component.ApiMethod; +import org.apache.camel.util.component.ApiMethodPropertiesHelper; + +/** + * Represents a Box endpoint. + * + * + * + */ +@UriEndpoint(scheme = "box", title = "Box", syntax = "box:apiName/methodName", consumerClass = BoxConsumer.class, consumerPrefix = "consumer", label = "api,file,cloud", lenientProperties = true) +public class BoxEndpoint extends AbstractApiEndpoint<BoxApiName, BoxConfiguration> { + + @UriParam(name = "configuration", description = "Box 2 Configuration") + private BoxConfiguration configuration; + + // cached connection + private BoxAPIConnection boxConnection; + + private Object apiProxy; + + private boolean boxConnectionShared; + + public BoxEndpoint(String uri, BoxComponent component, BoxApiName apiName, String methodName, + BoxConfiguration endpointConfiguration) { + super(uri, component, apiName, methodName, BoxApiCollection.getCollection().getHelper(apiName), + endpointConfiguration); + this.configuration = endpointConfiguration; + } + + /* + * (non-Javadoc) + * + * @see org.apache.camel.impl.DefaultEndpoint#getComponent() + */ + @Override + public BoxComponent getComponent() { + return (BoxComponent) super.getComponent(); + } + + /** + * The BoxAPIConnection of endpoint. + * + * @return the BoxAPIConnection of endpoint. + */ + public BoxAPIConnection getBoxConnection() { + return boxConnection; + } + + /* + * (non-Javadoc) + * + * @see org.apache.camel.Endpoint#createProducer() + */ + public Producer createProducer() throws Exception { + return new BoxProducer(this); + } + + /* + * (non-Javadoc) + * + * @see org.apache.camel.Endpoint#createConsumer(org.apache.camel.Processor) + */ + public Consumer createConsumer(Processor processor) throws Exception { + // make sure inBody is not set for consumers + if (inBody != null) { + throw new IllegalArgumentException("Option inBody is not supported for consumer endpoint"); + } + final BoxConsumer consumer = new BoxConsumer(this, processor); + // also set consumer.* properties + configureConsumer(consumer); + return consumer; + } + + /* + * (non-Javadoc) + * + * @see + * org.apache.camel.util.component.AbstractApiEndpoint#getPropertiesHelper() + */ + @Override + protected ApiMethodPropertiesHelper<BoxConfiguration> getPropertiesHelper() { + return BoxPropertiesHelper.getHelper(); + } + + /* + * (non-Javadoc) + * + * @see + * org.apache.camel.util.component.AbstractApiEndpoint#getThreadProfileName( + * ) + */ + protected String getThreadProfileName() { + return BoxConstants.THREAD_PROFILE_NAME; + } + + /* + * (non-Javadoc) + * + * @see org.apache.camel.util.component.AbstractApiEndpoint# + * afterConfigureProperties() + */ + @Override + protected void afterConfigureProperties() { + // create connection eagerly, a good way to validate configuration + createBoxConnection(); + + } + + /* + * (non-Javadoc) + * + * @see org.apache.camel.util.component.AbstractApiEndpoint#getApiProxy(org. + * apache.camel.util.component.ApiMethod, java.util.Map) + */ + @Override + public Object getApiProxy(ApiMethod method, Map<String, Object> args) { + if (apiProxy == null) { + // create API proxy lazily + createApiProxy(args); + } + return apiProxy; + } + + private void createBoxConnection() { + final BoxComponent component = getComponent(); + this.boxConnectionShared = configuration.equals(getComponent().getConfiguration()); + if (boxConnectionShared) { + // get shared singleton connection from Component + this.boxConnection = component.getBoxConnection(); + } else { + this.boxConnection = BoxConnectionHelper.createConnection(configuration); + } + } + + private void createApiProxy(Map<String, Object> args) { + switch (apiName) { + case COLLABORATIONS: + apiProxy = new BoxCollaborationsManager(getBoxConnection()); + break; + case COMMENTS: + apiProxy = new BoxCommentsManager(getBoxConnection()); + break; + case EVENT_LOGS: + apiProxy = new BoxEventLogsManager(getBoxConnection()); + break; + case EVENTS: + apiProxy = new BoxEventsManager(getBoxConnection()); + break; + case FILES: + apiProxy = new BoxFilesManager(getBoxConnection()); + break; + case FOLDERS: + apiProxy = new BoxFoldersManager(getBoxConnection()); + break; + case GROUPS: + apiProxy = new BoxGroupsManager(getBoxConnection()); + break; + case SEARCH: + apiProxy = new BoxSearchManager(getBoxConnection()); + break; + case TASKS: + apiProxy = new BoxTasksManager(getBoxConnection()); + break; + case USERS: + apiProxy = new BoxUsersManager(getBoxConnection()); + break; + default: + throw new IllegalArgumentException("Invalid API name " + apiName); + } + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxProducer.java ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxProducer.java b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxProducer.java new file mode 100644 index 0000000..0df9c12 --- /dev/null +++ b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/BoxProducer.java @@ -0,0 +1,35 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.box; + +import org.apache.camel.component.box.internal.BoxApiName; +import org.apache.camel.component.box.internal.BoxPropertiesHelper; + +import org.apache.camel.util.component.AbstractApiProducer; + +/** + * The Box producer. + * + * + * + */ +public class BoxProducer extends AbstractApiProducer<BoxApiName, BoxConfiguration> { + + public BoxProducer(BoxEndpoint endpoint) { + super(endpoint, BoxPropertiesHelper.getHelper()); + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxConnectionHelper.java ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxConnectionHelper.java b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxConnectionHelper.java new file mode 100644 index 0000000..2158d64 --- /dev/null +++ b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxConnectionHelper.java @@ -0,0 +1,286 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.box.internal; + +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.net.ssl.SSLContext; + +import com.box.sdk.BoxAPIConnection; +import com.box.sdk.BoxAPIException; +import com.box.sdk.BoxDeveloperEditionAPIConnection; +import com.box.sdk.IAccessTokenCache; +import com.box.sdk.InMemoryLRUAccessTokenCache; +import com.box.sdk.JWTEncryptionPreferences; +import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; +import com.gargoylesoftware.htmlunit.Page; +import com.gargoylesoftware.htmlunit.ProxyConfig; +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.WebClientOptions; +import com.gargoylesoftware.htmlunit.WebRequest; +import com.gargoylesoftware.htmlunit.WebResponse; +import com.gargoylesoftware.htmlunit.html.HtmlButton; +import com.gargoylesoftware.htmlunit.html.HtmlDivision; +import com.gargoylesoftware.htmlunit.html.HtmlForm; +import com.gargoylesoftware.htmlunit.html.HtmlPage; +import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput; +import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; +import com.gargoylesoftware.htmlunit.html.HtmlTextInput; +import com.gargoylesoftware.htmlunit.util.WebConnectionWrapper; + +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.component.box.BoxConfiguration; +import org.apache.camel.util.ObjectHelper; +import org.apache.camel.util.jsse.SSLContextParameters; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpHost; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * BoxConnectionHelper + * + * <p> + * Utility class for creating Box API Connections + * + * + * + */ +public final class BoxConnectionHelper { + + private static final Logger LOG = LoggerFactory.getLogger(BoxConnectionHelper.class); + + private static final Pattern QUERY_PARAM_PATTERN = Pattern.compile("&?([^=]+)=([^&]+)"); + + private BoxConnectionHelper() { + // hide utility class constructor + } + + public static BoxAPIConnection createConnection(final BoxConfiguration configuration) { + if (configuration.getAuthenticationType() == null) { + throw new RuntimeCamelException( + "Box API connection failed: Authentication type not specified in configuration"); + } + switch (configuration.getAuthenticationType()) { + case BoxConfiguration.APP_ENTERPRISE_AUTHENTICATION: + return createAppEnterpriseAuthenticatedConnection(configuration); + case BoxConfiguration.APP_USER_AUTHENTICATION: + return createAppUserAuthenticatedConnection(configuration); + case BoxConfiguration.STANDARD_AUTHENTICATION: + return createStandardAuthenticatedConnection(configuration); + default: + throw new RuntimeCamelException(String.format("Box API connection failed: Invalid authentication type '%s'", + configuration.getAuthenticationType())); + } + } + + public static BoxAPIConnection createStandardAuthenticatedConnection(BoxConfiguration configuration) { + + // Create web client for first leg of OAuth2 + // + final WebClient webClient = new WebClient(); + final WebClientOptions options = webClient.getOptions(); + options.setRedirectEnabled(true); + options.setJavaScriptEnabled(false); + options.setThrowExceptionOnFailingStatusCode(true); + options.setThrowExceptionOnScriptError(true); + options.setPrintContentOnFailingStatusCode(LOG.isDebugEnabled()); + try { + // use default SSP to create supported non-SSL protocols list + final SSLContext sslContext = new SSLContextParameters().createSSLContext(null); + options.setSSLClientProtocols(sslContext.createSSLEngine().getEnabledProtocols()); + } catch (GeneralSecurityException e) { + throw ObjectHelper.wrapRuntimeCamelException(e); + } catch (IOException e) { + throw ObjectHelper.wrapRuntimeCamelException(e); + } finally { + if (webClient != null) { + webClient.close(); + } + } + + // disable default gzip compression, as htmlunit does not negotiate + // pages sent with no compression + new WebConnectionWrapper(webClient) { + @Override + public WebResponse getResponse(WebRequest request) throws IOException { + request.setAdditionalHeader(HttpHeaders.ACCEPT_ENCODING, "identity"); + return super.getResponse(request); + } + }; + + // add HTTP proxy if set + final Map<String, Object> httpParams = configuration.getHttpParams(); + if (httpParams != null && httpParams.get("http.route.default-proxy") != null) { + final HttpHost proxyHost = (HttpHost) httpParams.get("http.route.default-proxy"); + final Boolean socksProxy = (Boolean) httpParams.get("http.route.socks-proxy"); + final ProxyConfig proxyConfig = new ProxyConfig(proxyHost.getHostName(), proxyHost.getPort(), + socksProxy != null ? socksProxy : false); + options.setProxyConfig(proxyConfig); + } + + // authorize application on user's behalf + try { + + // generate anti-forgery token to prevent/detect CSRF attack + final String csrfToken = String.valueOf(new SecureRandom().nextLong()); + + final HtmlPage authPage = webClient.getPage(authorizationUrl(configuration.getClientId(), csrfToken)); + + // look for <div role="error_message"> + final HtmlDivision div = authPage + .getFirstByXPath("//div[contains(concat(' ', @class, ' '), ' error_message ')]"); + if (div != null) { + final String errorMessage = div.getTextContent().replaceAll("\\s+", " ") + .replaceAll(" Show Error Details", ":").trim(); + throw new IllegalArgumentException("Error authorizing application: " + errorMessage); + } + + // submit login credentials + final HtmlForm loginForm = authPage.getFormByName("login_form"); + final HtmlTextInput login = loginForm.getInputByName("login"); + login.setText(configuration.getUserName()); + final HtmlPasswordInput password = loginForm.getInputByName("password"); + password.setText(configuration.getUserPassword()); + final HtmlSubmitInput submitInput = loginForm.getInputByName("login_submit"); + + // submit consent + final HtmlPage consentPage = submitInput.click(); + final HtmlForm consentForm = consentPage.getFormByName("consent_form"); + final HtmlButton consentAccept = consentForm.getButtonByName("consent_accept"); + + // disable redirect to avoid loading redirect URL + webClient.getOptions().setRedirectEnabled(false); + + // validate CSRF and get authorization code + String redirectQuery; + try { + final Page redirectPage = consentAccept.click(); + redirectQuery = redirectPage.getUrl().getQuery(); + } catch (FailingHttpStatusCodeException e) { + // escalate non redirect errors + if (e.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) { + throw e; + } + final String location = e.getResponse().getResponseHeaderValue("Location"); + redirectQuery = new URL(location).getQuery(); + } + final Map<String, String> params = new HashMap<String, String>(); + final Matcher matcher = QUERY_PARAM_PATTERN.matcher(redirectQuery); + while (matcher.find()) { + params.put(matcher.group(1), matcher.group(2)); + } + final String state = params.get("state"); + if (!csrfToken.equals(state)) { + throw new SecurityException("Invalid CSRF code!"); + } else { + + // get authorization code + final String authorizationCode = params.get("code"); + + return new BoxAPIConnection(configuration.getClientId(), configuration.getClientSecret(), + authorizationCode); + } + + } catch (BoxAPIException e) { + throw new RuntimeCamelException( + String.format("Box API connection failed: API returned the error code %d\n\n%s", + e.getResponseCode(), e.getResponse()), + e); + } catch (Exception e) { + throw new RuntimeCamelException(String.format("Box API connection failed: %s", e.getMessage()), e); + } + } + + public static BoxAPIConnection createAppUserAuthenticatedConnection(BoxConfiguration configuration) { + // Create Encryption Preferences + JWTEncryptionPreferences encryptionPref = new JWTEncryptionPreferences(); + encryptionPref.setPublicKeyID(configuration.getPublicKeyId()); + + try { + encryptionPref.setPrivateKey(new String(Files.readAllBytes(Paths.get(configuration.getPrivateKeyFile())))); + } catch (Exception e) { + throw new RuntimeCamelException("Box API connection failed: could not read privateKeyFile", e); + } + + encryptionPref.setPrivateKeyPassword(configuration.getPrivateKeyPassword()); + encryptionPref.setEncryptionAlgorithm(configuration.getEncryptionAlgorithm()); + + IAccessTokenCache accessTokenCache = configuration.getAccessTokenCache(); + if (accessTokenCache == null) { + accessTokenCache = new InMemoryLRUAccessTokenCache(configuration.getMaxCacheEntries()); + } + + try { + return BoxDeveloperEditionAPIConnection.getAppUserConnection(configuration.getUserId(), + configuration.getClientId(), configuration.getClientSecret(), encryptionPref, accessTokenCache); + } catch (BoxAPIException e) { + throw new RuntimeCamelException( + String.format("Box API connection failed: API returned the error code %d\n\n%s", + e.getResponseCode(), e.getResponse()), + e); + } + + } + + public static BoxAPIConnection createAppEnterpriseAuthenticatedConnection(BoxConfiguration configuration) { + // Create Encryption Preferences + JWTEncryptionPreferences encryptionPref = new JWTEncryptionPreferences(); + encryptionPref.setPublicKeyID(configuration.getPublicKeyId()); + + try { + encryptionPref.setPrivateKey(new String(Files.readAllBytes(Paths.get(configuration.getPrivateKeyFile())))); + } catch (Exception e) { + throw new RuntimeCamelException("Box API connection failed: could not read privateKeyFile", e); + } + + encryptionPref.setPrivateKeyPassword(configuration.getPrivateKeyPassword()); + encryptionPref.setEncryptionAlgorithm(configuration.getEncryptionAlgorithm()); + + IAccessTokenCache accessTokenCache = configuration.getAccessTokenCache(); + if (accessTokenCache == null) { + accessTokenCache = new InMemoryLRUAccessTokenCache(configuration.getMaxCacheEntries()); + } + + try { + return BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(configuration.getEnterpriseId(), + configuration.getClientId(), configuration.getClientSecret(), encryptionPref, accessTokenCache); + } catch (BoxAPIException e) { + throw new RuntimeCamelException( + String.format("Box API connection failed: API returned the error code %d\n\n%s", + e.getResponseCode(), e.getResponse()), + e); + } + + } + + public static String authorizationUrl(String clientId, String stateToken) { + return "https://account.box.com/api/oauth2/authorize?response_type=code&redirect_url=https%3A%2F%2Flocalhost%2F&client_id=" + + clientId + "&state=" + stateToken; + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxConstants.java ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxConstants.java b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxConstants.java new file mode 100644 index 0000000..c4922fa --- /dev/null +++ b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxConstants.java @@ -0,0 +1,32 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.box.internal; + +/** + * Constants for Box component. + * + * + * + */ +public interface BoxConstants { + + // suffix for parameters when passed as exchange header properties + String PROPERTY_PREFIX = "CamelBox."; + + // thread profile name for this component + String THREAD_PROFILE_NAME = "CamelBox"; +} http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxPropertiesHelper.java ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxPropertiesHelper.java b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxPropertiesHelper.java new file mode 100644 index 0000000..2ad52ce --- /dev/null +++ b/components/camel-box/camel-box-component/src/main/java/org/apache/camel/component/box/internal/BoxPropertiesHelper.java @@ -0,0 +1,42 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.box.internal; + +import org.apache.camel.component.box.BoxConfiguration; +import org.apache.camel.util.component.ApiMethodPropertiesHelper; + +/** + * Singleton {@link ApiMethodPropertiesHelper} for Box component. + * + * + * + */ +public final class BoxPropertiesHelper extends ApiMethodPropertiesHelper<BoxConfiguration> { + + private static BoxPropertiesHelper helper; + + private BoxPropertiesHelper() { + super(BoxConfiguration.class, BoxConstants.PROPERTY_PREFIX); + } + + public static synchronized BoxPropertiesHelper getHelper() { + if (helper == null) { + helper = new BoxPropertiesHelper(); + } + return helper; + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/main/resources/META-INF/LICENSE.txt ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/main/resources/META-INF/LICENSE.txt b/components/camel-box/camel-box-component/src/main/resources/META-INF/LICENSE.txt new file mode 100644 index 0000000..6b0b127 --- /dev/null +++ b/components/camel-box/camel-box-component/src/main/resources/META-INF/LICENSE.txt @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/main/resources/META-INF/NOTICE.txt ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/main/resources/META-INF/NOTICE.txt b/components/camel-box/camel-box-component/src/main/resources/META-INF/NOTICE.txt new file mode 100644 index 0000000..2e215bf --- /dev/null +++ b/components/camel-box/camel-box-component/src/main/resources/META-INF/NOTICE.txt @@ -0,0 +1,11 @@ + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Apache Camel distribution. == + ========================================================================= + + This product includes software developed by + The Apache Software Foundation (http://www.apache.org/). + + Please read the different LICENSE files present in the licenses directory of + this distribution. http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/main/resources/META-INF/services/org/apache/camel/component/box ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/main/resources/META-INF/services/org/apache/camel/component/box b/components/camel-box/camel-box-component/src/main/resources/META-INF/services/org/apache/camel/component/box new file mode 100644 index 0000000..43c4063 --- /dev/null +++ b/components/camel-box/camel-box-component/src/main/resources/META-INF/services/org/apache/camel/component/box @@ -0,0 +1,18 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +class=org.apache.camel.component.box.BoxComponent http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/AbstractBoxTestSupport.java ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/AbstractBoxTestSupport.java b/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/AbstractBoxTestSupport.java new file mode 100644 index 0000000..6d87573 --- /dev/null +++ b/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/AbstractBoxTestSupport.java @@ -0,0 +1,82 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.box; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.apache.camel.CamelContext; +import org.apache.camel.CamelExecutionException; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.apache.camel.util.IntrospectionSupport; + +/** + * Abstract base class for Box Integration tests generated by Camel API component maven plugin. + */ +public class AbstractBoxTestSupport extends CamelTestSupport { + + private static final String TEST_OPTIONS_PROPERTIES = "/test-options.properties"; + + @Override + protected CamelContext createCamelContext() throws Exception { + + final CamelContext context = super.createCamelContext(); + + // read Box component configuration from TEST_OPTIONS_PROPERTIES + final Properties properties = new Properties(); + try { + properties.load(getClass().getResourceAsStream(TEST_OPTIONS_PROPERTIES)); + } catch (Exception e) { + throw new IOException(String.format("%s could not be loaded: %s", TEST_OPTIONS_PROPERTIES, e.getMessage()), + e); + } + + Map<String, Object> options = new HashMap<String, Object>(); + for (Map.Entry<Object, Object> entry : properties.entrySet()) { + options.put(entry.getKey().toString(), entry.getValue()); + } + + final BoxConfiguration configuration = new BoxConfiguration(); + IntrospectionSupport.setProperties(configuration, options); + + // add BoxComponent to Camel context + final BoxComponent component = new BoxComponent(context); + component.setConfiguration(configuration); + context.addComponent("box", component); + + return context; + } + + @Override + public boolean isCreateCamelContextPerClass() { + // only create the context once for this class + return true; + } + + @SuppressWarnings("unchecked") + protected <T> T requestBodyAndHeaders(String endpointUri, Object body, Map<String, Object> headers) + throws CamelExecutionException { + return (T) template().requestBodyAndHeaders(endpointUri, body, headers); + } + + @SuppressWarnings("unchecked") + protected <T> T requestBody(String endpoint, Object body) throws CamelExecutionException { + return (T) template().requestBody(endpoint, body); + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/BoxCollaborationsManagerIntegrationTest.java ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/BoxCollaborationsManagerIntegrationTest.java b/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/BoxCollaborationsManagerIntegrationTest.java new file mode 100644 index 0000000..31a0756 --- /dev/null +++ b/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/BoxCollaborationsManagerIntegrationTest.java @@ -0,0 +1,232 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.box; + +import java.io.FileNotFoundException; +import java.util.HashMap; +import java.util.Map; + +import com.box.sdk.BoxAPIConnection; +import com.box.sdk.BoxAPIException; +import com.box.sdk.BoxCollaboration; +import com.box.sdk.BoxFolder; +import com.box.sdk.BoxUser; +import com.box.sdk.CreateUserParams; + +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.box.api.BoxCollaborationsManager; +import org.apache.camel.component.box.internal.BoxApiCollection; +import org.apache.camel.component.box.internal.BoxCollaborationsManagerApiMethod; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test class for + * {@link BoxCollaborationsManager} APIs. + */ +public class BoxCollaborationsManagerIntegrationTest extends AbstractBoxTestSupport { + + private static final Logger LOG = LoggerFactory.getLogger(BoxCollaborationsManagerIntegrationTest.class); + private static final String PATH_PREFIX = BoxApiCollection.getCollection() + .getApiName(BoxCollaborationsManagerApiMethod.class).getName(); + private static final String CAMEL_TEST_FOLDER = "CamelTestFolder"; + private static final String CAMEL_TEST_COLLABORATOR_EMAIL = "[email protected]"; + private static final String CAMEL_TEST_COLLABORATOR_NAME = "cameltest"; + + private BoxFolder testFolder; + private BoxCollaboration testCollaboration; + + @Test + public void testAddFolderCollaborationByEmail() throws Exception { + // delete collaborator created by setupTest + deleteTestCollaborator(); + + final Map<String, Object> headers = new HashMap<String, Object>(); + // parameter type is String + headers.put("CamelBox.folderId", testFolder.getID()); + // parameter type is String + headers.put("CamelBox.email", CAMEL_TEST_COLLABORATOR_EMAIL); + // parameter type is com.box.sdk.BoxCollaboration.Role + headers.put("CamelBox.role", BoxCollaboration.Role.EDITOR); + + final com.box.sdk.BoxCollaboration result = requestBodyAndHeaders("direct://ADDFOLDERCOLLABORATIONBYEMAIL", + testFolder.getID(), headers); + + assertNotNull("addFolderCollaboration result", result); + LOG.debug("addFolderCollaboration: " + result); + } + + @Test + public void testAddFolderCollaboration() throws Exception { + // delete collaborator created by setupTest + deleteTestCollaborator(); + BoxUser user = null; + try { + // create test collaborator + CreateUserParams params = new CreateUserParams(); + params.setSpaceAmount(1073741824); // 1 GB + user = BoxUser.createAppUser(getConnection(), CAMEL_TEST_COLLABORATOR_NAME, params).getResource(); + + final Map<String, Object> headers = new HashMap<String, Object>(); + // parameter type is String + headers.put("CamelBox.folderId", testFolder.getID()); + // parameter type is String + headers.put("CamelBox.collaborator", user); + // parameter type is com.box.sdk.BoxCollaboration.Role + headers.put("CamelBox.role", BoxCollaboration.Role.EDITOR); + + final com.box.sdk.BoxCollaboration result = requestBodyAndHeaders("direct://ADDFOLDERCOLLABORATION", + testFolder.getID(), headers); + assertNotNull("addFolderCollaboration result", result); + LOG.debug("addFolderCollaboration: " + result); + } catch (BoxAPIException e) { + throw new RuntimeException( + String.format("Box API returned the error code %d\n\n%s", e.getResponseCode(), e.getResponse()), e); + } finally { + if (user != null) { + user.delete(false, true); + } + } + } + + @Test + public void testGetCollaborationInfo() throws Exception { + // using String message body for single parameter "collaborationId" + final com.box.sdk.BoxCollaboration.Info result = requestBody("direct://GETCOLLABORATIONINFO", + testCollaboration.getID()); + + assertNotNull("getCollaborationInfo result", result); + LOG.debug("getCollaborationInfo: " + result); + } + + @Test + public void testGetFolderCollaborations() throws Exception { + // using String message body for single parameter "folderId" + @SuppressWarnings("rawtypes") + final java.util.Collection result = requestBody("direct://GETFOLDERCOLLABORATIONS", testFolder.getID()); + + assertNotNull("getFolderCollaborations result", result); + LOG.debug("getFolderCollaborations: " + result); + } + + @SuppressWarnings("rawtypes") + @Test + public void testGetPendingCollaborations() throws Exception { + final java.util.Collection result = requestBody("direct://GETPENDINGCOLLABORATIONS", null); + + assertNotNull("getPendingCollaborations result", result); + LOG.debug("getPendingCollaborations: " + result); + } + + @Test + public void testUpdateCollaborationInfo() throws Exception { + final Map<String, Object> headers = new HashMap<String, Object>(); + // parameter type is String + headers.put("CamelBox.collaborationId", testCollaboration.getID()); + // parameter type is com.box.sdk.BoxCollaboration.Info + + BoxCollaboration.Info info = testCollaboration.getInfo(); + info.setRole(BoxCollaboration.Role.PREVIEWER); + headers.put("CamelBox.info", info); + + final com.box.sdk.BoxCollaboration result = requestBodyAndHeaders("direct://UPDATECOLLABORATIONINFO", null, + headers); + + assertNotNull("updateCollaborationInfo result", result); + assertNotNull("updateCollaborationInfo info", result.getInfo()); + assertEquals("updateCollaborationInfo info", BoxCollaboration.Role.PREVIEWER, result.getInfo().getRole()); + LOG.debug("updateCollaborationInfo: " + result); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + public void configure() { + + // test route for addFolderCollaboration + from("direct://ADDFOLDERCOLLABORATIONBYEMAIL") + .to("box://" + PATH_PREFIX + "/addFolderCollaborationByEmail"); + + // test route for addFolderCollaboration + from("direct://ADDFOLDERCOLLABORATION").to("box://" + PATH_PREFIX + "/addFolderCollaboration"); + + // test route for deleteCollaboration + from("direct://DELETECOLLABORATION") + .to("box://" + PATH_PREFIX + "/deleteCollaboration?inBody=collaborationId"); + + // test route for getCollaborationInfo + from("direct://GETCOLLABORATIONINFO") + .to("box://" + PATH_PREFIX + "/getCollaborationInfo?inBody=collaborationId"); + + // test route for getFolderCollaborations + from("direct://GETFOLDERCOLLABORATIONS") + .to("box://" + PATH_PREFIX + "/getFolderCollaborations?inBody=folderId"); + + // test route for getPendingCollaborations + from("direct://GETPENDINGCOLLABORATIONS").to("box://" + PATH_PREFIX + "/getPendingCollaborations"); + + // test route for updateCollaborationInfo + from("direct://UPDATECOLLABORATIONINFO").to("box://" + PATH_PREFIX + "/updateCollaborationInfo"); + + } + }; + } + + @Before + public void setupTest() throws Exception { + createTestFolder(); + createTestCollaborator(); + } + + @After + public void teardownTest() { + deleteTestCollaborator(); + deleteTestFolder(); + } + + public BoxAPIConnection getConnection() { + BoxEndpoint endpoint = (BoxEndpoint) context() + .getEndpoint("box://" + PATH_PREFIX + "/addFolderCollaboration"); + return endpoint.getBoxConnection(); + } + + private void createTestFolder() throws FileNotFoundException { + BoxFolder rootFolder = BoxFolder.getRootFolder(getConnection()); + testFolder = rootFolder.createFolder(CAMEL_TEST_FOLDER).getResource(); + } + + private void deleteTestFolder() { + testFolder.delete(true); + testFolder = null; + } + + private void createTestCollaborator() { + testCollaboration = testFolder.collaborate(CAMEL_TEST_COLLABORATOR_EMAIL, BoxCollaboration.Role.EDITOR) + .getResource(); + } + + private void deleteTestCollaborator() { + if (testCollaboration != null) { + testCollaboration.delete(); + testCollaboration = null; + } + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/db0ca734/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/BoxCommentsManagerIntegrationTest.java ---------------------------------------------------------------------- diff --git a/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/BoxCommentsManagerIntegrationTest.java b/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/BoxCommentsManagerIntegrationTest.java new file mode 100644 index 0000000..8f9e050 --- /dev/null +++ b/components/camel-box/camel-box-component/src/test/java/org/apache/camel/component/box/BoxCommentsManagerIntegrationTest.java @@ -0,0 +1,202 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.box; + +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.box.sdk.BoxAPIConnection; +import com.box.sdk.BoxComment; +import com.box.sdk.BoxFile; +import com.box.sdk.BoxFolder; + +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.box.api.BoxCommentsManager; +import org.apache.camel.component.box.internal.BoxApiCollection; +import org.apache.camel.component.box.internal.BoxCommentsManagerApiMethod; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test class for + * {@link BoxCommentsManager} APIs. + */ +public class BoxCommentsManagerIntegrationTest extends AbstractBoxTestSupport { + + private static final Logger LOG = LoggerFactory.getLogger(BoxCommentsManagerIntegrationTest.class); + private static final String PATH_PREFIX = BoxApiCollection.getCollection() + .getApiName(BoxCommentsManagerApiMethod.class).getName(); + private static final String CAMEL_TEST_FILE = "/CamelTestFile.txt"; + private static final String CAMEL_TEST_FILE_NAME = "CamelTestFile.txt"; + private static final String CAMEL_TEST_FILE_COMMENT = "CamelTestFile comment."; + private static final String CAMEL_TEST_FILE_CHANGED_COMMENT = "CamelTestFile changed comment."; + private static final String CAMEL_TEST_FILE_REPLY_COMMENT = "CamelTestFile changed comment."; + + private BoxFile testFile; + + @Test + public void testAddFileComment() throws Exception { + final Map<String, Object> headers = new HashMap<String, Object>(); + // parameter type is String + headers.put("CamelBox.fileId", testFile.getID()); + // parameter type is String + headers.put("CamelBox.message", CAMEL_TEST_FILE_COMMENT); + + final com.box.sdk.BoxFile result = requestBodyAndHeaders("direct://ADDFILECOMMENT", null, headers); + + assertNotNull("addFileComment result", result); + assertNotNull("addFileComment comments", result.getComments()); + assertTrue("changeCommentMessage comments size", result.getComments().size() > 0); + assertEquals("changeCommentMessage comment message", CAMEL_TEST_FILE_COMMENT, + result.getComments().get(0).getMessage()); + LOG.debug("addFileComment: " + result); + } + + @Test + public void testChangeCommentMessage() throws Exception { + + BoxComment.Info commentInfo = testFile.addComment(CAMEL_TEST_FILE_COMMENT); + + final Map<String, Object> headers = new HashMap<String, Object>(); + // parameter type is String + headers.put("CamelBox.commentId", commentInfo.getID()); + // parameter type is String + headers.put("CamelBox.message", CAMEL_TEST_FILE_CHANGED_COMMENT); + + final com.box.sdk.BoxComment result = requestBodyAndHeaders("direct://CHANGECOMMENTMESSAGE", null, headers); + + assertNotNull("changeCommentMessage result", result); + assertNotNull("changeCommentMessage message", result.getInfo().getMessage()); + assertEquals("changeCommentMessage message", CAMEL_TEST_FILE_CHANGED_COMMENT, result.getInfo().getMessage()); + LOG.debug("changeCommentMessage: " + result); + } + + @Test + public void testDeleteComment() throws Exception { + BoxComment.Info commentInfo = testFile.addComment(CAMEL_TEST_FILE_COMMENT); + + // using String message body for single parameter "commentId" + requestBody("direct://DELETECOMMENT", commentInfo.getID()); + + List<BoxComment.Info> comments = testFile.getComments(); + assertNotNull("deleteComment comments", comments); + assertEquals("deleteComment comments empty", 0, comments.size()); + } + + @Test + public void testGetCommentInfo() throws Exception { + + BoxComment.Info commentInfo = testFile.addComment(CAMEL_TEST_FILE_COMMENT); + + // using String message body for single parameter "commentId" + final com.box.sdk.BoxComment.Info result = requestBody("direct://GETCOMMENTINFO", commentInfo.getID()); + + assertNotNull("getCommentInfo result", result); + assertEquals("getCommentInfo message", CAMEL_TEST_FILE_COMMENT, result.getMessage()); + LOG.debug("getCommentInfo: " + result); + } + + @Test + public void testGetFileComments() throws Exception { + testFile.addComment(CAMEL_TEST_FILE_COMMENT); + + // using String message body for single parameter "fileId" + @SuppressWarnings("rawtypes") + final java.util.List result = requestBody("direct://GETFILECOMMENTS", testFile.getID()); + + assertNotNull("getFileComments result", result); + assertEquals("getFileComments size", 1, result.size()); + LOG.debug("getFileComments: " + result); + } + + @Test + public void testReplyToComment() throws Exception { + + BoxComment.Info commentInfo = testFile.addComment(CAMEL_TEST_FILE_COMMENT); + + final Map<String, Object> headers = new HashMap<String, Object>(); + // parameter type is String + headers.put("CamelBox.commentId", commentInfo.getID()); + // parameter type is String + headers.put("CamelBox.message", CAMEL_TEST_FILE_REPLY_COMMENT); + + final com.box.sdk.BoxComment result = requestBodyAndHeaders("direct://REPLYTOCOMMENT", null, headers); + + assertNotNull("replyToComment result", result); + assertEquals("replyToComment result", CAMEL_TEST_FILE_REPLY_COMMENT, result.getInfo().getMessage()); + LOG.debug("replyToComment: " + result); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + public void configure() { + // test route for addFileComment + from("direct://ADDFILECOMMENT").to("box://" + PATH_PREFIX + "/addFileComment"); + + // test route for changeCommentMessage + from("direct://CHANGECOMMENTMESSAGE").to("box://" + PATH_PREFIX + "/changeCommentMessage"); + + // test route for deleteComment + from("direct://DELETECOMMENT").to("box://" + PATH_PREFIX + "/deleteComment?inBody=commentId"); + + // test route for getCommentInfo + from("direct://GETCOMMENTINFO").to("box://" + PATH_PREFIX + "/getCommentInfo?inBody=commentId"); + + // test route for getFileComments + from("direct://GETFILECOMMENTS").to("box://" + PATH_PREFIX + "/getFileComments?inBody=fileId"); + + // test route for replyToComment + from("direct://REPLYTOCOMMENT").to("box://" + PATH_PREFIX + "/replyToComment"); + + } + }; + } + + @Before + public void setupTest() throws Exception { + createTestFile(); + } + + @After + public void teardownTest() { + deleteTestFile(); + } + + public BoxAPIConnection getConnection() { + BoxEndpoint endpoint = (BoxEndpoint) context().getEndpoint("box://" + PATH_PREFIX + "/addFileComment"); + return endpoint.getBoxConnection(); + } + + private void createTestFile() throws FileNotFoundException { + BoxFolder rootFolder = BoxFolder.getRootFolder(getConnection()); + InputStream stream = getClass().getResourceAsStream(CAMEL_TEST_FILE); + testFile = rootFolder.uploadFile(stream, CAMEL_TEST_FILE_NAME).getResource(); + } + + private void deleteTestFile() { + testFile.delete(); + testFile = null; + } + +}
