http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/main/java/org/apache/camel/component/box/BoxProducer.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/java/org/apache/camel/component/box/BoxProducer.java b/components/camel-box/src/main/java/org/apache/camel/component/box/BoxProducer.java deleted file mode 100644 index 95aaae5..0000000 --- a/components/camel-box/src/main/java/org/apache/camel/component/box/BoxProducer.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 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/b51280c8/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxClientHelper.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxClientHelper.java b/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxClientHelper.java deleted file mode 100644 index b526fa7..0000000 --- a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxClientHelper.java +++ /dev/null @@ -1,274 +0,0 @@ -/** - * 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.InetSocketAddress; -import java.net.Proxy; -import java.net.Socket; -import java.security.GeneralSecurityException; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import javax.net.ssl.SSLContext; - -import com.box.boxjavalibv2.BoxClient; -import com.box.boxjavalibv2.BoxConnectionManagerBuilder; -import com.box.boxjavalibv2.BoxRESTClient; -import com.box.boxjavalibv2.authorization.IAuthFlowUI; -import com.box.boxjavalibv2.authorization.IAuthSecureStorage; -import com.box.restclientv2.IBoxRESTClient; -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.HttpHost; -import org.apache.http.client.HttpClient; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.params.ConnRoutePNames; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Helper class to work with {@link BoxClient}. - */ -public final class BoxClientHelper { - - private static final Logger LOG = LoggerFactory.getLogger(BoxClientHelper.class); - - private BoxClientHelper() { - } - - // create BoxClient using provided configuration - @SuppressWarnings("deprecation") - public static CachedBoxClient createBoxClient(final BoxConfiguration configuration) { - - final String clientId = configuration.getClientId(); - final String clientSecret = configuration.getClientSecret(); - - final IAuthSecureStorage authSecureStorage = configuration.getAuthSecureStorage(); - final String userName = configuration.getUserName(); - final String userPassword = configuration.getUserPassword(); - - if ((authSecureStorage == null && ObjectHelper.isEmpty(userPassword)) - || ObjectHelper.isEmpty(userName) || ObjectHelper.isEmpty(clientId) || ObjectHelper.isEmpty(clientSecret)) { - throw new IllegalArgumentException( - "Missing one or more required properties " - + "clientId, clientSecret, userName and either authSecureStorage or userPassword"); - } - LOG.debug("Creating BoxClient for login:{}, client_id:{} ...", userName, clientId); - - // if set, use configured connection manager builder - final BoxConnectionManagerBuilder connectionManagerBuilder = configuration.getConnectionManagerBuilder(); - final BoxConnectionManagerBuilder connectionManager = connectionManagerBuilder != null - ? connectionManagerBuilder : new BoxConnectionManagerBuilder(); - - // create REST client for BoxClient - final ClientConnectionManager[] clientConnectionManager = new ClientConnectionManager[1]; - final IBoxRESTClient restClient = new BoxRESTClient(connectionManager.build()) { - @Override - public HttpClient getRawHttpClient() { - final HttpClient httpClient = super.getRawHttpClient(); - clientConnectionManager[0] = httpClient.getConnectionManager(); - final SchemeRegistry schemeRegistry = clientConnectionManager[0].getSchemeRegistry(); - SSLContextParameters sslContextParameters = configuration.getSslContextParameters(); - if (sslContextParameters == null) { - sslContextParameters = new SSLContextParameters(); - } - final Map<String, Object> configParams = configuration.getHttpParams(); - boolean useSocksProxy = false; - HttpHost proxyHost = null; - if (configParams != null && !configParams.isEmpty()) { - final Boolean socksProxy = (Boolean) configParams.get("http.route.socks-proxy"); - if (socksProxy != null && socksProxy) { - useSocksProxy = true; - proxyHost = (HttpHost) configParams.get(ConnRoutePNames.DEFAULT_PROXY); - } - // set custom HTTP params - LOG.debug("Setting {} HTTP Params", configParams.size()); - - final HttpParams httpParams = httpClient.getParams(); - for (Map.Entry<String, Object> param : configParams.entrySet()) { - // don't add proxy params if socks - if (!(useSocksProxy && (param.getKey().equals("http.route.socks-proxy") || param.getKey().equals(ConnRoutePNames.DEFAULT_PROXY)))) { - httpParams.setParameter(param.getKey(), param.getValue()); - } - } - - } - SSLContext sslContext; - try { - sslContext = sslContextParameters.createSSLContext(); - } catch (IOException e) { - throw ObjectHelper.wrapRuntimeCamelException(e); - } catch (GeneralSecurityException e) { - throw ObjectHelper.wrapRuntimeCamelException(e); - } - SSLSocketFactory socketFactory; - if (useSocksProxy) { - socketFactory = new SocksSSLSocketFactory(sslContext, proxyHost); - } else { - socketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - } - schemeRegistry.register(new Scheme("https", socketFactory, 443)); - - return httpClient; - } - }; - final BoxClient boxClient = new BoxClient(clientId, clientSecret, null, null, - restClient, configuration.getBoxConfig()); - - // enable OAuth auto-refresh - boxClient.setAutoRefreshOAuth(true); - - // wrap the configured storage in a caching storage - final CachingSecureStorage storage = new CachingSecureStorage(authSecureStorage); - - // set up a listener to notify secure storage and user provided listener, store it in configuration! - final OAuthHelperListener listener = new OAuthHelperListener(storage, configuration.getRefreshListener()); - boxClient.addOAuthRefreshListener(listener); - - final CachedBoxClient cachedBoxClient = new CachedBoxClient(boxClient, userName, clientId, storage, listener, clientConnectionManager); - LOG.debug("BoxClient created {}", cachedBoxClient); - return cachedBoxClient; - } - - public static void getOAuthToken(BoxConfiguration configuration, CachedBoxClient cachedBoxClient) throws Exception { - - final BoxClient boxClient = cachedBoxClient.getBoxClient(); - synchronized (boxClient) { - if (boxClient.isAuthenticated()) { - return; - } - - LOG.debug("Getting OAuth token for {}...", cachedBoxClient); - - final IAuthSecureStorage authSecureStorage = cachedBoxClient.getSecureStorage(); - if (authSecureStorage != null && authSecureStorage.getAuth() != null) { - - LOG.debug("Using secure storage for {}", cachedBoxClient); - // authenticate using stored refresh token - boxClient.authenticateFromSecureStorage(authSecureStorage); - } else { - - LOG.debug("Using OAuth {}", cachedBoxClient); - // authorize App for user, and create OAuth token with refresh token - final IAuthFlowUI authFlowUI = new LoginAuthFlowUI(configuration, boxClient); - final CountDownLatch latch = new CountDownLatch(1); - final LoginAuthFlowListener listener = new LoginAuthFlowListener(latch); - boxClient.authenticate(authFlowUI, true, listener); - - // wait for login to finish or timeout - if (!latch.await(configuration.getLoginTimeout(), TimeUnit.SECONDS)) { - if (!boxClient.isAuthenticated()) { - throw new RuntimeCamelException(String.format("Login timeout for %s", cachedBoxClient)); - } - } - final Exception ex = listener.getException(); - if (ex != null) { - throw new RuntimeCamelException(String.format("Login error for %s: %s", - cachedBoxClient, ex.getMessage()), ex); - } - } - - LOG.debug("OAuth token created for {}", cachedBoxClient); - // notify the cached client listener for the first time, since BoxClient doesn't!!! - cachedBoxClient.getListener().onRefresh(boxClient.getAuthData()); - } - } - - public static void closeIdleConnections(CachedBoxClient cachedBoxClient) { - @SuppressWarnings("deprecation") - final ClientConnectionManager connectionManager = cachedBoxClient.getClientConnectionManager(); - if (connectionManager != null) { - // close all idle connections - connectionManager.closeIdleConnections(1, TimeUnit.MILLISECONDS); - } - } - - public static void shutdownBoxClient(BoxConfiguration configuration, CachedBoxClient cachedBoxClient) throws Exception { - - final BoxClient boxClient = cachedBoxClient.getBoxClient(); - synchronized (boxClient) { - - LOG.debug("Shutting down {} ...", cachedBoxClient); - try { - // revoke token if requested - if (configuration.isRevokeOnShutdown()) { - revokeOAuthToken(configuration, cachedBoxClient); - } - } finally { - - boxClient.setConnectionOpen(false); - // close connections in the underlying HttpClient - @SuppressWarnings("deprecation") - final ClientConnectionManager connectionManager = cachedBoxClient.getClientConnectionManager(); - if (connectionManager != null) { - LOG.debug("Closing connections for {}", cachedBoxClient); - - connectionManager.shutdown(); - } else { - LOG.debug("ConnectionManager not created for {}", cachedBoxClient); - } - } - LOG.debug("Shutdown successful for {}", cachedBoxClient); - } - } - - private static void revokeOAuthToken(BoxConfiguration configuration, CachedBoxClient cachedBoxClient) throws Exception { - - final BoxClient boxClient = cachedBoxClient.getBoxClient(); - synchronized (boxClient) { - - if (boxClient.isAuthenticated()) { - - LOG.debug("Revoking OAuth refresh token for {}", cachedBoxClient); - - // revoke OAuth token - boxClient.getOAuthManager().revokeOAuth(boxClient.getAuthData().getAccessToken(), - configuration.getClientId(), configuration.getClientSecret()); - - // notify the OAuthListener of revoked token - cachedBoxClient.getListener().onRefresh(null); - // mark auth data revoked - boxClient.getOAuthDataController().setOAuthData(null); - } - } - } - - static class SocksSSLSocketFactory extends SSLSocketFactory { - HttpHost proxyHost; - - SocksSSLSocketFactory(SSLContext sslContext, HttpHost proxyHost) { - super(sslContext, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); - this.proxyHost = proxyHost; - } - - @Override - public Socket createSocket(final HttpContext context) throws IOException { - InetSocketAddress socksaddr = new InetSocketAddress(proxyHost.getHostName(), proxyHost.getPort()); - Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr); - return new Socket(proxy); - } - - } -} http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxConstants.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxConstants.java b/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxConstants.java deleted file mode 100644 index 49a4474..0000000 --- a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxConstants.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * 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."; - String NEXT_STREAM_POSITION_PROPERTY = PROPERTY_PREFIX + "nextStreamPosition"; - String CHUNK_SIZE_PROPERTY = PROPERTY_PREFIX + "chunkSize"; - - // thread profile name for this component - String THREAD_PROFILE_NAME = "CamelBox"; -} http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxPropertiesHelper.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxPropertiesHelper.java b/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxPropertiesHelper.java deleted file mode 100644 index ae9b4f6..0000000 --- a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/BoxPropertiesHelper.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 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/b51280c8/components/camel-box/src/main/java/org/apache/camel/component/box/internal/CachedBoxClient.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/CachedBoxClient.java b/components/camel-box/src/main/java/org/apache/camel/component/box/internal/CachedBoxClient.java deleted file mode 100644 index 2a806ba..0000000 --- a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/CachedBoxClient.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * 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 com.box.boxjavalibv2.BoxClient; -import org.apache.http.conn.ClientConnectionManager; - -public class CachedBoxClient { - - private final BoxClient boxClient; - - private final String login; - - private final String clientId; - - private final CachingSecureStorage secureStorage; - - private final OAuthHelperListener listener; - - @SuppressWarnings("deprecation") - private final ClientConnectionManager[] clientConnectionManager; - - @SuppressWarnings("deprecation") - public CachedBoxClient(BoxClient boxClient, String login, String clientId, CachingSecureStorage secureStorage, - OAuthHelperListener listener, ClientConnectionManager[] clientConnectionManager) { - this.boxClient = boxClient; - this.login = login; - this.clientId = clientId; - this.secureStorage = secureStorage; - this.listener = listener; - if (clientConnectionManager == null || clientConnectionManager.length != 1) { - throw new IllegalArgumentException("clientConnectionManager must be an array of length 1"); - } - this.clientConnectionManager = clientConnectionManager; - } - - public BoxClient getBoxClient() { - return boxClient; - } - - public CachingSecureStorage getSecureStorage() { - return secureStorage; - } - - public OAuthHelperListener getListener() { - return listener; - } - - @SuppressWarnings("deprecation") - public ClientConnectionManager getClientConnectionManager() { - return clientConnectionManager[0]; - } - - @Override - public String toString() { - return String.format("{login:%s, client_id:%s}", login, clientId); - } -} http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/main/java/org/apache/camel/component/box/internal/CachingSecureStorage.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/CachingSecureStorage.java b/components/camel-box/src/main/java/org/apache/camel/component/box/internal/CachingSecureStorage.java deleted file mode 100644 index adb606c..0000000 --- a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/CachingSecureStorage.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 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 com.box.boxjavalibv2.authorization.IAuthSecureStorage; -import com.box.boxjavalibv2.dao.IAuthData; - -/** - * A caching {@link IAuthSecureStorage} that also delegates to another {@link IAuthSecureStorage}. - */ -public class CachingSecureStorage implements IAuthSecureStorage { - - private final IAuthSecureStorage secureStorage; - - private IAuthData auth; - - public CachingSecureStorage(IAuthSecureStorage secureStorage) { - this.secureStorage = secureStorage; - } - - @Override - public void saveAuth(IAuthData newAuth) { - this.auth = newAuth; - if (secureStorage != null) { - secureStorage.saveAuth(newAuth); - } - } - - @Override - public IAuthData getAuth() { - if (auth == null && secureStorage != null) { - auth = secureStorage.getAuth(); - } - return auth; - } -} http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/main/java/org/apache/camel/component/box/internal/EventCallback.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/EventCallback.java b/components/camel-box/src/main/java/org/apache/camel/component/box/internal/EventCallback.java deleted file mode 100644 index f217bf6..0000000 --- a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/EventCallback.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 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 com.box.boxjavalibv2.dao.BoxEventCollection; - -/** - * Callback interface to handle BoxEvents received from long polling. - */ -public interface EventCallback { - - void onEvent(BoxEventCollection events) throws Exception; - - void onException(Exception e); -} http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LoginAuthFlowListener.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LoginAuthFlowListener.java b/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LoginAuthFlowListener.java deleted file mode 100644 index 3b0a25d..0000000 --- a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LoginAuthFlowListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * 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.util.concurrent.CountDownLatch; - -import com.box.boxjavalibv2.authorization.IAuthEvent; -import com.box.boxjavalibv2.authorization.IAuthFlowListener; -import com.box.boxjavalibv2.authorization.IAuthFlowMessage; -import com.box.boxjavalibv2.events.OAuthEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** -* Implementation of {@link IAuthFlowListener} to get success or failure status of OAuth flow. -*/ -public final class LoginAuthFlowListener implements IAuthFlowListener { - - private static final Logger LOG = LoggerFactory.getLogger(LoginAuthFlowListener.class); - - private final Exception[] exception = new Exception[1]; - private final CountDownLatch latch; - - public LoginAuthFlowListener(CountDownLatch latch) { - this.latch = latch; - } - - @Override - public void onAuthFlowMessage(IAuthFlowMessage message) { - // do nothing - } - - @Override - public void onAuthFlowException(Exception e) { - // record exception - exception[0] = e; - LOG.warn(String.format("OAuth exception: %s", e.getMessage()), e); - latch.countDown(); - } - - @Override - public void onAuthFlowEvent(IAuthEvent state, IAuthFlowMessage message) { - // check success - if (state == OAuthEvent.OAUTH_CREATED) { - LOG.debug("OAuth succeeded"); - latch.countDown(); - } - } - - public Exception getException() { - return exception[0]; - } -} http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LoginAuthFlowUI.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LoginAuthFlowUI.java b/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LoginAuthFlowUI.java deleted file mode 100644 index 778db59..0000000 --- a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LoginAuthFlowUI.java +++ /dev/null @@ -1,225 +0,0 @@ -/** - * 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.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.boxjavalibv2.BoxClient; -import com.box.boxjavalibv2.authorization.IAuthFlowListener; -import com.box.boxjavalibv2.authorization.IAuthFlowUI; -import com.box.boxjavalibv2.authorization.OAuthDataMessage; -import com.box.boxjavalibv2.authorization.OAuthWebViewData; -import com.box.boxjavalibv2.dao.BoxOAuthToken; -import com.box.boxjavalibv2.events.OAuthEvent; -import com.box.boxjavalibv2.resourcemanagers.IBoxOAuthManager; -import com.gargoylesoftware.htmlunit.BrowserVersion; -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.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.apache.http.conn.params.ConnRoutePNames; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** -* HtmlUnit based OAuth2 implementation of {@link IAuthFlowUI} -*/ -public final class LoginAuthFlowUI implements IAuthFlowUI { - - private static final Logger LOG = LoggerFactory.getLogger(LoginAuthFlowUI.class); - private static final Pattern QUERY_PARAM_PATTERN = Pattern.compile("&?([^=]+)=([^&]+)"); - - private final BoxConfiguration configuration; - private final BoxClient boxClient; - - public LoginAuthFlowUI(BoxConfiguration configuration, BoxClient boxClient) { - this.configuration = configuration; - this.boxClient = boxClient; - } - - @SuppressWarnings("deprecation") - @Override - public void authenticate(IAuthFlowListener listener) { - - // TODO run this on an Executor to make it async - - // create HtmlUnit client - final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_38); - 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(); - options.setSSLClientProtocols(sslContext.createSSLEngine().getEnabledProtocols()); - } catch (GeneralSecurityException e) { - throw ObjectHelper.wrapRuntimeCamelException(e); - } catch (IOException e) { - throw ObjectHelper.wrapRuntimeCamelException(e); - } - - // 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(ConnRoutePNames.DEFAULT_PROXY) != null) { - final HttpHost proxyHost = (HttpHost) httpParams.get(ConnRoutePNames.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 { - final String csrfId = String.valueOf(new SecureRandom().nextLong()); - - OAuthWebViewData viewData = new OAuthWebViewData(boxClient.getOAuthDataController()); - viewData.setOptionalState(String.valueOf(csrfId)); - final HtmlPage authPage = webClient.getPage(viewData.buildUrl().toString()); - - // 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 (!csrfId.equals(state)) { - final SecurityException e = new SecurityException("Invalid CSRF code!"); - listener.onAuthFlowException(e); - } else { - - // get authorization code - final String authorizationCode = params.get("code"); - - // get OAuth token - final IBoxOAuthManager oAuthManager = boxClient.getOAuthManager(); - final BoxOAuthToken oAuthToken = oAuthManager.createOAuth(authorizationCode, - configuration.getClientId(), configuration.getClientSecret(), null); - - // send initial token to BoxClient and this.listener - final OAuthDataMessage authDataMessage = new OAuthDataMessage(oAuthToken, - boxClient.getJSONParser(), boxClient.getResourceHub()); - listener.onAuthFlowEvent(OAuthEvent.OAUTH_CREATED, authDataMessage); - } - - } catch (Exception e) { - // forward login exceptions to listener - listener.onAuthFlowException(e); - } - } - - @Override - public void addAuthFlowListener(IAuthFlowListener listener) { - throw new UnsupportedOperationException("addAuthFlowListener"); - } - - @Override - public void initializeAuthFlow(Object applicationContext, String clientId, String clientSecret) { - // unknown usage - throw new UnsupportedOperationException("initializeAuthFlow"); - } - - @Override - public void initializeAuthFlow(Object applicationContext, String clientId, String clientSecret, - String redirectUrl) { - // unknown usage - throw new UnsupportedOperationException("initializeAuthFlow"); - } - - @Override - public void initializeAuthFlow(Object applicationContext, String clientId, String clientSecret, - String redirectUrl, BoxClient boxClient) { - // unknown usage - throw new UnsupportedOperationException("initializeAuthFlow"); - } -} http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LongPollingEventsManager.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LongPollingEventsManager.java b/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LongPollingEventsManager.java deleted file mode 100644 index 37611b7..0000000 --- a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/LongPollingEventsManager.java +++ /dev/null @@ -1,301 +0,0 @@ -/** - * 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.net.SocketException; -import java.net.SocketTimeoutException; -import java.util.ArrayList; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -import com.box.boxjavalibv2.dao.BoxCollection; -import com.box.boxjavalibv2.dao.BoxEventCollection; -import com.box.boxjavalibv2.dao.BoxRealTimeServer; -import com.box.boxjavalibv2.dao.BoxTypedObject; -import com.box.boxjavalibv2.exceptions.AuthFatalFailureException; -import com.box.boxjavalibv2.exceptions.BoxServerException; -import com.box.boxjavalibv2.requests.requestobjects.BoxEventRequestObject; -import com.box.boxjavalibv2.resourcemanagers.IBoxEventsManager; -import com.box.restclientv2.exceptions.BoxRestException; -import com.box.restclientv2.exceptions.BoxSDKException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.camel.RuntimeCamelException; -import org.apache.camel.util.ObjectHelper; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.StatusLine; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Manager for monitoring events using long polling. - */ -@SuppressWarnings("deprecation") -public class LongPollingEventsManager { - - private static final Logger LOG = LoggerFactory.getLogger(LongPollingEventsManager.class); - private static final String RETRY_TIMEOUT = "retry_timeout"; - private static final String MAX_RETRIES = "max_retries"; - private static final String MESSAGE = "message"; - private static final String NEW_CHANGE = "new_change"; - private static final String RECONNECT = "reconnect"; - private static final String OUT_OF_DATE = "out_of_date"; - - private final CachedBoxClient cachedBoxClient; - private final ExecutorService executorService; - private final BasicHttpParams httpParams; - - private HttpClient httpClient; - private Future<?> pollFuture; - private HttpGet httpGet; - private boolean done; - - public LongPollingEventsManager(CachedBoxClient boxClient, - Map<String, Object> httpParams, ExecutorService executorService) { - - this.cachedBoxClient = boxClient; - this.executorService = executorService; - - this.httpParams = new BasicHttpParams(); - HttpConnectionParams.setSoKeepalive(this.httpParams, true); - - if (httpParams != null) { - for (Map.Entry<String, Object> entry : httpParams.entrySet()) { - this.httpParams.setParameter(entry.getKey(), entry.getValue()); - } - } - } - - public void poll(long streamPosition, final String streamType, final int limit, final EventCallback callback) - throws BoxServerException, AuthFatalFailureException, BoxRestException { - - // get BoxClient Event Manager - final IBoxEventsManager eventsManager = cachedBoxClient.getBoxClient().getEventsManager(); - - // get current stream position if requested - if (BoxEventRequestObject.STREAM_POSITION_NOW == streamPosition) { - streamPosition = getCurrentStreamPosition(eventsManager, streamPosition); - } - - // validate parameters - ObjectHelper.notNull(streamPosition, "streamPosition"); - ObjectHelper.notEmpty(streamType, "streamType"); - ObjectHelper.notNull(callback, "eventCallback"); - - httpClient = new DefaultHttpClient(cachedBoxClient.getClientConnectionManager(), httpParams); - - // start polling thread - LOG.info("Started event polling thread for " + cachedBoxClient); - - final long startStreamPosition = streamPosition; - pollFuture = executorService.submit(new Runnable() { - @Override - public void run() { - - final ObjectMapper mapper = new ObjectMapper(); - - long currentStreamPosition = startStreamPosition; - BoxRealTimeServer realTimeServer = null; - - boolean retry = false; - int retries = 0; - int maxRetries = 1; - - while (!done) { - try { - // set to true if no exceptions thrown - retry = false; - - if (realTimeServer == null) { - - // get RTS URL - realTimeServer = getBoxRealTimeServer(currentStreamPosition, eventsManager); - - // update HTTP timeout - final int requestTimeout = Integer.parseInt( - realTimeServer.getExtraData(RETRY_TIMEOUT).toString()); - final HttpParams params = httpClient.getParams(); - HttpConnectionParams.setSoTimeout(params, requestTimeout * 1000); - - // update maxRetries - maxRetries = Integer.parseInt(realTimeServer.getExtraData(MAX_RETRIES).toString()); - } - - // create HTTP request for RTS - httpGet = getPollRequest(realTimeServer.getUrl(), currentStreamPosition); - - // execute RTS poll - HttpResponse httpResponse = null; - try { - httpResponse = httpClient.execute(httpGet, (HttpContext) null); - } catch (SocketTimeoutException e) { - LOG.debug("Poll timed out, retrying for " + cachedBoxClient); - } - - if (httpResponse != null) { - - // parse response - final StatusLine statusLine = httpResponse.getStatusLine(); - if (statusLine != null && statusLine.getStatusCode() == HttpStatus.SC_OK) { - final HttpEntity entity = httpResponse.getEntity(); - @SuppressWarnings("unchecked") - Map<String, String> rtsResponse = mapper.readValue(entity.getContent(), Map.class); - - final String message = rtsResponse.get(MESSAGE); - if (NEW_CHANGE.equals(message)) { - - // get events - final BoxEventRequestObject requestObject = - BoxEventRequestObject.getEventsRequestObject(currentStreamPosition); - requestObject.setStreamType(streamType); - requestObject.setLimit(limit); - final BoxEventCollection events = eventsManager.getEvents(requestObject); - - // notify callback - callback.onEvent(events); - - // update stream position - currentStreamPosition = events.getNextStreamPosition(); - - } else if (RECONNECT.equals(message) || MAX_RETRIES.equals(message)) { - LOG.debug("Long poll reconnect for " + cachedBoxClient); - realTimeServer = null; - } else if (OUT_OF_DATE.equals(message)) { - // update currentStreamPosition - LOG.debug("Long poll out of date for " + cachedBoxClient); - currentStreamPosition = getCurrentStreamPosition(eventsManager, - BoxEventRequestObject.STREAM_POSITION_NOW); - realTimeServer = null; - } else { - throw new RuntimeCamelException("Unknown poll response " + message); - } - } else { - String msg = "Unknown error"; - if (statusLine != null) { - msg = String.format("Error polling events for %s: code=%s, message=%s", - cachedBoxClient, statusLine.getStatusCode(), statusLine.getReasonPhrase()); - } - throw new RuntimeCamelException(msg); - } - } - - // keep polling - retry = true; - - } catch (InterruptedException e) { - LOG.debug("Interrupted event polling thread for {}, exiting...", cachedBoxClient); - } catch (BoxSDKException e) { - callback.onException(e); - } catch (RuntimeCamelException e) { - callback.onException(e); - } catch (SocketException e) { - // TODO handle connection aborts!!! - LOG.debug("Socket exception while event polling for {}", cachedBoxClient); - retry = true; - realTimeServer = null; - } catch (Exception e) { - callback.onException(new RuntimeCamelException("Error while polling for " - + cachedBoxClient + ": " + e.getMessage(), e)); - } finally { - // are we done yet? - if (!retry) { - done = true; - } else { - if (realTimeServer != null - && (++retries > maxRetries)) { - // make another option call - realTimeServer = null; - } - } - } - } - LOG.info("Stopped event polling thread for " + cachedBoxClient); - } - }); - } - - private long getCurrentStreamPosition(IBoxEventsManager eventsManager, long streamPosition) - throws BoxRestException, BoxServerException, AuthFatalFailureException { - - final BoxEventRequestObject requestObject = - BoxEventRequestObject.getEventsRequestObject(streamPosition); - final BoxEventCollection events = eventsManager.getEvents(requestObject); - streamPosition = events.getNextStreamPosition(); - return streamPosition; - } - - public void stopPolling() throws Exception { - if (!done) { - - // done polling - done = true; - - // make sure an HTTP GET is not in progress - if (httpGet != null && !httpGet.isAborted()) { - httpGet.abort(); - } - - // cancel polling thread - if (pollFuture.cancel(true)) { - LOG.info("Stopped event polling for " + cachedBoxClient); - } else { - LOG.warn("Unable to stop event polling for " + cachedBoxClient); - } - - httpClient = null; - pollFuture = null; - } - } - - private BoxRealTimeServer getBoxRealTimeServer(long currentStreamPosition, IBoxEventsManager eventsManager) - throws BoxRestException, BoxServerException, AuthFatalFailureException { - - final BoxEventRequestObject optionsRequest = - BoxEventRequestObject.getEventsRequestObject(currentStreamPosition); - - final BoxCollection eventOptions = eventsManager.getEventOptions(optionsRequest); - final ArrayList<BoxTypedObject> entries = eventOptions.getEntries(); - - // validate options - if (entries == null || entries.size() < 1 - || !(entries.get(0) instanceof BoxRealTimeServer)) { - - throw new RuntimeCamelException("No Real Time Server from event options for " + cachedBoxClient); - } - - return (BoxRealTimeServer) entries.get(0); - } - - private HttpGet getPollRequest(String url, long currentStreamPosition) throws AuthFatalFailureException { - - final HttpGet httpGet = new HttpGet(url + "&stream_position=" + currentStreamPosition); - final String accessToken = cachedBoxClient.getBoxClient().getAuthData().getAccessToken(); - httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken); - return httpGet; - } - -} http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/main/java/org/apache/camel/component/box/internal/OAuthHelperListener.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/OAuthHelperListener.java b/components/camel-box/src/main/java/org/apache/camel/component/box/internal/OAuthHelperListener.java deleted file mode 100644 index 591b0a4..0000000 --- a/components/camel-box/src/main/java/org/apache/camel/component/box/internal/OAuthHelperListener.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 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 com.box.boxjavalibv2.authorization.IAuthSecureStorage; -import com.box.boxjavalibv2.authorization.OAuthRefreshListener; -import com.box.boxjavalibv2.dao.IAuthData; - -/** -* Wrapper implementation of {@link OAuthRefreshListener} that - * delegates to an {@link IAuthSecureStorage} and another {@link OAuthRefreshListener}. -*/ -class OAuthHelperListener implements OAuthRefreshListener { - private final IAuthSecureStorage authSecureStorage; - private final OAuthRefreshListener configListener; - - private String refreshToken; - - OAuthHelperListener(IAuthSecureStorage authSecureStorage, OAuthRefreshListener configListener) { - this.authSecureStorage = authSecureStorage; - this.configListener = configListener; - - if (authSecureStorage != null && authSecureStorage.getAuth() != null) { - this.refreshToken = authSecureStorage.getAuth().getRefreshToken(); - } - } - - @Override - public void onRefresh(IAuthData newAuthData) { - - // look for refresh token update or revocation - if (authSecureStorage != null - && (newAuthData == null || !newAuthData.getRefreshToken().equals(refreshToken))) { - authSecureStorage.saveAuth(newAuthData); - } - if (configListener != null) { - configListener.onRefresh(newAuthData); - } - - // update cached refresh token - refreshToken = newAuthData != null ? newAuthData.getRefreshToken() : null; - } -} http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/main/resources/META-INF/LICENSE.txt ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/resources/META-INF/LICENSE.txt b/components/camel-box/src/main/resources/META-INF/LICENSE.txt deleted file mode 100644 index 6b0b127..0000000 --- a/components/camel-box/src/main/resources/META-INF/LICENSE.txt +++ /dev/null @@ -1,203 +0,0 @@ - - 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/b51280c8/components/camel-box/src/main/resources/META-INF/NOTICE.txt ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/resources/META-INF/NOTICE.txt b/components/camel-box/src/main/resources/META-INF/NOTICE.txt deleted file mode 100644 index 2e215bf..0000000 --- a/components/camel-box/src/main/resources/META-INF/NOTICE.txt +++ /dev/null @@ -1,11 +0,0 @@ - ========================================================================= - == 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/b51280c8/components/camel-box/src/main/resources/META-INF/services/org/apache/camel/TypeConverter ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/resources/META-INF/services/org/apache/camel/TypeConverter b/components/camel-box/src/main/resources/META-INF/services/org/apache/camel/TypeConverter deleted file mode 100644 index 3172b44..0000000 --- a/components/camel-box/src/main/resources/META-INF/services/org/apache/camel/TypeConverter +++ /dev/null @@ -1,17 +0,0 @@ -# -# 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. -# -org.apache.camel.component.box.BoxConverter http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/main/resources/META-INF/services/org/apache/camel/component/box ---------------------------------------------------------------------- diff --git a/components/camel-box/src/main/resources/META-INF/services/org/apache/camel/component/box b/components/camel-box/src/main/resources/META-INF/services/org/apache/camel/component/box deleted file mode 100644 index 43c4063..0000000 --- a/components/camel-box/src/main/resources/META-INF/services/org/apache/camel/component/box +++ /dev/null @@ -1,18 +0,0 @@ -# -# 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/b51280c8/components/camel-box/src/signatures/long-polling-events-manager.txt ---------------------------------------------------------------------- diff --git a/components/camel-box/src/signatures/long-polling-events-manager.txt b/components/camel-box/src/signatures/long-polling-events-manager.txt deleted file mode 100644 index 57ea578..0000000 --- a/components/camel-box/src/signatures/long-polling-events-manager.txt +++ /dev/null @@ -1 +0,0 @@ -void poll(long streamPosition, final String streamType, final int limit, final org.apache.camel.component.box.internal.EventCallback callback); \ No newline at end of file http://git-wip-us.apache.org/repos/asf/camel/blob/b51280c8/components/camel-box/src/test/java/org/apache/camel/component/box/AbstractBoxTestSupport.java ---------------------------------------------------------------------- diff --git a/components/camel-box/src/test/java/org/apache/camel/component/box/AbstractBoxTestSupport.java b/components/camel-box/src/test/java/org/apache/camel/component/box/AbstractBoxTestSupport.java deleted file mode 100644 index 7bcf809..0000000 --- a/components/camel-box/src/test/java/org/apache/camel/component/box/AbstractBoxTestSupport.java +++ /dev/null @@ -1,179 +0,0 @@ -/** - * 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.BufferedReader; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import com.box.boxjavalibv2.authorization.IAuthSecureStorage; -import com.box.boxjavalibv2.authorization.OAuthRefreshListener; -import com.box.boxjavalibv2.dao.BoxOAuthToken; -import com.box.boxjavalibv2.dao.IAuthData; -import com.box.boxjavalibv2.requests.requestobjects.BoxPagingRequestObject; -import org.apache.camel.CamelContext; -import org.apache.camel.CamelExecutionException; -import org.apache.camel.test.junit4.CamelTestSupport; -import org.apache.camel.util.IntrospectionSupport; -import org.apache.camel.util.ObjectHelper; -import org.junit.AfterClass; - -public abstract class AbstractBoxTestSupport extends CamelTestSupport { - - protected static final String CAMEL_TEST_TAG = "camel_was_here"; - protected static final String CAMEL_TEST_FILE = "CamelTestFile"; - protected static final BoxPagingRequestObject BOX_PAGING_REQUEST_OBJECT = BoxPagingRequestObject.pagingRequestObject(100, 0); - - protected static String testUserId; - protected static String testFolderId; - protected static String testFileId; - - private static final String LINE_SEPARATOR = System.getProperty("line.separator"); - private static final String TEST_OPTIONS_PROPERTIES = "/test-options.properties"; - private static final String REFRESH_TOKEN_PROPERTY = "refreshToken"; - - private static String refreshToken; - private static String propertyText; - - @Override - protected CamelContext createCamelContext() throws Exception { - - final InputStream in = getClass().getResourceAsStream(TEST_OPTIONS_PROPERTIES); - if (in == null) { - throw new IOException(TEST_OPTIONS_PROPERTIES + " could not be found"); - } - - final StringBuilder builder = new StringBuilder(); - final BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); - String line; - while ((line = reader.readLine()) != null) { - builder.append(line).append(LINE_SEPARATOR); - } - propertyText = builder.toString(); - - final Properties properties = new Properties(); - try { - properties.load(new StringReader(propertyText)); - } catch (IOException e) { - throw new IOException(String.format("%s could not be loaded: %s", TEST_OPTIONS_PROPERTIES, e.getMessage()), e); - } - - addSystemProperty("camel.box.userName", "userName", properties); - addSystemProperty("camel.box.userPassword", "userPassword", properties); - addSystemProperty("camel.box.clientId", "clientId", properties); - addSystemProperty("camel.box.clientSecret", "clientSecret", properties); - addSystemProperty("camel.box.refreshToken", "refreshToken", properties); - addSystemProperty("camel.box.testFolderId", "testFolderId", properties); - addSystemProperty("camel.box.testFileId", "testFileId", properties); - addSystemProperty("camel.box.testUserId", "testUserId", properties); - - // cache test properties - refreshToken = properties.getProperty(REFRESH_TOKEN_PROPERTY); - testFolderId = properties.getProperty("testFolderId"); - testFileId = properties.getProperty("testFileId"); - testUserId = properties.getProperty("testUserId"); - - 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); - configuration.setAuthSecureStorage(new IAuthSecureStorage() { - - @Override - public void saveAuth(IAuthData auth) { - if (auth == null) { - // revoked - refreshToken = ""; - } else { - // remember the refresh token to write back to test-options.properties - refreshToken = auth.getRefreshToken(); - } - } - - @Override - public IAuthData getAuth() { - if (ObjectHelper.isEmpty(refreshToken)) { - return null; - } else { - Map<String, Object> values = new HashMap<String, Object>(); - values.put(BoxOAuthToken.FIELD_REFRESH_TOKEN, refreshToken); - return new BoxOAuthToken(values); - } - } - }); - configuration.setRefreshListener(new OAuthRefreshListener() { - @Override - public void onRefresh(IAuthData newAuthData) { - log.debug("Refreshed OAuth data: " + ((newAuthData != null) ? newAuthData.getAccessToken() : null)); - } - }); - - // add BoxComponent to Camel context - final CamelContext context = super.createCamelContext(); - final BoxComponent component = new BoxComponent(context); - - component.setConfiguration(configuration); - context.addComponent("box", component); - - return context; - } - - private void addSystemProperty(String sourceName, String targetName, Properties properties) { - String value = System.getProperty(sourceName); - if (value != null && !value.trim().isEmpty()) { - properties.put(targetName, value); - } - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - CamelTestSupport.tearDownAfterClass(); - - // write the refresh token back to target/test-classes/test-options.properties - final URL resource = AbstractBoxTestSupport.class.getResource(TEST_OPTIONS_PROPERTIES); - final FileOutputStream out = new FileOutputStream(new File(resource.getPath())); - propertyText = propertyText.replaceAll(REFRESH_TOKEN_PROPERTY + "=\\S*", - REFRESH_TOKEN_PROPERTY + "=" + refreshToken); - out.write(propertyText.getBytes("UTF-8")); - out.close(); - } - - @Override - public boolean isCreateCamelContextPerClass() { - // only create the context once for this class - return true; - } - - protected <T> T requestBodyAndHeaders(String endpointUri, Object body, Map<String, Object> headers) throws CamelExecutionException { - return (T) template().requestBodyAndHeaders(endpointUri, body, headers); - } - - protected <T> T requestBody(String endpoint, Object body) throws CamelExecutionException { - return (T) template().requestBody(endpoint, body); - } -}