index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw | Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw/decorator/Activator.java | /**
* 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.cxf.dosgi.dsw.decorator;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Activator implements BundleActivator {
private static final Logger LOG = LoggerFactory.getLogger(Activator.class);
private ServiceDecoratorBundleListener bundleListener;
@Override
public void start(BundleContext context) {
ServiceDecoratorImpl serviceDecorator = new ServiceDecoratorImpl();
bundleListener = new ServiceDecoratorBundleListener(serviceDecorator);
context.addBundleListener(bundleListener);
context.registerService(ServiceDecorator.class.getName(), serviceDecorator, null);
}
@Override
public void stop(BundleContext context) {
LOG.debug("RemoteServiceAdmin Implementation is shutting down now");
if (bundleListener != null) {
context.removeBundleListener(bundleListener);
bundleListener = null;
}
}
}
| 1,000 |
0 | Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw | Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorBundleListener.java | /**
* 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.cxf.dosgi.dsw.decorator;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
public class ServiceDecoratorBundleListener implements BundleListener {
/**
*
*/
private final ServiceDecoratorImpl serviceDecorator;
/**
* @param serviceDecorator
*/
public ServiceDecoratorBundleListener(ServiceDecoratorImpl serviceDecorator) {
this.serviceDecorator = serviceDecorator;
}
@Override
public void bundleChanged(BundleEvent be) {
switch(be.getType()) {
case BundleEvent.STARTED:
this.serviceDecorator.addDecorations(be.getBundle());
break;
case BundleEvent.STOPPING:
this.serviceDecorator.removeDecorations(be.getBundle());
break;
default:
}
}
}
| 1,001 |
0 | Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw | Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw/decorator/DecorationParser.java | /**
* 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.cxf.dosgi.dsw.decorator;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.apache.cxf.xmlns.service_decoration._1_0.ServiceDecorationType;
import org.apache.cxf.xmlns.service_decoration._1_0.ServiceDecorationsType;
class DecorationParser {
private JAXBContext jaxbContext;
private Schema schema;
DecorationParser() {
try {
jaxbContext = JAXBContext.newInstance(ServiceDecorationsType.class.getPackage().getName(),
this.getClass().getClassLoader());
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
URL resource = getClass().getResource("/service-decoration.xsd");
schema = schemaFactory.newSchema(resource);
} catch (Exception e) {
throw new RuntimeException("Error loading decorations schema", e);
}
}
List<ServiceDecorationType> getDecorations(URL resourceURL) throws JAXBException, IOException {
if (resourceURL == null || !decorationType(resourceURL)) {
return new ArrayList<>();
}
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(schema);
InputStream is = resourceURL.openStream();
Source source = new StreamSource(is);
JAXBElement<ServiceDecorationsType> jaxb = unmarshaller.unmarshal(source, ServiceDecorationsType.class);
ServiceDecorationsType decorations = jaxb.getValue();
return decorations.getServiceDecoration();
}
private boolean decorationType(URL resourceURL) {
try {
InputStream is = resourceURL.openStream();
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(is);
reader.next();
String ns = reader.getNamespaceURI();
reader.close();
return ns.equals("http://cxf.apache.org/xmlns/service-decoration/1.0.0");
} catch (Exception e) {
return false;
}
}
}
| 1,002 |
0 | Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw | Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw/decorator/Rule.java | /**
* 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.cxf.dosgi.dsw.decorator;
import java.util.Map;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
public interface Rule {
/**
* When the ServiceReference passed in matches the rule's condition,
* set the additional properties in the target.
* @param sref The Service Reference to be checked.
* @param target Any additional properties are to be set in this map.
*/
void apply(ServiceReference<?> sref, Map<String, Object> target);
/**
* Returns the bundle that provided this rule.
* @return The Bundle where the Rule was defined.
*/
Bundle getBundle();
}
| 1,003 |
0 | Create_ds/cxf-dosgi/samples/ssl/ssl-intent/src/main/java/org/apache/cxf/dosgi/samples | Create_ds/cxf-dosgi/samples/ssl/ssl-intent/src/main/java/org/apache/cxf/dosgi/samples/ssl/SslIntent.java | /**
* 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.cxf.dosgi.samples.ssl;
import static javax.net.ssl.KeyManagerFactory.getDefaultAlgorithm;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.transport.http.HttpConduitConfig;
import org.apache.cxf.transport.http.HttpConduitFeature;
import org.osgi.service.component.annotations.Component;
/**
* Configures the client side conduit to trust the server certificate and authenticate by using
* a client certificate
*/
@Component //
(//
property = "org.apache.cxf.dosgi.IntentName=ssl" //
)
public class SslIntent implements Callable<List<Object>> {
private static final String CLIENT_PASSWORD = "password";
@Override
public List<Object> call() throws Exception {
HttpConduitFeature conduitFeature = new HttpConduitFeature();
HttpConduitConfig conduitConfig = new HttpConduitConfig();
TLSClientParameters tls = new TLSClientParameters();
String karafHome = System.getProperty("karaf.home");
tls.setKeyManagers(keyManager(keystore(karafHome + "/etc/keystores/client.jks", CLIENT_PASSWORD),
CLIENT_PASSWORD));
tls.setTrustManagers(trustManager(keystore(karafHome + "/etc/keystores/client.jks", CLIENT_PASSWORD)));
//tls.setTrustManagers(new TrustManager[]{new DefaultTrustManager()});
HostnameVerifier verifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
tls.setHostnameVerifier(verifier);
tls.setCertAlias("clientkey");
tls.setDisableCNCheck(true);
conduitConfig.setTlsClientParameters(tls);
conduitFeature.setConduitConfig(conduitConfig);
return Arrays.asList((Object)conduitFeature);
}
private TrustManager[] trustManager(KeyStore ks) throws Exception {
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(ks);
return factory.getTrustManagers();
}
private KeyManager[] keyManager(KeyStore ks, String keyPassword) throws Exception {
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(getDefaultAlgorithm());
kmfactory.init(ks, keyPassword.toCharArray());
return kmfactory.getKeyManagers();
}
private KeyStore keystore(String keystorePath, String storePassword) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keystorePath), storePassword.toCharArray());
return ks;
}
}
| 1,004 |
0 | Create_ds/cxf-dosgi/samples/ssl/ssl-intent/src/main/java/org/apache/cxf/dosgi/samples | Create_ds/cxf-dosgi/samples/ssl/ssl-intent/src/main/java/org/apache/cxf/dosgi/samples/ssl/EchoService.java | /**
* 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.cxf.dosgi.samples.ssl;
public interface EchoService {
String echo(String msg);
}
| 1,005 |
0 | Create_ds/cxf-dosgi/samples/security_filter/src/main/java/org/apache/cxf/dosgi/samples | Create_ds/cxf-dosgi/samples/security_filter/src/main/java/org/apache/cxf/dosgi/samples/security/SecureRestEndpoint.java | /**
* 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.cxf.dosgi.samples.security;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.osgi.service.component.annotations.Component;
@Component //
(//
service = SecureRestEndpoint.class,
property = //
{ //
"service.exported.interfaces=*",
"service.exported.configs=org.apache.cxf.rs",
"org.apache.cxf.rs.httpservice.context=/secure"
}
)
@Path("/")
public class SecureRestEndpoint {
@GET
@Path("hello")
@Produces(MediaType.TEXT_PLAIN)
public String sayHello() {
return "Hello and congratulations, you made it past the security filter";
}
}
| 1,006 |
0 | Create_ds/cxf-dosgi/samples/security_filter/src/main/java/org/apache/cxf/dosgi/samples | Create_ds/cxf-dosgi/samples/security_filter/src/main/java/org/apache/cxf/dosgi/samples/security/SampleSecurityFilter.java | /**
* 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.cxf.dosgi.samples.security;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A filter that requires a query string of "secure" to invoke the protected resource. Pax-Web whiteboard (if
* deployed) will attempt to apply this filter to servlets by name or URL, and will complain if neither
* servletName or urlPatterns are specified. The felix http service whiteboard may do something similar.
*/
@Component //
(//
service = javax.servlet.Filter.class,
property = //
{
"org.apache.cxf.httpservice.filter=true", "servletNames=none"
}//
)
public class SampleSecurityFilter implements Filter {
private static final Logger LOG = LoggerFactory.getLogger(SampleSecurityFilter.class);
@Override
public void destroy() {
LOG.info("destroy()");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if ("secure".equals(((HttpServletRequest)request).getQueryString())) {
LOG.info("Access granted");
chain.doFilter(request, response);
} else {
LOG.warn("Access denied");
((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
@Override
public void init(FilterConfig config) {
LOG.info("init()");
}
}
| 1,007 |
0 | Create_ds/cxf-dosgi/samples/soap/impl/src/main/java/org/apache/cxf/dosgi/samples/soap | Create_ds/cxf-dosgi/samples/soap/impl/src/main/java/org/apache/cxf/dosgi/samples/soap/impl/TaskServiceImpl.java | /**
* 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.cxf.dosgi.samples.soap.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.cxf.dosgi.samples.soap.Task;
import org.apache.cxf.dosgi.samples.soap.TaskService;
import org.osgi.service.component.annotations.Component;
@Component //
(//
immediate = true, //
name = "TaskService", //
property = //
{ //
"service.exported.interfaces=*", //
"service.exported.configs=org.apache.cxf.ws", //
"org.apache.cxf.ws.address=/taskservice" //
} //
)
public class TaskServiceImpl implements TaskService {
Map<Integer, Task> taskMap;
public TaskServiceImpl() {
taskMap = new HashMap<>();
Task task = new Task();
task.setId(1);
task.setTitle("Buy some coffee");
task.setDescription("Take the extra strong");
addOrUpdate(task);
task = new Task();
task.setId(2);
task.setTitle("Finish DOSGi example");
task.setDescription("");
addOrUpdate(task);
}
@Override
public Task get(Integer id) {
return taskMap.get(id);
}
@Override
public void addOrUpdate(Task task) {
taskMap.put(task.getId(), task);
}
@Override
public Collection<Task> getAll() {
// taskMap.values is not serializable
return new ArrayList<>(taskMap.values());
}
@Override
public void delete(Integer id) {
taskMap.remove(id);
}
}
| 1,008 |
0 | Create_ds/cxf-dosgi/samples/soap/api/src/main/java/org/apache/cxf/dosgi/samples | Create_ds/cxf-dosgi/samples/soap/api/src/main/java/org/apache/cxf/dosgi/samples/soap/Task.java | /**
* 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.cxf.dosgi.samples.soap;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Task {
Integer id;
String title;
String description;
Date dueDate;
boolean finished;
public Task() {
}
public Task(Integer id, String title, String description) {
super();
this.id = id;
this.title = title;
this.description = description;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public boolean isFinished() {
return finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
}
| 1,009 |
0 | Create_ds/cxf-dosgi/samples/soap/api/src/main/java/org/apache/cxf/dosgi/samples | Create_ds/cxf-dosgi/samples/soap/api/src/main/java/org/apache/cxf/dosgi/samples/soap/TaskService.java | /**
* 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.cxf.dosgi.samples.soap;
import java.util.Collection;
import javax.jws.WebService;
@WebService
public interface TaskService {
Task get(Integer id);
void addOrUpdate(Task task);
void delete(Integer id);
Collection<Task> getAll();
}
| 1,010 |
0 | Create_ds/cxf-dosgi/samples/soap/client/src/main/java/org/apache/cxf/dosgi/samples/soap | Create_ds/cxf-dosgi/samples/soap/client/src/main/java/org/apache/cxf/dosgi/samples/soap/client/TaskServiceCommand.java | /**
* 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.cxf.dosgi.samples.soap.client;
import java.util.Collection;
import org.apache.cxf.dosgi.samples.soap.Task;
import org.apache.cxf.dosgi.samples.soap.TaskService;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
@Component//
(//
service = TaskServiceCommand.class,
property = //
{
"osgi.command.scope=task", //
"osgi.command.function=list", //
"osgi.command.function=add", //
"osgi.command.function=delete"
}//
)
public class TaskServiceCommand {
private TaskService taskService;
public void list() {
System.out.println("Open tasks:");
Collection<Task> tasks = taskService.getAll();
for (Task task : tasks) {
String line = String.format("%d %s", task.getId(), task.getTitle());
System.out.println(line);
}
}
public void add(Integer id, String title) {
Task task = new Task(id, title, "");
taskService.addOrUpdate(task);
}
public void delete(Integer id) {
taskService.delete(id);
}
@Reference
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
}
| 1,011 |
0 | Create_ds/cxf-dosgi/samples/rest/impl/src/main/java/org/apache/cxf/dosgi/samples/rest | Create_ds/cxf-dosgi/samples/rest/impl/src/main/java/org/apache/cxf/dosgi/samples/rest/impl/TaskResourceImpl.java | /**
* 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.cxf.dosgi.samples.rest.impl;
import static java.util.Arrays.asList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.cxf.dosgi.common.api.IntentsProvider;
import org.apache.cxf.dosgi.samples.rest.Task;
import org.apache.cxf.dosgi.samples.rest.TaskResource;
import org.apache.cxf.jaxrs.swagger.Swagger2Feature;
import org.osgi.service.component.annotations.Component;
@Component//
(//
immediate = true, //
name = "TaskResource", //
property = //
{ //
"service.exported.interfaces=org.apache.cxf.dosgi.samples.rest.TaskResource", //
"service.exported.configs=org.apache.cxf.rs", //
"org.apache.cxf.rs.address=/tasks" //
} //
)
public class TaskResourceImpl implements TaskResource, IntentsProvider {
Map<Integer, Task> taskMap;
public TaskResourceImpl() {
taskMap = new HashMap<>();
Task task = new Task();
task.setId(1);
task.setTitle("Buy some coffee");
task.setDescription("Take the extra strong");
add(task);
task = new Task();
task.setId(2);
task.setTitle("Finish DOSGi example");
task.setDescription("");
add(task);
}
@Override
public Task get(Integer id) {
return taskMap.get(id);
}
@Override
public void add(Task task) {
taskMap.put(task.getId(), task);
}
@Override
public void update(Integer id, Task task) {
taskMap.put(id, task);
}
@Override
public Task[] getAll() {
return taskMap.values().toArray(new Task[]{});
}
@Override
public void delete(Integer id) {
taskMap.remove(id);
}
@Override
public List<?> getIntents() {
return asList(createSwaggerFeature());
}
private Swagger2Feature createSwaggerFeature() {
Swagger2Feature swagger = new Swagger2Feature();
swagger.setDescription("Sample jaxrs application to organize tasks");
swagger.setTitle("Tasks sample");
swagger.setUsePathBasedConfig(true); // Necessary for OSGi
// swagger.setScan(false); // Must be set for cxf < 3.2.x
swagger.setPrettyPrint(true);
swagger.setSupportSwaggerUi(true);
return swagger;
}
}
| 1,012 |
0 | Create_ds/cxf-dosgi/samples/rest/api/src/main/java/org/apache/cxf/dosgi/samples | Create_ds/cxf-dosgi/samples/rest/api/src/main/java/org/apache/cxf/dosgi/samples/rest/Task.java | /**
* 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.cxf.dosgi.samples.rest;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Task {
Integer id;
String title;
String description;
Date dueDate;
boolean finished;
public Task() {
}
public Task(Integer id, String title, String description) {
super();
this.id = id;
this.title = title;
this.description = description;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public boolean isFinished() {
return finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
}
| 1,013 |
0 | Create_ds/cxf-dosgi/samples/rest/api/src/main/java/org/apache/cxf/dosgi/samples | Create_ds/cxf-dosgi/samples/rest/api/src/main/java/org/apache/cxf/dosgi/samples/rest/TaskResource.java | /**
* 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.cxf.dosgi.samples.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@Api(tags = {"tasks"})
@Path("")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public interface TaskResource {
@ApiOperation(value = "Get task by ID", notes = "Returns a single task", response = Task.class)
@ApiResponses(value = {
@ApiResponse(code = 404, message = "Task not found")
})
@GET
@Path("/{id}")
Task get(@PathParam("id") Integer id);
@ApiOperation(value = "Add task")
@POST
void add(Task task);
@ApiOperation(value = "Update existing task")
@PUT
@Path("/{id}")
void update(Integer id, Task task);
@ApiOperation(value = "Deletes a task")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "Task not found")
})
@DELETE
@Path("/{id}")
void delete(Integer id);
@ApiOperation(value = "Retrieve all tasks")
@GET
Task[] getAll();
}
| 1,014 |
0 | Create_ds/cxf-dosgi/samples/rest/impl-jackson/src/main/java/org/apache/cxf/dosgi/samples/rest | Create_ds/cxf-dosgi/samples/rest/impl-jackson/src/main/java/org/apache/cxf/dosgi/samples/rest/impl/JacksonIntent.java | /**
* 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.cxf.dosgi.samples.rest.impl;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import org.apache.cxf.dosgi.common.api.IntentsProvider;
import org.osgi.service.component.annotations.Component;
/**
* Not needed in the current example config.
* This shows how to export a custom intent.
*/
@Component //
(//
property = "org.apache.cxf.dosgi.IntentName=jackson" //
)
public class JacksonIntent implements IntentsProvider {
@Override
public List<?> getIntents() {
return Arrays.asList((Object)new JacksonJaxbJsonProvider());
}
}
| 1,015 |
0 | Create_ds/cxf-dosgi/samples/rest/impl-jackson/src/main/java/org/apache/cxf/dosgi/samples/rest | Create_ds/cxf-dosgi/samples/rest/impl-jackson/src/main/java/org/apache/cxf/dosgi/samples/rest/impl/TaskResourceImpl.java | /**
* 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.cxf.dosgi.samples.rest.impl;
import static java.util.Arrays.asList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.cxf.dosgi.common.api.IntentsProvider;
import org.apache.cxf.dosgi.samples.rest.Task;
import org.apache.cxf.dosgi.samples.rest.TaskResource;
import org.apache.cxf.ext.logging.LoggingFeature;
import org.apache.cxf.feature.Features;
import org.osgi.service.component.annotations.Component;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import io.swagger.annotations.Api;
@Component//
(//
immediate = true, //
name = "TaskResource", //
property = //
{ //
"service.exported.interfaces=*", //
"service.exported.configs=org.apache.cxf.rs", //
"org.apache.cxf.rs.address=/tasks", //
// By default CXF will favor the default json provider
"cxf.bus.prop.skip.default.json.provider.registration=true"
} //
)
@Api(value = "mytest")
@Features(classes = {LoggingFeature.class})
public class TaskResourceImpl implements TaskResource, IntentsProvider {
Map<Integer, Task> taskMap;
public TaskResourceImpl() {
taskMap = new HashMap<>();
Task task = new Task();
task.setId(1);
task.setTitle("Buy some coffee");
task.setDescription("Take the extra strong");
add(task);
task = new Task();
task.setId(2);
task.setTitle("Finish DOSGi example");
task.setDescription("");
add(task);
}
@Override
public Task get(Integer id) {
return taskMap.get(id);
}
@Override
public void add(Task task) {
taskMap.put(task.getId(), task);
}
@Override
public void update(Integer id, Task task) {
taskMap.put(id, task);
}
@Override
public Task[] getAll() {
return taskMap.values().toArray(new Task[]{});
}
@Override
public void delete(Integer id) {
taskMap.remove(id);
}
@Override
public List<?> getIntents() {
return asList(new JacksonJaxbJsonProvider());
}
}
| 1,016 |
0 | Create_ds/cxf-dosgi/samples/rest/client/src/main/java/org/apache/cxf/dosgi/samples/rest | Create_ds/cxf-dosgi/samples/rest/client/src/main/java/org/apache/cxf/dosgi/samples/rest/client/TaskResourceCommand.java | /**
* 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.cxf.dosgi.samples.rest.client;
import org.apache.cxf.dosgi.samples.rest.Task;
import org.apache.cxf.dosgi.samples.rest.TaskResource;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
@Component//
(//
service = TaskResourceCommand.class,
property = //
{
"osgi.command.scope=task", //
"osgi.command.function=list", //
"osgi.command.function=add", //
"osgi.command.function=delete"
}//
)
public class TaskResourceCommand {
private TaskResource taskService;
public void list() {
System.out.println("Open tasks:");
Task[] tasks = taskService.getAll();
for (Task task : tasks) {
String line = String.format("%d %s", task.getId(), task.getTitle());
System.out.println(line);
}
}
public void add(Integer id, String title) {
Task task = new Task(id, title, "");
taskService.add(task);
}
public void delete(Integer id) {
taskService.delete(id);
}
@Reference
public void setTaskService(TaskResource taskService) {
this.taskService = taskService;
}
}
| 1,017 |
0 | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/proxy/MySubService.java | /**
* 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.cxf.dosgi.common.proxy;
import java.io.IOException;
public interface MySubService extends MyBaseService {
void throwException2() throws IOException;
}
| 1,018 |
0 | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/proxy/ServiceInvocationHandlerTest.java | /**
* 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.cxf.dosgi.common.proxy;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
public class ServiceInvocationHandlerTest {
private static final Map<String, Method> OBJECT_METHODS = new HashMap<>();
{
for (Method m : Object.class.getMethods()) {
OBJECT_METHODS.put(m.getName(), m);
}
}
@Test
public void testInvoke() throws Throwable {
ServiceInvocationHandler sih = new ServiceInvocationHandler("hello", String.class);
Method m = String.class.getMethod("length");
assertEquals(5, sih.invoke(null, m, new Object[] {}));
}
@Test
public void testInvokeObjectMethod() throws Throwable {
final List<String> called = new ArrayList<>();
ServiceInvocationHandler sih = new ServiceInvocationHandler("hi", String.class) {
@Override
public boolean equals(Object obj) {
called.add("equals");
return super.equals(obj);
}
@Override
public int hashCode() {
called.add("hashCode");
return super.hashCode();
}
@Override
public String toString() {
called.add("toString");
return "somestring";
}
};
Object proxy = Proxy.newProxyInstance(
getClass().getClassLoader(), new Class[] {Runnable.class}, sih);
assertEquals(true,
sih.invoke(null, OBJECT_METHODS.get("equals"), new Object[] {proxy}));
assertEquals(System.identityHashCode(sih),
sih.invoke(null, OBJECT_METHODS.get("hashCode"), new Object[] {}));
assertEquals("somestring",
sih.invoke(null, OBJECT_METHODS.get("toString"), new Object[] {}));
assertEquals(Arrays.asList("equals", "hashCode", "toString"), called);
}
@Test(expected = IOException.class)
public void testException() throws IOException {
MySubService proxy = ProxyFactory.create(new MyServiceImpl(), MySubService.class);
proxy.throwException2();
}
@Test(expected = IOException.class)
public void testInheritedException() throws IOException {
MySubService proxy = ProxyFactory.create(new MyServiceImpl(), MySubService.class);
proxy.throwException1();
}
}
| 1,019 |
0 | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/proxy/MyBaseService.java | /**
* 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.cxf.dosgi.common.proxy;
import java.io.IOException;
public interface MyBaseService {
void throwException1() throws IOException;
}
| 1,020 |
0 | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/proxy/MyServiceImpl.java | /**
* 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.cxf.dosgi.common.proxy;
import java.io.IOException;
public class MyServiceImpl implements MySubService {
@Override
public void throwException1() throws IOException {
throw new IOException();
}
@Override
public void throwException2() throws IOException {
throw new IOException();
}
}
| 1,021 |
0 | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/util/PropertyHelperTest.java | /**
* 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.cxf.dosgi.common.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.RemoteConstants;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class PropertyHelperTest {
@Test
public void testMultiValuePropertyAsString() {
assertEquals(Collections.singleton("hi"),
PropertyHelper.getMultiValueProperty("hi"));
}
@Test
public void testMultiValuePropertyAsArray() {
assertEquals(Arrays.asList("a", "b"),
PropertyHelper.getMultiValueProperty(new String[]{"a", "b"}));
}
@Test
public void testMultiValuePropertyAsCollection() {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
assertEquals(list, PropertyHelper.getMultiValueProperty(list));
}
@Test
public void testMultiValuePropertyNull() {
assertTrue(PropertyHelper.getMultiValueProperty(null).isEmpty());
}
@Test
public void testGetProperty() {
Map<String, Object> p = new HashMap<>();
p.put(RemoteConstants.ENDPOINT_ID, "http://google.de");
p.put("notAString", new Object());
p.put(org.osgi.framework.Constants.OBJECTCLASS, new String[]{"my.class"});
p.put(RemoteConstants.SERVICE_IMPORTED_CONFIGS, new String[]{"my.config"});
EndpointDescription endpoint = new EndpointDescription(p);
assertNull(PropertyHelper.getProperty(endpoint.getProperties(), "unknownProp"));
assertEquals(p.get(RemoteConstants.ENDPOINT_ID),
PropertyHelper.getProperty(endpoint.getProperties(), RemoteConstants.ENDPOINT_ID));
assertNull(PropertyHelper.getProperty(endpoint.getProperties(), "notAString"));
}
}
| 1,022 |
0 | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/intent | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/intent/impl/DummyServiceWithLogging.java | /**
* 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.cxf.dosgi.common.intent.impl;
import org.apache.cxf.feature.Features;
import org.apache.cxf.transport.common.gzip.GZIPFeature;
@Features(classes = GZIPFeature.class)
public class DummyServiceWithLogging {
}
| 1,023 |
0 | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/intent | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/intent/impl/DummyServiceWithLoggingIP.java | /**
* 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.cxf.dosgi.common.intent.impl;
import java.util.Arrays;
import java.util.List;
import org.apache.cxf.dosgi.common.api.IntentsProvider;
import org.apache.cxf.transport.common.gzip.GZIPFeature;
public class DummyServiceWithLoggingIP implements IntentsProvider {
@Override
public List<?> getIntents() {
return Arrays.asList(new GZIPFeature());
}
}
| 1,024 |
0 | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/intent | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/intent/impl/IntentManagerImplTest.java | /**
* 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.cxf.dosgi.common.intent.impl;
import java.util.List;
import org.apache.cxf.transport.common.gzip.GZIPFeature;
import org.junit.Assert;
import org.junit.Test;
public class IntentManagerImplTest {
@Test
public void testIntentsFromFeatureAnn() {
IntentManagerImpl im = new IntentManagerImpl();
List<Object> intents = im.getIntentsFromService(new DummyServiceWithLogging());
Assert.assertEquals(1, intents.size());
Object feature = intents.iterator().next();
Assert.assertEquals(GZIPFeature.class, feature.getClass());
}
@Test
public void testIntentsFromIntentsProvider() {
IntentManagerImpl im = new IntentManagerImpl();
List<Object> intents = im.getIntentsFromService(new DummyServiceWithLoggingIP());
Assert.assertEquals(1, intents.size());
Object feature = intents.iterator().next();
Assert.assertEquals(GZIPFeature.class, feature.getClass());
}
}
| 1,025 |
0 | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/httpservice/HttpServiceManagerTest.java | /**
* 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.cxf.dosgi.common.httpservice;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.junit.Assert.assertEquals;
import java.util.Dictionary;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;
public class HttpServiceManagerTest {
@Test
public void testGetAbsoluteAddress() {
HttpServiceManager manager = new HttpServiceManager();
manager.initFromConfig(null);
String address1 = manager.getAbsoluteAddress(null, "/myservice");
assertEquals("http://localhost:8181/cxf/myservice", address1);
String address2 = manager.getAbsoluteAddress("/mycontext", "/myservice");
assertEquals("http://localhost:8181/mycontext/myservice", address2);
}
@Test
public void testRegisterAndUnregisterServlet() throws Exception {
IMocksControl c = EasyMock.createControl();
BundleContext dswContext = c.createMock(BundleContext.class);
Filter filter = c.createMock(Filter.class);
expect(dswContext.createFilter(EasyMock.eq("(service.id=12345)"))).andReturn(filter).once();
Capture<ServiceListener> captured = EasyMock.newCapture();
dswContext.addServiceListener(EasyMock.capture(captured), EasyMock.<String>anyObject());
expectLastCall().atLeastOnce();
expect(dswContext.getProperty("org.apache.cxf.httpservice.requirefilter")).andReturn(null).atLeastOnce();
ServletConfig config = c.createMock(ServletConfig.class);
expect(config.getInitParameter(EasyMock.<String>anyObject())).andReturn(null).atLeastOnce();
ServletContext servletContext = c.createMock(ServletContext.class);
expect(config.getServletContext()).andReturn(servletContext);
final HttpService httpService = new DummyHttpService(config);
ServiceReference<?> sr = c.createMock(ServiceReference.class);
expect(sr.getProperty(EasyMock.eq("service.id"))).andReturn(12345L).atLeastOnce();
expect(servletContext.getResourceAsStream((String)EasyMock.anyObject())).andReturn(null).anyTimes();
c.replay();
HttpServiceManager h = new HttpServiceManager();
h.setContext(dswContext);
h.setHttpService(httpService);
Bus bus = BusFactory.newInstance().createBus();
h.registerServlet(bus, "/myService", dswContext, 12345L);
ServiceEvent event = new ServiceEvent(ServiceEvent.UNREGISTERING, sr);
captured.getValue().serviceChanged(event);
c.verify();
}
static class DummyHttpService implements HttpService {
private ServletConfig config;
DummyHttpService(ServletConfig config) {
this.config = config;
}
@Override
@SuppressWarnings("rawtypes")
public void registerServlet(String alias, Servlet servlet, Dictionary initparams, HttpContext context)
throws ServletException {
assertEquals("/myService", alias);
servlet.init(config);
}
@Override
public void registerResources(String alias, String name, HttpContext context) {
throw new RuntimeException("This method should not be called");
}
@Override
public void unregister(String alias) {
}
@Override
public HttpContext createDefaultHttpContext() {
return EasyMock.createNiceMock(HttpContext.class);
}
}
}
| 1,026 |
0 | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/test/java/org/apache/cxf/dosgi/common/httpservice/SecurityDelegatingHttpContextTest.java | /**
* 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.cxf.dosgi.common.httpservice;
import java.io.PrintWriter;
import java.net.URL;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@SuppressWarnings({
"unchecked", "rawtypes"
})
public class SecurityDelegatingHttpContextTest {
protected HttpContext defaultHttpContext;
protected SecurityDelegatingHttpContext httpContext;
protected CommitResponseFilter commitFilter;
protected DoNothingFilter doNothingFilter;
protected AccessDeniedFilter accessDeniedFilter;
protected String mimeType;
protected URL url; // does not need to exist
@Before
public void setUp() throws Exception {
mimeType = "text/xml";
url = new URL("file:test.xml"); // does not need to exist
// Sample filters
commitFilter = new CommitResponseFilter();
doNothingFilter = new DoNothingFilter();
accessDeniedFilter = new AccessDeniedFilter();
// Mock up the default http context
defaultHttpContext = EasyMock.createNiceMock(HttpContext.class);
EasyMock.expect(defaultHttpContext.getMimeType((String)EasyMock.anyObject())).andReturn(mimeType);
EasyMock.expect(defaultHttpContext.getResource((String)EasyMock.anyObject())).andReturn(url);
EasyMock.replay(defaultHttpContext);
}
@Test
public void testFilterRequired() throws Exception {
// Mock up the service references
ServiceReference[] serviceReferences = {};
// Mock up the bundle context
BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class);
EasyMock.expect(bundleContext.getServiceReferences(Filter.class.getName(),
"(org.apache.cxf.httpservice.filter=true)"))
.andReturn(serviceReferences);
EasyMock.replay(bundleContext);
// Set up the secure http context
httpContext = new SecurityDelegatingHttpContext(bundleContext, defaultHttpContext);
httpContext.requireFilter = true;
// Ensure that the httpContext doesn't allow the request to be processed, since there are no registered servlet
// filters
HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
EasyMock.replay(request);
HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
EasyMock.replay(response);
boolean requestAllowed = httpContext.handleSecurity(request, response);
assertFalse(requestAllowed);
// Ensure that the httpContext returns true if there is no requirement for registered servlet filters
httpContext.requireFilter = false;
requestAllowed = httpContext.handleSecurity(request, response);
assertTrue(requestAllowed);
}
@Test
public void testSingleCommitFilter() throws Exception {
// Mock up the service references
ServiceReference filterReference = EasyMock.createNiceMock(ServiceReference.class);
EasyMock.replay(filterReference);
ServiceReference[] serviceReferences = {filterReference};
// Mock up the bundle context
BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class);
EasyMock.expect(bundleContext.getServiceReferences((String)EasyMock.anyObject(), (String)EasyMock.anyObject()))
.andReturn(serviceReferences);
EasyMock.expect(bundleContext.getService((ServiceReference)EasyMock.anyObject())).andReturn(commitFilter);
EasyMock.replay(bundleContext);
// Set up the secure http context
httpContext = new SecurityDelegatingHttpContext(bundleContext, defaultHttpContext);
// Ensure that the httpContext returns false, since the filter has committed the response
HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
EasyMock.replay(request);
HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
EasyMock.expect(response.isCommitted()).andReturn(false); // the first call checks to see whether to invoke the
// filter
EasyMock.expect(response.isCommitted()).andReturn(true); // the second is called to determine the handleSecurity
// return value
EasyMock.expect(response.getWriter()).andReturn(new PrintWriter(System.out));
EasyMock.replay(response);
assertFalse(httpContext.handleSecurity(request, response));
// Ensure that the appropriate filters were called
assertTrue(commitFilter.called);
assertFalse(doNothingFilter.called);
assertFalse(accessDeniedFilter.called);
}
@Test
public void testFilterChain() throws Exception {
// Mock up the service references
ServiceReference filterReference = EasyMock.createNiceMock(ServiceReference.class);
EasyMock.replay(filterReference);
ServiceReference[] serviceReferences = {filterReference, filterReference};
// Mock up the bundle context
BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class);
EasyMock.expect(bundleContext.getServiceReferences((String)EasyMock.anyObject(), (String)EasyMock.anyObject()))
.andReturn(serviceReferences);
EasyMock.expect(bundleContext.getService((ServiceReference)EasyMock.anyObject())).andReturn(doNothingFilter);
EasyMock.expect(bundleContext.getService((ServiceReference)EasyMock.anyObject())).andReturn(commitFilter);
EasyMock.replay(bundleContext);
// Set up the secure http context
httpContext = new SecurityDelegatingHttpContext(bundleContext, defaultHttpContext);
// Ensure that the httpContext returns false, since the filter has committed the response
HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
EasyMock.replay(request);
HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
EasyMock.expect(response.isCommitted()).andReturn(false); // doNothingFilter should not commit the response
EasyMock.expect(response.getWriter()).andReturn(new PrintWriter(System.out));
EasyMock.expect(response.isCommitted()).andReturn(false);
EasyMock.expect(response.isCommitted()).andReturn(true); // the commit filter indicating that it committed the
// response
EasyMock.replay(response);
assertFalse(httpContext.handleSecurity(request, response));
// Ensure that the appropriate filters were called
assertTrue(doNothingFilter.called);
assertTrue(commitFilter.called);
assertFalse(accessDeniedFilter.called);
}
@Test
public void testAllowRequest() throws Exception {
// Mock up the service references
ServiceReference filterReference = EasyMock.createNiceMock(ServiceReference.class);
EasyMock.replay(filterReference);
ServiceReference[] serviceReferences = {filterReference};
// Mock up the bundle context
BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class);
EasyMock.expect(bundleContext.getServiceReferences((String)EasyMock.anyObject(), (String)EasyMock.anyObject()))
.andReturn(serviceReferences);
EasyMock.expect(bundleContext.getService((ServiceReference)EasyMock.anyObject())).andReturn(doNothingFilter);
EasyMock.replay(bundleContext);
// Set up the secure http context
httpContext = new SecurityDelegatingHttpContext(bundleContext, defaultHttpContext);
// Ensure that the httpContext returns true, since the filter has not committed the response
HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
EasyMock.replay(request);
HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
EasyMock.expect(response.isCommitted()).andReturn(false);
EasyMock.replay(response);
assertTrue(httpContext.handleSecurity(request, response));
// Ensure that the appropriate filters were called
assertTrue(doNothingFilter.called);
assertFalse(commitFilter.called);
assertFalse(accessDeniedFilter.called);
}
@Test
public void testDelegation() {
BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class);
EasyMock.replay(bundleContext);
// Set up the secure http context
httpContext = new SecurityDelegatingHttpContext(bundleContext, defaultHttpContext);
// Ensure that it delegates non-security calls to the wrapped implementation (in this case, the mock)
assertEquals(mimeType, httpContext.getMimeType(""));
assertEquals(url, httpContext.getResource(""));
}
}
class CommitResponseFilter implements Filter {
boolean called;
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws java.io.IOException {
called = true;
response.getWriter().write("committing the response");
}
}
class DoNothingFilter implements Filter {
boolean called;
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws java.io.IOException, javax.servlet.ServletException {
called = true;
chain.doFilter(request, response);
}
}
class AccessDeniedFilter implements Filter {
boolean called;
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws java.io.IOException {
called = true;
((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
| 1,027 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/proxy/ProxyFactory.java | /**
* 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.cxf.dosgi.common.proxy;
import java.lang.reflect.Proxy;
public final class ProxyFactory {
private ProxyFactory() {
}
@SuppressWarnings("unchecked")
public static <T> T create(Object serviceProxy, Class<T> iType) {
Class<?>[] ifaces = new Class<?>[] {iType};
return (T)Proxy.newProxyInstance(iType.getClassLoader(), ifaces,
new ServiceInvocationHandler(serviceProxy, iType));
}
}
| 1,028 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/proxy/ExceptionMapper.java | /**
* 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.cxf.dosgi.common.proxy;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.osgi.framework.ServiceException;
public class ExceptionMapper {
private static final String REMOTE_EXCEPTION_TYPE = "REMOTE";
private Map<Method, Set<Class<?>>> exceptionsMap = new HashMap<>();
public ExceptionMapper(Class<?> iType) {
introspectTypeForExceptions(iType);
}
public Throwable mapException(Method m, Throwable ex) {
Throwable cause = ex.getCause() == null ? ex : ex.getCause();
Set<Class<?>> excTypes = exceptionsMap.get(m);
if (excTypes != null) {
for (Class<?> type : excTypes) {
if (type.isAssignableFrom(ex.getClass())) {
return ex;
}
if (type.isAssignableFrom(cause.getClass())) {
return cause;
}
}
}
return new ServiceException(REMOTE_EXCEPTION_TYPE, ex);
}
private void introspectTypeForExceptions(Class<?> iType) {
for (Method m : iType.getDeclaredMethods()) {
addExceptions(m);
}
for (Method m : iType.getMethods()) {
addExceptions(m);
}
}
private void addExceptions(Method m) {
for (Class<?> excType : m.getExceptionTypes()) {
if (Exception.class.isAssignableFrom(excType)) {
getCurrentExTypes(m).add(excType);
}
}
}
private Set<Class<?>> getCurrentExTypes(Method m) {
Set<Class<?>> types = exceptionsMap.get(m);
if (types == null) {
types = new HashSet<>();
exceptionsMap.put(m, types);
}
return types;
}
}
| 1,029 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/proxy/ServiceInvocationHandler.java | /**
* 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.cxf.dosgi.common.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Collection;
public class ServiceInvocationHandler implements InvocationHandler {
private static final Collection<Method> OBJECT_METHODS = Arrays.asList(Object.class.getMethods());
private Object serviceObject;
private ExceptionMapper exceptionMapper;
ServiceInvocationHandler(Object serviceObject, Class<?> iType) {
this.serviceObject = serviceObject;
this.exceptionMapper = new ExceptionMapper(iType);
}
@Override
public Object invoke(Object proxy, final Method m, Object[] params) throws Throwable {
if (OBJECT_METHODS.contains(m)) {
if (m.getName().equals("equals")) {
params = new Object[] {Proxy.getInvocationHandler(params[0])};
}
return m.invoke(this, params);
}
ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
final Object[] paramsFinal = params;
return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
return m.invoke(serviceObject, paramsFinal);
}
});
} catch (Throwable ex) {
Throwable theCause = ex.getCause() == null ? ex : ex.getCause();
throw exceptionMapper.mapException(m, theCause);
} finally {
Thread.currentThread().setContextClassLoader(oldCl);
}
}
}
| 1,030 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/util/PropertyHelper.java | /**
* 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.cxf.dosgi.common.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class PropertyHelper {
public static final Logger LOG = LoggerFactory.getLogger(PropertyHelper.class);
private PropertyHelper() {
}
@SuppressWarnings("unchecked")
public static Collection<String> getMultiValueProperty(Object property) {
if (property == null) {
return Collections.emptyList();
} else if (property instanceof Collection) {
return (Collection<String>)property;
} else if (property instanceof String[]) {
return Arrays.asList((String[])property);
} else {
return Collections.singleton(property.toString());
}
}
public static String getProperty(Map<String, Object> dict, String name) {
Object value = dict.get(name);
return value instanceof String ? (String) value : null;
}
public static String getFirstNonEmptyStringProperty(Map<String, Object> dict, String... keys) {
for (String key : keys) {
String value = getProperty(dict, key);
if (value != null) {
return value;
}
}
return null;
}
}
| 1,031 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/intent/IntentHandler.java | /**
* 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.cxf.dosgi.common.intent;
import org.apache.cxf.endpoint.AbstractEndpointFactory;
public interface IntentHandler {
boolean apply(AbstractEndpointFactory factory, String intentName, Object intent);
}
| 1,032 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/intent/IntentManager.java | /**
* 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.cxf.dosgi.common.intent;
import java.util.List;
import java.util.Map;
import java.util.Set;
public interface IntentManager {
String INTENT_NAME_PROP = "org.apache.cxf.dosgi.IntentName";
String INTENT_NAME_PROP2 = "intentName";
Set<String> getExported(Map<String, Object> sd);
Set<String> getImported(Map<String, Object> sd);
List<Object> getRequiredIntents(Set<String> requiredIntents);
<T> List<T> getIntents(Class<? extends T> type, List<Object> intents);
<T> T getIntent(Class<? extends T> type, List<Object> intents);
List<Object> getIntentsFromService(Object serviceBean);
}
| 1,033 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/intent | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/intent/impl/IntentManagerImpl.java | /**
* 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.cxf.dosgi.common.intent.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import org.apache.cxf.dosgi.common.api.IntentsProvider;
import org.apache.cxf.dosgi.common.intent.IntentManager;
import org.apache.cxf.dosgi.common.util.PropertyHelper;
import org.apache.cxf.feature.Features;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.remoteserviceadmin.RemoteConstants;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(service = IntentManager.class)
public class IntentManagerImpl implements IntentManager {
static final Logger LOG = LoggerFactory.getLogger(IntentManagerImpl.class);
private static final int DEFAULT_INTENT_TIMEOUT = 30000;
private final Map<String, Object> intentMap = new HashMap<>();
private final long maxIntentWaitTime = DEFAULT_INTENT_TIMEOUT;
private ServiceTracker<Object, Object> tracker;
@Activate
public void activate(BundleContext context) throws InvalidSyntaxException {
String filterSt = String.format("(|(%s=*)(%s=*))", INTENT_NAME_PROP, INTENT_NAME_PROP2);
Filter filter = FrameworkUtil.createFilter(filterSt);
tracker = new ServiceTracker<Object, Object>(context, filter, null) {
@Override
public Object addingService(ServiceReference<Object> reference) {
Object intent = super.addingService(reference);
addIntent(intent, getName(reference));
return intent;
}
@Override
public void removedService(ServiceReference<Object> reference, Object intent) {
removeIntent(intent, getName(reference));
super.removedService(reference, intent);
}
private String getName(ServiceReference<Object> reference) {
String name = (String)reference.getProperty(INTENT_NAME_PROP);
String name2 = (String)reference.getProperty(INTENT_NAME_PROP2);
return name != null ? name : name2;
}
};
tracker.open();
}
@Deactivate
public void deactivate() {
tracker.close();
}
public synchronized void addIntent(Object intent, String intentName) {
LOG.info("Adding custom intent " + intentName);
intentMap.put(intentName, intent);
}
public synchronized void removeIntent(Object intent, String intentName) {
intentMap.remove(intentName);
}
@Override
@SuppressWarnings("unchecked")
public synchronized List<Object> getRequiredIntents(Set<String> requiredIntents) {
String[] intentNames = assertAllIntentsSupported(requiredIntents);
List<Object> intents = new ArrayList<>();
for (String intentName : intentNames) {
Object intent = intentMap.get(intentName);
if (intent instanceof Callable<?>) {
try {
List<Object> curIntents = ((Callable<List<Object>>)intent).call();
intents.addAll(curIntents);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else if (intent instanceof IntentsProvider) {
try {
IntentsProvider provider = (IntentsProvider)intent;
List<?> curIntents = provider.getIntents();
intents.addAll(curIntents);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
intents.add(intent);
}
}
return intents;
}
@Override
public <T> T getIntent(Class<? extends T> type, List<Object> intents) {
List<T> selectedIntents = getIntents(type, intents);
if (selectedIntents.isEmpty()) {
return null;
}
if (selectedIntents.size() > 1) {
LOG.warn("More than one intent of type " + type + " present. Using only the first one.");
}
return selectedIntents.iterator().next();
}
@Override
public <T> List<T> getIntents(Class<? extends T> type, List<Object> intents) {
List<T> result = new ArrayList<>();
for (Object intent : intents) {
if (type.isInstance(intent)) {
result.add(type.cast(intent));
}
}
return result;
}
public synchronized String[] assertAllIntentsSupported(Set<String> requiredIntents) {
long endTime = System.currentTimeMillis() + maxIntentWaitTime;
Set<String> unsupportedIntents;
boolean first = true;
do {
unsupportedIntents = getMissingIntents(requiredIntents);
long remainingSeconds = (endTime - System.currentTimeMillis()) / 1000;
if (!unsupportedIntents.isEmpty() && remainingSeconds > 0) {
String msg = "Waiting for custom intents {} timeout in {} seconds";
if (first) {
LOG.info(msg, Arrays.toString(unsupportedIntents.toArray()), remainingSeconds);
first = false;
} else {
if (LOG.isDebugEnabled()) {
LOG.debug(msg, Arrays.toString(unsupportedIntents.toArray()), remainingSeconds);
}
}
try {
wait(1000);
} catch (InterruptedException e) {
LOG.warn(e.getMessage(), e);
}
}
} while (!unsupportedIntents.isEmpty() && System.currentTimeMillis() < endTime);
if (!unsupportedIntents.isEmpty()) {
throw new RuntimeException("service cannot be exported because the following "
+ "intents are not supported by this RSA: " + unsupportedIntents);
}
return requiredIntents.toArray(new String[]{});
}
private synchronized Set<String> getMissingIntents(Collection<String> requiredIntents) {
Set<String> unsupportedIntents = new HashSet<>();
unsupportedIntents.clear();
for (String ri : requiredIntents) {
if (!intentMap.containsKey(ri)) {
unsupportedIntents.add(ri);
}
}
return unsupportedIntents;
}
@Override
public Set<String> getExported(Map<String, Object> sd) {
Set<String> allIntents = new HashSet<>();
Collection<String> intents = PropertyHelper
.getMultiValueProperty(sd.get(RemoteConstants.SERVICE_EXPORTED_INTENTS));
allIntents.addAll(parseIntents(intents));
Collection<String> intents2 = PropertyHelper
.getMultiValueProperty(sd.get(RemoteConstants.SERVICE_EXPORTED_INTENTS_EXTRA));
allIntents.addAll(parseIntents(intents2));
return allIntents;
}
@Override
public List<Object> getIntentsFromService(Object serviceBean) {
List<Object> intents = new ArrayList<>();
if (serviceBean instanceof IntentsProvider) {
intents.addAll(((IntentsProvider)serviceBean).getIntents());
}
Features features = serviceBean.getClass().getAnnotation(Features.class);
if (features != null && features.classes() != null) {
for (Class<?> clazz : features.classes()) {
try {
intents.add(clazz.newInstance());
} catch (Exception e) {
throw new RuntimeException("Could not instantiate feature from class " + clazz.getName(), e);
}
}
}
return intents;
}
@Override
public Set<String> getImported(Map<String, Object> sd) {
Collection<String> intents = PropertyHelper.getMultiValueProperty(sd.get(RemoteConstants.SERVICE_INTENTS));
return new HashSet<>(intents);
}
private static Collection<String> parseIntents(Collection<String> intents) {
List<String> parsed = new ArrayList<>();
for (String intent : intents) {
parsed.addAll(Arrays.asList(intent.split("[ ]")));
}
return parsed;
}
}
| 1,034 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/endpoint/ServerEndpoint.java | /**
* 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.cxf.dosgi.common.endpoint;
import org.apache.aries.rsa.spi.Endpoint;
import org.apache.cxf.endpoint.Server;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
public class ServerEndpoint implements Endpoint {
private EndpointDescription desc;
private Server server;
public ServerEndpoint(EndpointDescription desc, Server server) {
this.desc = desc;
this.server = server;
}
public Server getServer() {
return this.server;
}
@Override
public void close() {
this.server.destroy();
}
@Override
public EndpointDescription description() {
return this.desc;
}
}
| 1,035 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/api/IntentsProvider.java | /**
* 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.cxf.dosgi.common.api;
import java.util.List;
/**
* Returns a list of CXF extension objects that can define the same things a intents
*/
public interface IntentsProvider {
List<?> getIntents();
}
| 1,036 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/handlers/BaseDistributionProvider.java | /**
* 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.cxf.dosgi.common.handlers;
import static org.apache.cxf.dosgi.common.util.PropertyHelper.getMultiValueProperty;
import java.util.Collection;
import java.util.Map;
import org.apache.aries.rsa.spi.DistributionProvider;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.dosgi.common.httpservice.HttpServiceManager;
import org.apache.cxf.dosgi.common.intent.IntentManager;
import org.apache.cxf.endpoint.AbstractEndpointFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.RemoteConstants;
public abstract class BaseDistributionProvider implements DistributionProvider {
protected IntentManager intentManager;
protected HttpServiceManager httpServiceManager;
protected boolean configTypeSupported(Map<String, Object> endpointProps, String configType) {
Collection<String> configs = getMultiValueProperty(endpointProps.get(RemoteConstants.SERVICE_EXPORTED_CONFIGS));
return configs == null || configs.isEmpty() || configs.contains(configType);
}
protected EndpointDescription createEndpointDesc(Map<String, Object> props,
String[] importedConfigs,
String addressPropName,
String address,
Collection<String> intents) {
props.put(RemoteConstants.SERVICE_IMPORTED_CONFIGS, importedConfigs);
props.put(addressPropName, address);
props.put(RemoteConstants.SERVICE_INTENTS, intents);
props.put(RemoteConstants.ENDPOINT_ID, address);
return new EndpointDescription(props);
}
protected Bus createBus(Long sid, BundleContext callingContext, String contextRoot,
Map<String, Object> endpointProps) {
Bus bus = BusFactory.newInstance().createBus();
for (Map.Entry<String, Object> prop : endpointProps.entrySet()) {
if (prop.getKey().startsWith("cxf.bus.prop.")) {
bus.setProperty(prop.getKey().substring("cxf.bus.prop.".length()), prop.getValue());
}
}
if (contextRoot != null) {
httpServiceManager.registerServlet(bus, contextRoot, callingContext, sid);
}
return bus;
}
protected void addContextProperties(AbstractEndpointFactory factory, Map<String, Object> sd, String propName) {
@SuppressWarnings("unchecked")
Map<String, Object> props = (Map<String, Object>)sd.get(propName);
if (props != null) {
factory.getProperties(true).putAll(props);
}
}
}
| 1,037 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/httpservice/SecurityDelegatingHttpContext.java | /**
* 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.cxf.dosgi.common.httpservice;
import java.io.IOException;
import java.net.URL;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* An HttpContext that delegates to another HttpContext for all things other than security. This implementation handles
* security by delegating to a {@link FilterChain} based on the set of {@link Filter}s registered with a
* {@link #FILTER_PROP} property.
* </p>
* <p>
* If the {@link BundleContext} contains a {@link #FILTER_REQUIRED_PROP} property with value "true", requests will not
* be allowed until at least one {@link Filter} with a {@link #FILTER_PROP} property is registered.
* </p>
*/
class SecurityDelegatingHttpContext implements HttpContext {
public static final String FILTER_PROP = "org.apache.cxf.httpservice.filter";
public static final String FILTER_REQUIRED_PROP = "org.apache.cxf.httpservice.requirefilter";
private static final Logger LOG = LoggerFactory.getLogger(SecurityDelegatingHttpContext.class);
private static final String FILTER_FILTER = "(" + FILTER_PROP + "=*)";
BundleContext bundleContext;
HttpContext delegate;
boolean requireFilter;
SecurityDelegatingHttpContext(BundleContext bundleContext, HttpContext delegate) {
this.bundleContext = bundleContext;
this.delegate = delegate;
requireFilter = Boolean.TRUE.toString().equalsIgnoreCase(bundleContext.getProperty(FILTER_REQUIRED_PROP));
}
@Override
public String getMimeType(String name) {
return delegate.getMimeType(name);
}
@Override
public URL getResource(String name) {
return delegate.getResource(name);
}
@Override
@SuppressWarnings({
"unchecked", "rawtypes"
})
public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException {
ServiceReference[] refs;
try {
refs = bundleContext.getServiceReferences(Filter.class.getName(), FILTER_FILTER);
} catch (InvalidSyntaxException e) {
LOG.warn(e.getMessage(), e);
return false;
}
if (refs == null || refs.length == 0) {
LOG.info("No filter registered.");
return !requireFilter;
}
Filter[] filters = new Filter[refs.length];
try {
for (int i = 0; i < refs.length; i++) {
filters[i] = (Filter)bundleContext.getService(refs[i]);
}
try {
new Chain(filters).doFilter(request, response);
return !response.isCommitted();
} catch (ServletException e) {
LOG.warn(e.getMessage(), e);
return false;
}
} finally {
for (int i = 0; i < refs.length; i++) {
if (filters[i] != null) {
bundleContext.ungetService(refs[i]);
}
}
}
}
}
/**
* A {@link FilterChain} composed of {@link Filter}s with the
*/
class Chain implements FilterChain {
private static final Logger LOG = LoggerFactory.getLogger(Chain.class);
int current;
final Filter[] filters;
Chain(Filter[] filters) {
this.filters = filters;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
if (current < filters.length && !response.isCommitted()) {
Filter filter = filters[current++];
LOG.info("doFilter() on {}", filter);
filter.doFilter(request, response, this);
}
}
}
| 1,038 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/httpservice/HttpServiceManager.java | /**
* 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.cxf.dosgi.common.httpservice;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import org.apache.cxf.Bus;
import org.apache.cxf.transport.http.DestinationRegistry;
import org.apache.cxf.transport.http.DestinationRegistryImpl;
import org.apache.cxf.transport.servlet.CXFNonSpringServlet;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component //
(//
name = "org.apache.cxf.dosgi.http", //
service = HttpServiceManager.class //
)
public class HttpServiceManager {
/**
* Prefix to create an absolute URL from a relative URL. See HttpServiceManager.getAbsoluteAddress
* Defaults to: http://localhost:8181
*/
public static final String KEY_HTTP_BASE = "httpBase";
public static final String KEY_CXF_SERVLET_ALIAS = "cxfServletAlias";
public static final String DEFAULT_CXF_SERVLET_ALIAS = "/cxf";
private static final Logger LOG = LoggerFactory.getLogger(HttpServiceManager.class);
private Map<Long, String> exportedAliases = Collections.synchronizedMap(new HashMap<Long, String>());
private String httpBase;
private String cxfServletAlias;
private HttpService httpService;
private BundleContext context;
@Activate
public void activate(ComponentContext compContext) {
Dictionary<String, Object> config = compContext.getProperties();
initFromConfig(config);
this.context = compContext.getBundleContext();
}
public void initFromConfig(Dictionary<String, Object> config) {
if (config == null) {
config = new Hashtable<>();
}
this.httpBase = getWithDefault(config.get(KEY_HTTP_BASE), "http://localhost:8181");
this.cxfServletAlias = getWithDefault(config.get(KEY_CXF_SERVLET_ALIAS), "/cxf");
}
private String getWithDefault(Object value, String defaultValue) {
return value == null ? defaultValue : value.toString();
}
public Bus registerServlet(Bus bus, String contextRoot, BundleContext callingContext, Long sid) {
bus.setExtension(new DestinationRegistryImpl(), DestinationRegistry.class);
CXFNonSpringServlet cxf = new CXFNonSpringServlet();
cxf.setBus(bus);
try {
HttpContext httpContext1 = httpService.createDefaultHttpContext();
HttpContext httpContext = new SecurityDelegatingHttpContext(callingContext, httpContext1);
httpService.registerServlet(contextRoot, cxf, new Hashtable<String, String>(), httpContext);
registerUnexportHook(sid, contextRoot);
LOG.info("Successfully registered CXF DOSGi servlet at " + contextRoot);
} catch (Exception e) {
throw new ServiceException("CXF DOSGi: problem registering CXF HTTP Servlet", e);
}
return bus;
}
/**
* This listens for service removal events and "un-exports" the service from the HttpService.
*
* @param sid the service id to track
* @param alias the HTTP servlet context alias
*/
private void registerUnexportHook(Long sid, String alias) {
LOG.debug("Registering service listener for service with ID {}", sid);
String previous = exportedAliases.put(sid, alias);
if (previous != null) {
LOG.warn("Overwriting service export for service with ID {}", sid);
}
try {
Filter f = context.createFilter("(" + org.osgi.framework.Constants.SERVICE_ID + "=" + sid + ")");
if (f != null) {
context.addServiceListener(new UnregisterListener(), f.toString());
} else {
LOG.warn("Service listener could not be started. The service will not be automatically unexported.");
}
} catch (InvalidSyntaxException e) {
LOG.warn("Service listener could not be started. The service will not be automatically unexported.",
e);
}
}
public String getDefaultAddress(Class<?> type) {
return "/" + type.getName().replace('.', '/');
}
public String getAbsoluteAddress(String contextRoot, String endpointAddress) {
if (endpointAddress.startsWith("http")) {
return endpointAddress;
}
String effContextRoot = contextRoot == null ? cxfServletAlias : contextRoot;
return this.httpBase + effContextRoot + endpointAddress;
}
private final class UnregisterListener implements ServiceListener {
@Override
public void serviceChanged(ServiceEvent event) {
if (!(event.getType() == ServiceEvent.UNREGISTERING)) {
return;
}
final ServiceReference<?> sref = event.getServiceReference();
final Long sid = (Long)sref.getProperty(org.osgi.framework.Constants.SERVICE_ID);
final String alias = exportedAliases.remove(sid);
if (alias == null) {
LOG.error("Unable to unexport HTTP servlet for service class '{}',"
+ " service-id {}: no servlet alias found",
sref.getProperty(org.osgi.framework.Constants.OBJECTCLASS), sid);
return;
}
LOG.debug("Unexporting HTTP servlet for alias '{}'", alias);
try {
httpService.unregister(alias);
} catch (Exception e) {
LOG.warn("An exception occurred while unregistering service for HTTP servlet alias '{}'",
alias, e);
}
}
}
public void setContext(BundleContext context) {
this.context = context;
}
@Reference
public void setHttpService(HttpService httpService) {
this.httpService = httpService;
}
}
| 1,039 |
0 | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common | Create_ds/cxf-dosgi/common/src/main/java/org/apache/cxf/dosgi/common/policy/Exporter.java | /**
* 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.cxf.dosgi.common.policy;
import static org.osgi.service.remoteserviceadmin.RemoteConstants.SERVICE_EXPORTED_CONFIGS;
import static org.osgi.service.remoteserviceadmin.RemoteConstants.SERVICE_EXPORTED_INTERFACES;
import java.util.HashMap;
import java.util.Map;
import org.apache.aries.rsa.spi.ExportPolicy;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.annotations.Component;
/**
* This export policy allows to export services with just the rs or ws address property.
* This policy must be configured in the Aries RSA TopologyManager config to be activated.
*/
@Component //
(//
immediate = true, //
property = "name=cxf" //
)
public class Exporter implements ExportPolicy {
@Override
public Map<String, String> additionalParameters(ServiceReference<?> sref) {
Map<String, String> params = new HashMap<>();
if (sref.getProperty("org.apache.cxf.rs.address") != null) {
setDefault(sref, params, SERVICE_EXPORTED_INTERFACES, "*");
setDefault(sref, params, SERVICE_EXPORTED_CONFIGS, "org.apache.cxf.rs");
}
if (sref.getProperty("org.apache.cxf.ws.address") != null) {
setDefault(sref, params, SERVICE_EXPORTED_INTERFACES, "*");
setDefault(sref, params, SERVICE_EXPORTED_CONFIGS, "org.apache.cxf.ws");
}
return params;
}
private void setDefault(ServiceReference<?> sref, Map<String, String> params, String key, String value) {
if (sref.getProperty(key) == null) {
params.put(key, value);
}
}
}
| 1,040 |
0 | Create_ds/cxf-dosgi/provider-ws/src/test/java/org/apache/cxf/dosgi/dsw/handlers | Create_ds/cxf-dosgi/provider-ws/src/test/java/org/apache/cxf/dosgi/dsw/handlers/jaxws/MyJaxWsEchoServiceImpl.java | /**
* 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.cxf.dosgi.dsw.handlers.jaxws;
public class MyJaxWsEchoServiceImpl implements MyJaxWsEchoService {
@Override
public String echo(String message) {
return message;
}
} | 1,041 |
0 | Create_ds/cxf-dosgi/provider-ws/src/test/java/org/apache/cxf/dosgi/dsw/handlers | Create_ds/cxf-dosgi/provider-ws/src/test/java/org/apache/cxf/dosgi/dsw/handlers/jaxws/MyJaxWsEchoService.java | /**
* 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.cxf.dosgi.dsw.handlers.jaxws;
import javax.jws.WebService;
@WebService
public interface MyJaxWsEchoService {
String echo(String message);
} | 1,042 |
0 | Create_ds/cxf-dosgi/provider-ws/src/test/java/org/apache/cxf/dosgi/dsw/handlers | Create_ds/cxf-dosgi/provider-ws/src/test/java/org/apache/cxf/dosgi/dsw/handlers/simple/MySimpleEchoServiceImpl.java | /**
* 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.cxf.dosgi.dsw.handlers.simple;
public class MySimpleEchoServiceImpl implements MySimpleEchoService {
@Override
public String echo(String message) {
return message;
}
} | 1,043 |
0 | Create_ds/cxf-dosgi/provider-ws/src/test/java/org/apache/cxf/dosgi/dsw/handlers | Create_ds/cxf-dosgi/provider-ws/src/test/java/org/apache/cxf/dosgi/dsw/handlers/simple/MySimpleEchoService.java | /**
* 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.cxf.dosgi.dsw.handlers.simple;
public interface MySimpleEchoService {
String echo(String message);
} | 1,044 |
0 | Create_ds/cxf-dosgi/provider-ws/src/test/java/org/apache/cxf/dosgi/dsw/handlers | Create_ds/cxf-dosgi/provider-ws/src/test/java/org/apache/cxf/dosgi/dsw/handlers/ws/PojoConfigurationTypeHandlerTest.java | /**
* 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.cxf.dosgi.dsw.handlers.ws;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.xml.namespace.QName;
import org.apache.aries.rsa.spi.Endpoint;
import org.apache.aries.rsa.util.EndpointHelper;
import org.apache.cxf.dosgi.common.endpoint.ServerEndpoint;
import org.apache.cxf.dosgi.common.httpservice.HttpServiceManager;
import org.apache.cxf.dosgi.common.intent.IntentManager;
import org.apache.cxf.dosgi.common.intent.impl.IntentManagerImpl;
import org.apache.cxf.dosgi.dsw.handlers.jaxws.MyJaxWsEchoService;
import org.apache.cxf.dosgi.dsw.handlers.simple.MySimpleEchoService;
import org.apache.cxf.dosgi.dsw.handlers.simple.MySimpleEchoServiceImpl;
import org.apache.cxf.endpoint.EndpointImpl;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.frontend.ClientFactoryBean;
import org.apache.cxf.frontend.ClientProxyFactoryBean;
import org.apache.cxf.frontend.ServerFactoryBean;
import org.apache.cxf.jaxws.support.JaxWsEndpointImpl;
import org.apache.cxf.transport.Destination;
import org.apache.cxf.ws.addressing.AttributedURIType;
import org.apache.cxf.ws.addressing.EndpointReferenceType;
import org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.easymock.IMocksControl;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.RemoteConstants;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class PojoConfigurationTypeHandlerTest {
@Test
public void testGetPojoAddressEndpointURI() {
IntentManager intentManager = new IntentManagerImpl();
WsProvider handler = new WsProvider();
handler.setIntentManager(intentManager);
handler.setHttpServiceManager(dummyHttpServiceManager());
Map<String, Object> sd = new HashMap<>();
String url = "http://somewhere:1234/blah";
sd.put(RemoteConstants.ENDPOINT_ID, url);
assertEquals(url, handler.getServerAddress(sd, String.class));
}
private HttpServiceManager dummyHttpServiceManager() {
return new HttpServiceManager();
}
@Test
public void testGetPojoAddressEndpointCxf() {
IntentManager intentManager = new IntentManagerImpl();
WsProvider handler = new WsProvider();
handler.setIntentManager(intentManager);
handler.setHttpServiceManager(dummyHttpServiceManager());
Map<String, Object> sd = new HashMap<>();
String url = "http://somewhere:29/boo";
sd.put("org.apache.cxf.ws.address", url);
assertEquals(url, handler.getServerAddress(sd, String.class));
}
@Test
public void testGetDefaultPojoAddress() {
IntentManager intentManager = new IntentManagerImpl();
WsProvider handler = new WsProvider();
handler.setIntentManager(intentManager);
handler.setHttpServiceManager(dummyHttpServiceManager());
Map<String, Object> sd = new HashMap<>();
assertEquals("/java/lang/String", handler.getServerAddress(sd, String.class));
}
// todo: add test for data bindings
@Test
public void testCreateProxy() {
IMocksControl c = EasyMock.createNiceControl();
BundleContext bc1 = c.createMock(BundleContext.class);
BundleContext requestingContext = c.createMock(BundleContext.class);
final ClientProxyFactoryBean cpfb = c.createMock(ClientProxyFactoryBean.class);
ReflectionServiceFactoryBean sf = c.createMock(ReflectionServiceFactoryBean.class);
EasyMock.expect(cpfb.getServiceFactory()).andReturn(sf).anyTimes();
ClientFactoryBean cf = c.createMock(ClientFactoryBean.class);
EasyMock.expect(cpfb.getClientFactoryBean()).andReturn(cf).anyTimes();
IntentManager intentManager = new IntentManagerImpl();
WsProvider p = new WsProvider() {
@Override
protected ClientProxyFactoryBean createClientProxyFactoryBean(Map<String, Object> sd,
Class<?> iClass) {
return cpfb;
}
};
p.setIntentManager(intentManager);
p.setHttpServiceManager(dummyHttpServiceManager());
p.activate(bc1);
Class<?>[] exportedInterfaces = new Class[] {Runnable.class};
Map<String, Object> props = new HashMap<>();
props.put(RemoteConstants.ENDPOINT_ID, "http://google.de/");
EndpointHelper.addObjectClass(props, exportedInterfaces);
props.put(RemoteConstants.SERVICE_IMPORTED_CONFIGS, new String[] {"my.config"});
EndpointDescription endpoint = new EndpointDescription(props);
cpfb.setAddress((String)EasyMock.eq(props.get(RemoteConstants.ENDPOINT_ID)));
EasyMock.expectLastCall().atLeastOnce();
cpfb.setServiceClass(EasyMock.eq(Runnable.class));
EasyMock.expectLastCall().atLeastOnce();
c.replay();
Object proxy = p.importEndpoint(null, requestingContext, exportedInterfaces, endpoint);
assertNotNull(proxy);
assertTrue("Proxy is not of the requested type! ", proxy instanceof Runnable);
c.verify();
}
@Test
public void testCreateServerWithAddressProperty() {
BundleContext dswContext = EasyMock.createNiceMock(BundleContext.class);
EasyMock.replay(dswContext);
String myService = "Hi";
final ServerFactoryBean sfb = createMockServerFactoryBean();
IntentManager intentManager = new IntentManagerImpl();
WsProvider p = new WsProvider() {
@Override
protected ServerFactoryBean createServerFactoryBean(Map<String, Object> sd, Class<?> iClass) {
return sfb;
}
};
p.activate(dswContext);
p.setIntentManager(intentManager);
p.setHttpServiceManager(dummyHttpServiceManager());
BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class);
EasyMock.replay(bundleContext);
Class<?>[] exportedInterface = new Class[] {String.class
};
Map<String, Object> props = new HashMap<>();
EndpointHelper.addObjectClass(props, exportedInterface);
props.put(WsConstants.WS_ADDRESS_PROPERTY, "http://alternate_host:80/myString");
Endpoint exportResult = p.exportService(myService, bundleContext, props, exportedInterface);
Map<String, Object> edProps = exportResult.description().getProperties();
assertNotNull(edProps.get(RemoteConstants.SERVICE_IMPORTED_CONFIGS));
assertEquals(1, ((String[])edProps.get(RemoteConstants.SERVICE_IMPORTED_CONFIGS)).length);
assertEquals(WsConstants.WS_CONFIG_TYPE,
((String[])edProps.get(RemoteConstants.SERVICE_IMPORTED_CONFIGS))[0]);
assertEquals("http://alternate_host:80/myString", edProps.get(RemoteConstants.ENDPOINT_ID));
}
@Test
public void testAddressing() {
runAddressingTest(new HashMap<String, Object>(), "http://localhost:9000/java/lang/Runnable");
Map<String, Object> p1 = new HashMap<>();
p1.put("org.apache.cxf.ws.address", "http://somewhere");
runAddressingTest(p1, "http://somewhere");
Map<String, Object> p3 = new HashMap<>();
p3.put("org.apache.cxf.ws.port", 65535);
runAddressingTest(p3, "http://localhost:65535/java/lang/Runnable");
Map<String, Object> p4 = new HashMap<>();
p4.put("org.apache.cxf.ws.port", "8181");
runAddressingTest(p4, "http://localhost:8181/java/lang/Runnable");
}
private void runAddressingTest(Map<String, Object> properties, String expectedAddress) {
Class<?>[] exportedInterface = new Class[] {Runnable.class};
EndpointHelper.addObjectClass(properties, exportedInterface);
BundleContext dswContext = EasyMock.createNiceMock(BundleContext.class);
String expectedUUID = UUID.randomUUID().toString();
EasyMock.expect(dswContext.getProperty(org.osgi.framework.Constants.FRAMEWORK_UUID))
.andReturn(expectedUUID);
EasyMock.replay(dswContext);
IntentManager intentManager = new IntentManagerImpl();
WsProvider handler = new WsProvider() {
@Override
protected Endpoint createServerFromFactory(ServerFactoryBean factory, EndpointDescription epd) {
return new ServerEndpoint(epd, null);
}
};
handler.setIntentManager(intentManager);
handler.setHttpServiceManager(dummyHttpServiceManager());
handler.activate(dswContext);
Runnable myService = new Runnable() {
@Override
public void run() {
}
};
BundleContext bundleContext = EasyMock.createNiceMock(BundleContext.class);
EasyMock.replay(bundleContext);
Endpoint result = handler.exportService(myService, bundleContext, properties, exportedInterface);
Map<String, Object> props = result.description().getProperties();
assertEquals(expectedAddress, props.get("org.apache.cxf.ws.address"));
assertArrayEquals(new String[] {"org.apache.cxf.ws"},
(String[])props.get(RemoteConstants.SERVICE_IMPORTED_CONFIGS));
assertArrayEquals(new String[] {"java.lang.Runnable"},
(String[])props.get(org.osgi.framework.Constants.OBJECTCLASS));
}
@Test
public void testCreateServerException() {
BundleContext dswContext = EasyMock.createNiceMock(BundleContext.class);
EasyMock.replay(dswContext);
IntentManager intentManager = new IntentManagerImpl();
WsProvider handler = new WsProvider() {
@Override
protected Endpoint createServerFromFactory(ServerFactoryBean factory, EndpointDescription epd) {
throw new TestException();
}
};
handler.setIntentManager(intentManager);
handler.setHttpServiceManager(dummyHttpServiceManager());
handler.activate(dswContext);
Class[] exportedInterfaces = {Runnable.class};
Map<String, Object> props = new HashMap<>();
EndpointHelper.addObjectClass(props, exportedInterfaces);
Runnable myService = EasyMock.createMock(Runnable.class);
EasyMock.replay(myService);
try {
handler.exportService(myService, null, props, exportedInterfaces);
fail("Expected TestException");
} catch (TestException e) {
// Expected
} catch (RuntimeException re) {
if (!(re.getCause() instanceof TestException)) {
fail("Expected TestException");
}
}
}
private ServerFactoryBean createMockServerFactoryBean() {
ReflectionServiceFactoryBean sf = EasyMock.createNiceMock(ReflectionServiceFactoryBean.class);
EasyMock.replay(sf);
final StringBuilder serverURI = new StringBuilder();
ServerFactoryBean sfb = EasyMock.createNiceMock(ServerFactoryBean.class);
Server server = createMockServer(sfb);
EasyMock.expect(sfb.getServiceFactory()).andReturn(sf).anyTimes();
EasyMock.expect(sfb.create()).andReturn(server);
sfb.setAddress((String)EasyMock.anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() {
serverURI.setLength(0);
serverURI.append(EasyMock.getCurrentArguments()[0]);
return null;
}
});
EasyMock.expect(sfb.getAddress()).andAnswer(new IAnswer<String>() {
@Override
public String answer() {
return serverURI.toString();
}
});
EasyMock.replay(sfb);
return sfb;
}
private Server createMockServer(final ServerFactoryBean sfb) {
AttributedURIType addr = EasyMock.createMock(AttributedURIType.class);
EasyMock.expect(addr.getValue()).andAnswer(new IAnswer<String>() {
@Override
public String answer() {
return sfb.getAddress();
}
});
EasyMock.replay(addr);
EndpointReferenceType er = EasyMock.createMock(EndpointReferenceType.class);
EasyMock.expect(er.getAddress()).andReturn(addr);
EasyMock.replay(er);
Destination destination = EasyMock.createMock(Destination.class);
EasyMock.expect(destination.getAddress()).andReturn(er);
EasyMock.replay(destination);
Server server = EasyMock.createNiceMock(Server.class);
EasyMock.expect(server.getDestination()).andReturn(destination);
EasyMock.replay(server);
return server;
}
@Test
public void testCreateEndpointProps() {
BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
EasyMock.expect(bc.getProperty("org.osgi.framework.uuid")).andReturn("some_uuid1");
EasyMock.replay(bc);
IntentManager intentManager = new IntentManagerImpl();
WsProvider pch = new WsProvider();
pch.setIntentManager(intentManager);
pch.setHttpServiceManager(dummyHttpServiceManager());
pch.activate(bc);
Class<?>[] exportedInterfaces = new Class[] {String.class};
Map<String, Object> sd = new HashMap<>();
sd.put(org.osgi.framework.Constants.SERVICE_ID, 42);
EndpointHelper.addObjectClass(sd, exportedInterfaces);
List<String> intents = Arrays.asList("my_intent", "your_intent");
EndpointDescription epd = pch.createEndpointDesc(sd,
new String[] {"org.apache.cxf.ws"},
"http://localhost:12345",
intents);
assertEquals("http://localhost:12345", epd.getId());
assertEquals(Arrays.asList("java.lang.String"), epd.getInterfaces());
assertEquals(Arrays.asList("org.apache.cxf.ws"), epd.getConfigurationTypes());
assertEquals(Arrays.asList("my_intent", "your_intent"), epd.getIntents());
assertEquals(new Version("0.0.0"), epd.getPackageVersion("java.lang"));
}
@Test
public void testCreateJaxWsEndpointWithoutIntents() {
IMocksControl c = EasyMock.createNiceControl();
BundleContext dswBC = c.createMock(BundleContext.class);
IntentManager intentManager = new IntentManagerImpl();
WsProvider handler = new WsProvider();
handler.setIntentManager(intentManager);
handler.setHttpServiceManager(dummyHttpServiceManager());
handler.activate(dswBC);
Class<?>[] exportedInterfaces = new Class[] {MyJaxWsEchoService.class};
Map<String, Object> sd = new HashMap<>();
sd.put(WsConstants.WS_ADDRESS_PROPERTY, "/somewhere");
EndpointHelper.addObjectClass(sd, exportedInterfaces);
BundleContext serviceBC = c.createMock(BundleContext.class);
Object myService = c.createMock(MyJaxWsEchoService.class);
c.replay();
ServerEndpoint serverWrapper = (ServerEndpoint)handler.exportService(myService, serviceBC, sd,
exportedInterfaces);
c.verify();
org.apache.cxf.endpoint.Endpoint ep = serverWrapper.getServer().getEndpoint();
QName bindingName = ep.getEndpointInfo().getBinding().getName();
assertEquals(JaxWsEndpointImpl.class, ep.getClass());
assertEquals(new QName("http://jaxws.handlers.dsw.dosgi.cxf.apache.org/",
"MyJaxWsEchoServiceServiceSoapBinding"),
bindingName);
}
@Test
public void testCreateSimpleEndpointWithoutIntents() {
IMocksControl c = EasyMock.createNiceControl();
BundleContext dswBC = c.createMock(BundleContext.class);
IntentManager intentManager = new IntentManagerImpl();
WsProvider handler = new WsProvider();
handler.setIntentManager(intentManager);
handler.setHttpServiceManager(dummyHttpServiceManager());
handler.activate(dswBC);
Map<String, Object> sd = new HashMap<>();
sd.put(Constants.OBJECTCLASS, new String[]{MySimpleEchoService.class.getName()});
sd.put(WsConstants.WS_ADDRESS_PROPERTY, "/somewhere_else");
BundleContext serviceBC = c.createMock(BundleContext.class);
c.replay();
Class<?>[] ifaces = new Class[] {MySimpleEchoService.class};
MySimpleEchoServiceImpl service = new MySimpleEchoServiceImpl();
ServerEndpoint serverWrapper = (ServerEndpoint)handler.exportService(service, serviceBC, sd, ifaces);
c.verify();
org.apache.cxf.endpoint.Endpoint ep = serverWrapper.getServer().getEndpoint();
QName bindingName = ep.getEndpointInfo().getBinding().getName();
assertEquals(EndpointImpl.class, ep.getClass());
assertEquals(new QName("http://simple.handlers.dsw.dosgi.cxf.apache.org/",
"MySimpleEchoServiceSoapBinding"),
bindingName);
}
@SuppressWarnings("serial")
public static class TestException extends RuntimeException {
}
}
| 1,045 |
0 | Create_ds/cxf-dosgi/provider-ws/src/main/java/org/apache/cxf/dosgi/dsw/handlers | Create_ds/cxf-dosgi/provider-ws/src/main/java/org/apache/cxf/dosgi/dsw/handlers/ws/WsdlSupport.java | /**
* 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.cxf.dosgi.dsw.handlers.ws;
import java.net.URL;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.cxf.common.util.PackageUtils;
import org.apache.cxf.dosgi.common.util.PropertyHelper;
import org.apache.cxf.frontend.AbstractWSDLBasedEndpointFactory;
import org.osgi.framework.BundleContext;
public final class WsdlSupport {
private WsdlSupport() {
}
public static void setWsdlProperties(AbstractWSDLBasedEndpointFactory factory, //
BundleContext context, //
Map<String, Object> sd) {
String location = PropertyHelper.getProperty(sd, WsConstants.WS_WSDL_LOCATION);
if (location != null) {
URL wsdlURL = context.getBundle().getResource(location);
if (wsdlURL != null) {
factory.setWsdlURL(wsdlURL.toString());
}
QName serviceName = getServiceQName(null, sd,
WsConstants.WS_WSDL_SERVICE_NAMESPACE,
WsConstants.WS_WSDL_SERVICE_NAME);
if (serviceName != null) {
factory.setServiceName(serviceName);
QName portName = getPortQName(serviceName.getNamespaceURI(), sd,
WsConstants.WS_WSDL_PORT_NAME);
if (portName != null) {
factory.setEndpointName(portName);
}
}
}
}
protected static QName getServiceQName(Class<?> iClass, Map<String, Object> sd, String nsPropName,
String namePropName) {
String serviceNs = PropertyHelper.getProperty(sd, nsPropName);
String serviceName = PropertyHelper.getProperty(sd, namePropName);
if (iClass == null && (serviceNs == null || serviceName == null)) {
return null;
}
if (serviceNs == null) {
serviceNs = PackageUtils.getNamespace(PackageUtils.getPackageName(iClass));
}
if (serviceName == null) {
serviceName = iClass.getSimpleName();
}
return new QName(serviceNs, serviceName);
}
protected static QName getPortQName(String ns, Map<String, Object> sd, String propName) {
String portName = PropertyHelper.getProperty(sd, propName);
if (portName == null) {
return null;
}
return new QName(ns, portName);
}
}
| 1,046 |
0 | Create_ds/cxf-dosgi/provider-ws/src/main/java/org/apache/cxf/dosgi/dsw/handlers | Create_ds/cxf-dosgi/provider-ws/src/main/java/org/apache/cxf/dosgi/dsw/handlers/ws/WsConstants.java | /**
* 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.cxf.dosgi.dsw.handlers.ws;
public final class WsConstants {
public static final String WS_CONFIG_TYPE = "org.apache.cxf.ws";
public static final String WS_ADDRESS_PROPERTY = WS_CONFIG_TYPE + ".address";
public static final String WS_PORT_PROPERTY = WS_CONFIG_TYPE + ".port";
public static final String WS_HTTP_SERVICE_CONTEXT = WS_CONFIG_TYPE + ".httpservice.context";
public static final String WS_CONTEXT_PROPS_PROP_KEY = WS_CONFIG_TYPE + ".context.properties";
public static final String WS_WSDL_SERVICE_NAMESPACE = WS_CONFIG_TYPE + ".service.ns";
public static final String WS_WSDL_SERVICE_NAME = WS_CONFIG_TYPE + ".service.name";
public static final String WS_WSDL_PORT_NAME = WS_CONFIG_TYPE + ".port.name";
public static final String WS_WSDL_LOCATION = WS_CONFIG_TYPE + ".wsdl.location";
private WsConstants() {
// never constructed
}
}
| 1,047 |
0 | Create_ds/cxf-dosgi/provider-ws/src/main/java/org/apache/cxf/dosgi/dsw/handlers | Create_ds/cxf-dosgi/provider-ws/src/main/java/org/apache/cxf/dosgi/dsw/handlers/ws/WsProvider.java | /**
* 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.cxf.dosgi.dsw.handlers.ws;
import static org.osgi.service.remoteserviceadmin.RemoteConstants.REMOTE_CONFIGS_SUPPORTED;
import static org.osgi.service.remoteserviceadmin.RemoteConstants.REMOTE_INTENTS_SUPPORTED;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jws.WebService;
import org.apache.aries.rsa.spi.DistributionProvider;
import org.apache.aries.rsa.spi.Endpoint;
import org.apache.aries.rsa.spi.IntentUnsatisfiedException;
import org.apache.cxf.Bus;
import org.apache.cxf.aegis.databinding.AegisDatabinding;
import org.apache.cxf.binding.BindingConfiguration;
import org.apache.cxf.binding.soap.SoapBindingConfiguration;
import org.apache.cxf.databinding.DataBinding;
import org.apache.cxf.dosgi.common.api.IntentsProvider;
import org.apache.cxf.dosgi.common.endpoint.ServerEndpoint;
import org.apache.cxf.dosgi.common.handlers.BaseDistributionProvider;
import org.apache.cxf.dosgi.common.httpservice.HttpServiceManager;
import org.apache.cxf.dosgi.common.intent.IntentManager;
import org.apache.cxf.dosgi.common.proxy.ProxyFactory;
import org.apache.cxf.dosgi.common.util.PropertyHelper;
import org.apache.cxf.endpoint.AbstractEndpointFactory;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.feature.Feature;
import org.apache.cxf.frontend.ClientProxyFactoryBean;
import org.apache.cxf.frontend.ServerFactoryBean;
import org.apache.cxf.jaxb.JAXBDataBinding;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.RemoteConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(configurationPid = "cxf-dsw", property = //
{//
REMOTE_CONFIGS_SUPPORTED + "=" + WsConstants.WS_CONFIG_TYPE,
REMOTE_INTENTS_SUPPORTED + "="
})
public class WsProvider extends BaseDistributionProvider implements DistributionProvider {
private static final Logger LOG = LoggerFactory.getLogger(WsProvider.class);
protected BundleContext bundleContext;
@Reference
public void setHttpServiceManager(HttpServiceManager httpServiceManager) {
this.httpServiceManager = httpServiceManager;
}
@Reference
public void setIntentManager(IntentManager intentManager) {
this.intentManager = intentManager;
}
@Activate
public void activate(BundleContext context) {
this.bundleContext = context;
}
@Override
public String[] getSupportedTypes() {
return new String[] {WsConstants.WS_CONFIG_TYPE};
}
@Override
@SuppressWarnings("rawtypes")
public Object importEndpoint(ClassLoader consumerLoader,
BundleContext consumerContext,
Class[] interfaces,
EndpointDescription endpoint) throws IntentUnsatisfiedException {
if (interfaces.length > 1) {
throw new IllegalArgumentException("Multiple interfaces are not supported by this provider");
}
Class<?> iClass = interfaces[0];
Map<String, Object> sd = endpoint.getProperties();
String address = getClientAddress(sd);
LOG.info("Creating a " + iClass.getName() + " client, endpoint address is " + address);
try {
ClientProxyFactoryBean factory = createClientProxyFactoryBean(sd, iClass);
factory.setDataBinding(getDataBinding(sd, iClass));
factory.setBindingConfig(new SoapBindingConfiguration());
factory.setServiceClass(iClass);
factory.setAddress(address);
addContextProperties(factory.getClientFactoryBean(), sd, WsConstants.WS_CONTEXT_PROPS_PROP_KEY);
WsdlSupport.setWsdlProperties(factory.getClientFactoryBean(), bundleContext, sd);
applyIntents(sd, factory);
return ProxyFactory.create(factory.create(), iClass);
} catch (Exception e) {
throw new RuntimeException("proxy creation failed", e);
}
}
private void applyIntents(Map<String, Object> sd, ClientProxyFactoryBean factory) {
Set<String> intentNames = intentManager.getImported(sd);
List<Object> intents = intentManager.getRequiredIntents(intentNames);
List<Feature> features = intentManager.getIntents(Feature.class, intents);
factory.setFeatures(features);
DataBinding dataBinding = intentManager.getIntent(DataBinding.class, intents);
if (dataBinding != null) {
factory.setDataBinding(dataBinding);
}
BindingConfiguration binding = copy(intentManager.getIntent(BindingConfiguration.class, intents));
if (binding != null) {
factory.setBindingConfig(binding);
}
}
private BindingConfiguration copy(BindingConfiguration bindingCfg) {
return bindingCfg instanceof SoapBindingConfiguration
? copy((SoapBindingConfiguration)bindingCfg) : bindingCfg;
}
private SoapBindingConfiguration copy(SoapBindingConfiguration intent) {
SoapBindingConfiguration bindingCfg = new SoapBindingConfiguration();
bindingCfg.setVersion(intent.getVersion());
bindingCfg.setTransportURI(intent.getTransportURI());
bindingCfg.setUse(intent.getUse());
if (intent.isSetStyle()) {
bindingCfg.setStyle(intent.getStyle());
}
bindingCfg.setMtomEnabled(intent.isMtomEnabled());
bindingCfg.setBindingName(intent.getBindingName());
bindingCfg.setBindingNamePostfix(intent.getBindingNamePostfix());
return bindingCfg;
}
@Override
@SuppressWarnings("rawtypes")
public Endpoint exportService(Object serviceO,
BundleContext serviceContext,
Map<String, Object> endpointProps,
Class[] exportedInterfaces) throws IntentUnsatisfiedException {
if (!configTypeSupported(endpointProps, WsConstants.WS_CONFIG_TYPE)) {
return null;
}
Class<?> iClass = exportedInterfaces[0];
String address = getPojoAddress(endpointProps, iClass);
ServerFactoryBean factory = createServerFactoryBean(endpointProps, iClass);
String contextRoot = PropertyHelper.getProperty(endpointProps, WsConstants.WS_HTTP_SERVICE_CONTEXT);
final Long sid = (Long) endpointProps.get(RemoteConstants.ENDPOINT_SERVICE_ID);
Set<String> intentNames = intentManager.getExported(endpointProps);
List<Object> intents = intentManager.getRequiredIntents(intentNames);
intents.addAll(intentManager.getIntentsFromService(serviceO));
Bus bus = createBus(sid, serviceContext, contextRoot, endpointProps);
factory.setDataBinding(getDataBinding(endpointProps, iClass));
factory.setBindingConfig(new SoapBindingConfiguration());
factory.setBus(bus);
factory.setServiceClass(iClass);
factory.setServiceBean(serviceO);
factory.setAddress(address);
addContextProperties(factory, endpointProps, WsConstants.WS_CONTEXT_PROPS_PROP_KEY);
WsdlSupport.setWsdlProperties(factory, serviceContext, endpointProps);
if (serviceO instanceof IntentsProvider) {
intents.addAll(((IntentsProvider)serviceO).getIntents());
}
applyIntents(intents, factory);
String completeEndpointAddress = httpServiceManager.getAbsoluteAddress(contextRoot, address);
try {
EndpointDescription epd = createEndpointDesc(endpointProps,
new String[]{WsConstants.WS_CONFIG_TYPE},
completeEndpointAddress, intentNames);
return createServerFromFactory(factory, epd);
} catch (Exception e) {
throw new RuntimeException("Error exporting service with address " + completeEndpointAddress, e);
}
}
private void applyIntents(List<Object> intents, AbstractEndpointFactory factory) {
List<Feature> features = intentManager.getIntents(Feature.class, intents);
factory.setFeatures(features);
DataBinding dataBinding = intentManager.getIntent(DataBinding.class, intents);
if (dataBinding != null) {
factory.setDataBinding(dataBinding);
}
BindingConfiguration binding = intentManager.getIntent(BindingConfiguration.class, intents);
if (binding != null) {
factory.setBindingConfig(binding);
}
}
protected EndpointDescription createEndpointDesc(Map<String, Object> props, String[] importedConfigs,
String address, Collection<String> intents) {
return super.createEndpointDesc(props, importedConfigs, WsConstants.WS_ADDRESS_PROPERTY, address, intents);
}
private String getPojoAddress(Map<String, Object> sd, Class<?> iClass) {
String address = getClientAddress(sd);
if (address != null) {
return address;
}
// If the property is not of type string this will cause an ClassCastException which
// will be propagated to the ExportRegistration exception property.
Object port = sd.get(WsConstants.WS_PORT_PROPERTY);
if (port == null) {
port = "9000";
}
address = "http://localhost:" + port + "/" + iClass.getName().replace('.', '/');
LOG.info("Using a default address: " + address);
return address;
}
protected String getClientAddress(Map<String, Object> sd) {
return PropertyHelper.getFirstNonEmptyStringProperty(sd, WsConstants.WS_ADDRESS_PROPERTY,
RemoteConstants.ENDPOINT_ID);
}
protected String getServerAddress(Map<String, Object> sd, Class<?> iClass) {
String address = getClientAddress(sd);
return address == null ? httpServiceManager.getDefaultAddress(iClass) : address;
}
protected Endpoint createServerFromFactory(ServerFactoryBean factory, EndpointDescription epd) {
Server server = factory.create();
return new ServerEndpoint(epd, server);
}
private DataBinding getDataBinding(Map<String, Object> sd, Class<?> iClass) {
return isJAXWS(sd, iClass) ? new JAXBDataBinding() : new AegisDatabinding();
}
// Isolated so that it can be substituted for testing
protected ClientProxyFactoryBean createClientProxyFactoryBean(Map<String, Object> sd, Class<?> iClass) {
return isJAXWS(sd, iClass) ? new JaxWsProxyFactoryBean() : new ClientProxyFactoryBean();
}
// Isolated so that it can be substituted for testing
protected ServerFactoryBean createServerFactoryBean(Map<String, Object> sd, Class<?> iClass) {
return isJAXWS(sd, iClass) ? new JaxWsServerFactoryBean() : new ServerFactoryBean();
}
private boolean isJAXWS(Map<String, Object> sd, Class<?> iClass) {
return iClass.getAnnotation(WebService.class) != null;
}
}
| 1,048 |
0 | Create_ds/kotlinpoet/kotlinpoet/src/jvmTest/java/com/squareup | Create_ds/kotlinpoet/kotlinpoet/src/jvmTest/java/com/squareup/kotlinpoet/JavaClassWithArrayValueAnnotation.java | package com.squareup.kotlinpoet;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import static com.squareup.kotlinpoet.JavaClassWithArrayValueAnnotation.AnnotationWithArrayValue;
@AnnotationWithArrayValue({
Object.class, Boolean.class
})
public class JavaClassWithArrayValueAnnotation {
@Retention(RetentionPolicy.RUNTIME)
@interface AnnotationWithArrayValue {
Class[] value();
}
} | 1,049 |
0 | Create_ds/kotlinpoet/kotlinpoet/src/jvmTest/java/com/squareup | Create_ds/kotlinpoet/kotlinpoet/src/jvmTest/java/com/squareup/kotlinpoet/TypeNameTest.java | /*
* Copyright (C) 2015 Square, Inc.
*
* 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
*
* https://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 com.squareup.kotlinpoet;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.junit.Test;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
public class TypeNameTest {
protected <E extends Enum<E>> E generic(E[] values) {
return values[0];
}
protected static class TestGeneric<T> {
class Inner {}
class InnerGeneric<T2> {}
static class NestedNonGeneric {}
}
protected static TestGeneric<String>.Inner testGenericStringInner() {
return null;
}
protected static TestGeneric<Integer>.Inner testGenericIntInner() {
return null;
}
protected static TestGeneric<Short>.InnerGeneric<Long> testGenericInnerLong() {
return null;
}
protected static TestGeneric<Short>.InnerGeneric<Integer> testGenericInnerInt() {
return null;
}
protected static TestGeneric.NestedNonGeneric testNestedNonGeneric() {
return null;
}
@Test public void genericType() throws Exception {
Method recursiveEnum = getClass().getDeclaredMethod("generic", Enum[].class);
TypeNames.get(recursiveEnum.getReturnType());
TypeNames.get(recursiveEnum.getGenericReturnType());
TypeName genericTypeName = TypeNames.get(recursiveEnum.getParameterTypes()[0]);
TypeNames.get(recursiveEnum.getGenericParameterTypes()[0]);
// Make sure the generic argument is present
assertThat(genericTypeName.toString()).contains("Enum");
}
@Test public void innerClassInGenericType() throws Exception {
Method genericStringInner = getClass().getDeclaredMethod("testGenericStringInner");
TypeNames.get(genericStringInner.getReturnType());
TypeName genericTypeName = TypeNames.get(genericStringInner.getGenericReturnType());
assertNotEquals(TypeNames.get(genericStringInner.getGenericReturnType()),
TypeNames.get(getClass().getDeclaredMethod("testGenericIntInner").getGenericReturnType()));
// Make sure the generic argument is present
assertThat(genericTypeName.toString()).isEqualTo(
TestGeneric.class.getCanonicalName() + "<java.lang.String>.Inner");
}
@Test public void innerGenericInGenericType() throws Exception {
Method genericStringInner = getClass().getDeclaredMethod("testGenericInnerLong");
TypeNames.get(genericStringInner.getReturnType());
TypeName genericTypeName = TypeNames.get(genericStringInner.getGenericReturnType());
assertNotEquals(TypeNames.get(genericStringInner.getGenericReturnType()),
TypeNames.get(getClass().getDeclaredMethod("testGenericInnerInt").getGenericReturnType()));
// Make sure the generic argument is present
assertThat(genericTypeName.toString()).isEqualTo(
TestGeneric.class.getCanonicalName() + "<java.lang.Short>.InnerGeneric<java.lang.Long>");
}
@Test public void innerStaticInGenericType() throws Exception {
Method staticInGeneric = getClass().getDeclaredMethod("testNestedNonGeneric");
TypeNames.get(staticInGeneric.getReturnType());
TypeName typeName = TypeNames.get(staticInGeneric.getGenericReturnType());
// Make sure there are no generic arguments
assertThat(typeName.toString()).isEqualTo(
TestGeneric.class.getCanonicalName() + ".NestedNonGeneric");
}
@Test public void equalsAndHashCodePrimitive() {
assertEqualsHashCodeAndToString(TypeNames.BOOLEAN, TypeNames.BOOLEAN);
assertEqualsHashCodeAndToString(TypeNames.BYTE, TypeNames.BYTE);
assertEqualsHashCodeAndToString(TypeNames.CHAR, TypeNames.CHAR);
assertEqualsHashCodeAndToString(TypeNames.DOUBLE, TypeNames.DOUBLE);
assertEqualsHashCodeAndToString(TypeNames.FLOAT, TypeNames.FLOAT);
assertEqualsHashCodeAndToString(TypeNames.INT, TypeNames.INT);
assertEqualsHashCodeAndToString(TypeNames.LONG, TypeNames.LONG);
assertEqualsHashCodeAndToString(TypeNames.SHORT, TypeNames.SHORT);
assertEqualsHashCodeAndToString(TypeNames.UNIT, TypeNames.UNIT);
}
@Test public void equalsAndHashCodeClassName() {
assertEqualsHashCodeAndToString(ClassNames.get(Object.class), ClassNames.get(Object.class));
assertEqualsHashCodeAndToString(TypeNames.get(Object.class), ClassNames.get(Object.class));
assertEqualsHashCodeAndToString(ClassName.bestGuess("java.lang.Object"),
ClassNames.get(Object.class));
}
@Test public void equalsAndHashCodeParameterizedTypeName() {
assertEqualsHashCodeAndToString(ParameterizedTypeName.get(List.class, Object.class),
ParameterizedTypeName.get(List.class, Object.class));
assertEqualsHashCodeAndToString(ParameterizedTypeName.get(Set.class, UUID.class),
ParameterizedTypeName.get(Set.class, UUID.class));
assertNotEquals(ClassNames.get(List.class), ParameterizedTypeName.get(List.class,
String.class));
}
@Test public void equalsAndHashCodeTypeVariableName() {
assertEqualsHashCodeAndToString(TypeVariableName.get("A"),
TypeVariableName.get("A"));
TypeVariableName typeVar1 = TypeVariableName.get("T", Comparator.class, Serializable.class);
TypeVariableName typeVar2 = TypeVariableName.get("T", Comparator.class, Serializable.class);
assertEqualsHashCodeAndToString(typeVar1, typeVar2);
}
@Test public void equalsAndHashCodeWildcardTypeName() {
assertEqualsHashCodeAndToString(WildcardTypeName.producerOf(Object.class),
WildcardTypeName.producerOf(Object.class));
assertEqualsHashCodeAndToString(WildcardTypeName.producerOf(Serializable.class),
WildcardTypeName.producerOf(Serializable.class));
assertEqualsHashCodeAndToString(WildcardTypeName.consumerOf(String.class),
WildcardTypeName.consumerOf(String.class));
}
private void assertEqualsHashCodeAndToString(TypeName a, TypeName b) {
assertEquals(a.toString(), b.toString());
assertThat(a.equals(b)).isTrue();
assertThat(a.hashCode()).isEqualTo(b.hashCode());
assertFalse(a.equals(null));
}
}
| 1,050 |
0 | Create_ds/PayPal-Android-SDK/SampleApp/src/androidTest/java/com/paypal/example/paypalandroidsdkexample | Create_ds/PayPal-Android-SDK/SampleApp/src/androidTest/java/com/paypal/example/paypalandroidsdkexample/test/TestHelper.java | package com.paypal.example.paypalandroidsdkexample.test;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
import android.support.test.runner.lifecycle.Stage;
import android.text.format.DateFormat;
import android.view.View;
import com.lukekorth.deviceautomator.DeviceAutomator;
import com.lukekorth.deviceautomator.UiObjectMatcher;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.InstrumentationRegistry.getTargetContext;
import static com.lukekorth.deviceautomator.AutomatorAction.click;
import static com.lukekorth.deviceautomator.AutomatorAction.setText;
import static com.lukekorth.deviceautomator.DeviceAutomator.onDevice;
import static com.lukekorth.deviceautomator.UiObjectMatcher.withContentDescription;
import static com.lukekorth.deviceautomator.UiObjectMatcher.withText;
/**
* This helper class provides with methods to help write better tests.
*/
public abstract class TestHelper {
public static final String PAYPAL_SAMPLE_APP_PACKAGE_NAME = "com.paypal.example.paypalandroidsdkexample.debug";
public static final String PAYPAL_SANDBOX_USERNAME = "sample@buy.com";
public static final String PAYPAL_SANDBOX_PASSWORD = "123123123";
public static void setup() {
PreferenceManager.getDefaultSharedPreferences(getTargetContext())
.edit()
.clear()
.commit();
onDevice().onHomeScreen().launchApp(PAYPAL_SAMPLE_APP_PACKAGE_NAME);
}
public static DeviceAutomator onDeviceWithScreenShot() {
DeviceAutomator result = onDevice();
takeScreenshot(null);
return result;
}
public static DeviceAutomator onDeviceWithScreenShot(UiObjectMatcher matcher) {
DeviceAutomator result = onDevice(matcher);
takeScreenshot(null);
return result;
}
public static void takeScreenshot(String name) {
if (name == null) {
Date now = new Date();
DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
name = String.valueOf(now.getTime());
}
// In Testdroid Cloud, taken screenshots are always stored
// under /test-screenshots/ folder and this ensures those screenshots
// be shown under Test Results
String path =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/test-screenshots/" + name + ".png";
OutputStream out = null;
try {
View scrView = getActivityInstance().getWindow().getDecorView().getRootView();
scrView.setDrawingCacheEnabled(true);
Bitmap bm = scrView.getDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(bm);
scrView.setDrawingCacheEnabled(false);
File imageFile = new File(path);
out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
} catch (Exception ex) {
// Ignore any exceptions as this is just for debugging purposes
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception ex) {
// Nothing to do here
}
}
}
public static Activity getActivityInstance() {
final Activity[] currentActivity = new Activity[1];
getInstrumentation().waitForIdleSync();
getInstrumentation().runOnMainSync(new Runnable() {
public void run() {
Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
Iterator<Activity> iterator = resumedActivities.iterator();
while (iterator.hasNext()) {
currentActivity[0] = (Activity) iterator.next();
}
}
});
return currentActivity[0];
}
public static void onLogin() {
onDeviceWithScreenShot(withContentDescription("Email")).perform(click(), setText(PAYPAL_SANDBOX_USERNAME));
onDeviceWithScreenShot().pressDPadDown().typeText(PAYPAL_SANDBOX_PASSWORD);
onDeviceWithScreenShot(withText("Log In")).perform(click());
}
public static void onAgree() {
try {
onDeviceWithScreenShot(withText("Agree")).perform(click());
} catch (RuntimeException ex) {
// This may mean, he has already agreed to it before.
}
}
}
| 1,051 |
0 | Create_ds/PayPal-Android-SDK/SampleApp/src/androidTest/java/com/paypal/example/paypalandroidsdkexample | Create_ds/PayPal-Android-SDK/SampleApp/src/androidTest/java/com/paypal/example/paypalandroidsdkexample/test/PaymentTest.java | package com.paypal.example.paypalandroidsdkexample.test;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import android.support.test.runner.AndroidJUnit4;
import static com.lukekorth.deviceautomator.AutomatorAction.click;
import static com.lukekorth.deviceautomator.AutomatorAssertion.text;
import static com.lukekorth.deviceautomator.UiObjectMatcher.withText;
import static com.lukekorth.deviceautomator.UiObjectMatcher.withTextStartingWith;
import static com.paypal.example.paypalandroidsdkexample.test.TestHelper.onDeviceWithScreenShot;
import static com.paypal.example.paypalandroidsdkexample.test.TestHelper.onLogin;
import static com.paypal.example.paypalandroidsdkexample.test.TestHelper.onAgree;
import static com.paypal.example.paypalandroidsdkexample.test.TestHelper.takeScreenshot;
import static org.hamcrest.CoreMatchers.containsString;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class PaymentTest {
@Before
public void setup() {
TestHelper.setup();
}
/**
* Makes a Single Payment
*/
@Test(timeout = 60000)
public void buyAThing() {
onDeviceWithScreenShot(withText("Buy a Thing")).perform(click());
onDeviceWithScreenShot(withText("Pay with")).perform(click());
onLogin();
// Payment Confirmation
onDeviceWithScreenShot(withText("Pay")).perform(click());
// Confirm Result Success
onDeviceWithScreenShot(withTextStartingWith("Result :")).check(text(containsString("PaymentConfirmation")));
}
/**
* Gets a Future Payment Consent
*/
@Test(timeout = 60000)
public void futurePaymentConsent() {
takeScreenshot("futurePaymentConsent");
onDeviceWithScreenShot(withText("Future Payment Consent")).perform(click());
onLogin();
onAgree();
// Confirm Result Success
onDeviceWithScreenShot(withTextStartingWith("Result :")).check(text(containsString("Future Payment")));
}
/**
* Makes a Future Payment Purchase
*/
@Test(timeout = 60000)
public void futurePaymentPurchase() {
takeScreenshot("futurePaymentPurchase");
onDeviceWithScreenShot(withText("Future Payment Purchase")).perform(click());
// Confirm Result Success
onDeviceWithScreenShot(withTextStartingWith("Result :")).check(text(containsString("Client Metadata Id")));
}
/**
* Gets Profile Sharing Consent
*/
@Test(timeout = 60000)
public void profileSharingConsent() {
takeScreenshot("profileSharingConsent");
onDeviceWithScreenShot(withText("Profile Sharing Consent")).perform(click());
onLogin();
onAgree();
// Confirm Result Success
onDeviceWithScreenShot(withTextStartingWith("Result :")).check(text(containsString("Profile Sharing code")));
}
}
| 1,052 |
0 | Create_ds/PayPal-Android-SDK/SampleApp/src/main/java/com/paypal/example | Create_ds/PayPal-Android-SDK/SampleApp/src/main/java/com/paypal/example/paypalandroidsdkexample/SampleActivity.java | package com.paypal.example.paypalandroidsdkexample;
import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalFuturePaymentActivity;
import com.paypal.android.sdk.payments.PayPalItem;
import com.paypal.android.sdk.payments.PayPalOAuthScopes;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalProfileSharingActivity;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import com.paypal.android.sdk.payments.ShippingAddress;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
*
* THIS FILE IS OVERWRITTEN BY `androidSDK/src/<general|partner>sampleAppJava.
* ANY UPDATES TO THIS FILE WILL BE REMOVED IN RELEASES.
*
* Basic sample using the SDK to make a payment or consent to future payments.
*
* For sample mobile backend interactions, see
* https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
*/
public class SampleActivity extends Activity {
private static final String TAG = "paymentExample";
/**
* - Set to PayPalConfiguration.ENVIRONMENT_PRODUCTION to move real money.
*
* - Set to PayPalConfiguration.ENVIRONMENT_SANDBOX to use your test credentials
* from https://developer.paypal.com
*
* - Set to PayPalConfiguration.ENVIRONMENT_NO_NETWORK to kick the tires
* without communicating to PayPal's servers.
*/
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_NO_NETWORK;
// note that these credentials will differ between live & sandbox environments.
private static final String CONFIG_CLIENT_ID = "credentials from developer.paypal.com";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static final int REQUEST_CODE_PROFILE_SHARING = 3;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Example Merchant")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
public void onBuyPressed(View pressed) {
/*
* PAYMENT_INTENT_SALE will cause the payment to complete immediately.
* Change PAYMENT_INTENT_SALE to
* - PAYMENT_INTENT_AUTHORIZE to only authorize payment and capture funds later.
* - PAYMENT_INTENT_ORDER to create a payment for authorization and capture
* later via calls from your server.
*
* Also, to include additional payment details and an item list, see getStuffToBuy() below.
*/
PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
/*
* See getStuffToBuy(..) for examples of some available payment options.
*/
Intent intent = new Intent(SampleActivity.this, PaymentActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
private PayPalPayment getThingToBuy(String paymentIntent) {
return new PayPalPayment(new BigDecimal("0.01"), "USD", "sample item",
paymentIntent);
}
/*
* This method shows use of optional payment details and item list.
*/
private PayPalPayment getStuffToBuy(String paymentIntent) {
//--- include an item list, payment amount details
PayPalItem[] items =
{
new PayPalItem("sample item #1", 2, new BigDecimal("87.50"), "USD",
"sku-12345678"),
new PayPalItem("free sample item #2", 1, new BigDecimal("0.00"),
"USD", "sku-zero-price"),
new PayPalItem("sample item #3 with a longer name", 6, new BigDecimal("37.99"),
"USD", "sku-33333")
};
BigDecimal subtotal = PayPalItem.getItemTotal(items);
BigDecimal shipping = new BigDecimal("7.21");
BigDecimal tax = new BigDecimal("4.67");
PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax);
BigDecimal amount = subtotal.add(shipping).add(tax);
PayPalPayment payment = new PayPalPayment(amount, "USD", "sample item", paymentIntent);
payment.items(items).paymentDetails(paymentDetails);
//--- set other optional fields like invoice_number, custom field, and soft_descriptor
payment.custom("This is text that will be associated with the payment that the app can use.");
return payment;
}
/*
* Add app-provided shipping address to payment
*/
private void addAppProvidedShippingAddress(PayPalPayment paypalPayment) {
ShippingAddress shippingAddress =
new ShippingAddress().recipientName("Mom Parker").line1("52 North Main St.")
.city("Austin").state("TX").postalCode("78729").countryCode("US");
paypalPayment.providedShippingAddress(shippingAddress);
}
/*
* Enable retrieval of shipping addresses from buyer's PayPal account
*/
private void enableShippingAddressRetrieval(PayPalPayment paypalPayment, boolean enable) {
paypalPayment.enablePayPalShippingAddressesRetrieval(enable);
}
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(SampleActivity.this, PayPalFuturePaymentActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
public void onProfileSharingPressed(View pressed) {
Intent intent = new Intent(SampleActivity.this, PayPalProfileSharingActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PayPalProfileSharingActivity.EXTRA_REQUESTED_SCOPES, getOauthScopes());
startActivityForResult(intent, REQUEST_CODE_PROFILE_SHARING);
}
private PayPalOAuthScopes getOauthScopes() {
/* create the set of required scopes
* Note: see https://developer.paypal.com/docs/integration/direct/identity/attributes/ for mapping between the
* attributes you select for this app in the PayPal developer portal and the scopes required here.
*/
Set<String> scopes = new HashSet<String>(
Arrays.asList(PayPalOAuthScopes.PAYPAL_SCOPE_EMAIL, PayPalOAuthScopes.PAYPAL_SCOPE_ADDRESS) );
return new PayPalOAuthScopes(scopes);
}
protected void displayResultText(String result) {
((TextView)findViewById(R.id.txtResult)).setText("Result : " + result);
Toast.makeText(
getApplicationContext(),
result, Toast.LENGTH_LONG)
.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm =
data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(TAG, confirm.toJSONObject().toString(4));
Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));
/**
* TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
* or consent completion.
* See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
* for more details.
*
* For sample mobile backend interactions, see
* https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
*/
displayResultText("PaymentConfirmation info received from PayPal");
} catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i(TAG, "The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(
TAG,
"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth =
data.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.i("FuturePaymentExample", auth.toJSONObject().toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.i("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
displayResultText("Future Payment code received from PayPal");
} catch (JSONException e) {
Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(
"FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_PROFILE_SHARING) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth =
data.getParcelableExtra(PayPalProfileSharingActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.i("ProfileSharingExample", auth.toJSONObject().toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.i("ProfileSharingExample", authorization_code);
sendAuthorizationToServer(auth);
displayResultText("Profile Sharing code received from PayPal");
} catch (JSONException e) {
Log.e("ProfileSharingExample", "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("ProfileSharingExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(
"ProfileSharingExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
/**
* TODO: Send the authorization response to your server, where it can
* exchange the authorization code for OAuth access and refresh tokens.
*
* Your server must then store these tokens, so that your server code
* can execute payments for this user in the future.
*
* A more complete example that includes the required app-server to
* PayPal-server integration is available from
* https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
*/
}
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Client Metadata ID from the SDK
String metadataId = PayPalConfiguration.getClientMetadataId(this);
Log.i("FuturePaymentExample", "Client Metadata ID: " + metadataId);
// TODO: Send metadataId and transaction details to your server for processing with
// PayPal...
displayResultText("Client Metadata Id received from SDK");
}
@Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
}
| 1,053 |
0 | Create_ds/cordova-amazon-fireos/test/cordova/plugins/org.apache.cordova.device/src | Create_ds/cordova-amazon-fireos/test/cordova/plugins/org.apache.cordova.device/src/android/Device.java | /*
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.cordova.device;
import java.util.TimeZone;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.provider.Settings;
import android.telephony.TelephonyManager;
public class Device extends CordovaPlugin {
public static final String TAG = "Device";
public static String cordovaVersion = "dev"; // Cordova version
public static String platform = "Android"; // Device OS
public static String uuid; // Device UUID
BroadcastReceiver telephonyReceiver = null;
/**
* Constructor.
*/
public Device() {
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
Device.uuid = getUuid();
this.initTelephonyReceiver();
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback id used when calling back into JavaScript.
* @return True if the action was valid, false if not.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("getDeviceInfo")) {
JSONObject r = new JSONObject();
r.put("uuid", Device.uuid);
r.put("version", this.getOSVersion());
r.put("platform", Device.platform);
r.put("cordova", Device.cordovaVersion);
r.put("model", this.getModel());
callbackContext.success(r);
}
else {
return false;
}
return true;
}
/**
* Unregister receiver.
*/
public void onDestroy() {
this.cordova.getActivity().unregisterReceiver(this.telephonyReceiver);
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Listen for telephony events: RINGING, OFFHOOK and IDLE
* Send these events to all plugins using
* CordovaActivity.onMessage("telephone", "ringing" | "offhook" | "idle")
*/
private void initTelephonyReceiver() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
//final CordovaInterface mycordova = this.cordova;
this.telephonyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// If state has changed
if ((intent != null) && intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
if (intent.hasExtra(TelephonyManager.EXTRA_STATE)) {
String extraData = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (extraData.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
LOG.i(TAG, "Telephone RINGING");
webView.postMessage("telephone", "ringing");
}
else if (extraData.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
LOG.i(TAG, "Telephone OFFHOOK");
webView.postMessage("telephone", "offhook");
}
else if (extraData.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
LOG.i(TAG, "Telephone IDLE");
webView.postMessage("telephone", "idle");
}
}
}
}
};
// Register the receiver
this.cordova.getActivity().registerReceiver(this.telephonyReceiver, intentFilter);
}
/**
* Get the OS name.
*
* @return
*/
public String getPlatform() {
return Device.platform;
}
/**
* Get the device's Universally Unique Identifier (UUID).
*
* @return
*/
public String getUuid() {
String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
return uuid;
}
/**
* Get the Cordova version.
*
* @return
*/
public String getCordovaVersion() {
return Device.cordovaVersion;
}
public String getModel() {
String model = android.os.Build.MODEL;
return model;
}
public String getProductName() {
String productname = android.os.Build.PRODUCT;
return productname;
}
/**
* Get the OS version.
*
* @return
*/
public String getOSVersion() {
String osversion = android.os.Build.VERSION.RELEASE;
return osversion;
}
public String getSDKVersion() {
@SuppressWarnings("deprecation")
String sdkversion = android.os.Build.VERSION.SDK;
return sdkversion;
}
public String getTimeZoneID() {
TimeZone tz = TimeZone.getDefault();
return (tz.getID());
}
}
| 1,054 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/userwebview.java | /*
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.cordova.test;
import android.os.Bundle;
import com.amazon.android.webkit.AmazonGeolocationPermissions.Callback;
import org.apache.cordova.*;
import com.amazon.android.webkit.AmazonWebView;
public class userwebview extends MainTestActivity {
public TestViewClient testViewClient;
public TestChromeClient testChromeClient;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
testViewClient = new TestViewClient(this, appView);
testChromeClient = new TestChromeClient(this, appView);
super.init();
appView.setWebViewClient(testViewClient);
appView.setWebChromeClient(testChromeClient);
super.loadUrl("file:///android_asset/www/userwebview/index.html");
}
public class TestChromeClient extends CordovaChromeClient {
public TestChromeClient(CordovaInterface ctx, CordovaWebView app) {
super(ctx, app);
LOG.d("userwebview", "TestChromeClient()");
}
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
LOG.d("userwebview", "onGeolocationPermissionsShowPrompt(" + origin + ")");
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
}
/**
* This class can be used to override the GapViewClient and receive notification of webview events.
*/
public class TestViewClient extends CordovaWebViewClient {
public TestViewClient(CordovaInterface ctx, CordovaWebView app) {
super(ctx, app);
LOG.d("userwebview", "TestViewClient()");
}
@Override
public boolean shouldOverrideUrlLoading(AmazonWebView view, String url) {
LOG.d("userwebview", "shouldOverrideUrlLoading(" + url + ")");
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onReceivedError(AmazonWebView view, int errorCode, String description, String failingUrl) {
LOG.d("userwebview", "onReceivedError: Error code=" + errorCode + " Description=" + description + " URL=" + failingUrl);
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
}
| 1,055 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/errorurl.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class errorurl extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences.set("errorUrl", "file:///android_asset/www/htmlnotfound/error.html");
super.loadUrl("file:///android_asset/www/htmlnotfound/index.html");
}
}
| 1,056 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/menus.java | /*
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.cordova.test;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import org.apache.cordova.*;
import org.apache.cordova.LOG;
public class menus extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// need the title to be shown (config.xml) for the options menu to be visible
super.init();
super.registerForContextMenu(super.appView);
super.loadUrl("file:///android_asset/www/menus/index.html");
}
// Demonstrate how to add your own menus to app
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
int base = Menu.FIRST;
// Group, item id, order, title
menu.add(base, base, base, "Item1");
menu.add(base, base + 1, base + 1, "Item2");
menu.add(base, base + 2, base + 2, "Item3");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
LOG.d("menus", "Item " + item.getItemId() + " pressed.");
this.appView.loadUrl("javascript:alert('Menu " + item.getItemId() + " pressed.')");
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
LOG.d("menus", "onPrepareOptionsMenu()");
// this.appView.loadUrl("javascript:alert('onPrepareOptionsMenu()')");
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info) {
LOG.d("menus", "onCreateContextMenu()");
menu.setHeaderTitle("Test Context Menu");
menu.add(200, 200, 200, "Context Item1");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
this.appView.loadUrl("javascript:alert('Context Menu " + item.getItemId() + " pressed.')");
return true;
}
}
| 1,057 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/CordovaDriverAction.java | /*
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.cordova.test;
import java.util.concurrent.ExecutorService;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import com.amazon.android.webkit.AmazonWebKitFactories;
import com.amazon.android.webkit.AmazonWebKitFactory;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class CordovaDriverAction extends Activity implements CordovaInterface {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void startActivityForResult(CordovaPlugin command, Intent intent,
int requestCode) {
// TODO Auto-generated method stub
}
public void setActivityResultCallback(CordovaPlugin plugin) {
// TODO Auto-generated method stub
}
public Activity getActivity() {
// TODO Auto-generated method stub
return null;
}
@Deprecated
public Context getContext() {
// TODO Auto-generated method stub
return null;
}
@Deprecated
public void cancelLoadUrl() {
// TODO Auto-generated method stub
}
public Object onMessage(String id, Object data) {
// TODO Auto-generated method stub
return null;
}
public ExecutorService getThreadPool() {
// TODO Auto-generated method stub
return null;
}
@Override
public AmazonWebKitFactory getFactory() {
return AmazonWebKitFactories.getDefaultFactory();
}
}
| 1,058 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/iframe.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class iframe extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/iframe/index.html");
}
}
| 1,059 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/ActivityPlugin.java | /*
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.cordova.test;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.LOG;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
/**
* This class provides a service.
*/
public class ActivityPlugin extends CordovaPlugin {
static String TAG = "ActivityPlugin";
/**
* Constructor.
*/
public ActivityPlugin() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) {
PluginResult result = new PluginResult(PluginResult.Status.OK, "");
try {
if (action.equals("start")) {
this.startActivity(args.getString(0));
callbackContext.sendPluginResult(result);
callbackContext.success();
return true;
}
} catch (JSONException e) {
result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, "JSON Exception");
callbackContext.sendPluginResult(result);
return false;
}
return false;
}
// --------------------------------------------------------------------------
// LOCAL METHODS
// --------------------------------------------------------------------------
public void startActivity(String className) {
try {
Intent intent = new Intent().setClass(this.cordova.getActivity(), Class.forName(className));
LOG.d(TAG, "Starting activity %s", className);
this.cordova.getActivity().startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
LOG.e(TAG, "Error starting activity %s", className);
}
}
}
| 1,060 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/timeout.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class timeout extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
// Short timeout to cause error
preferences.set("loadUrlTimeoutValue", 10);
super.loadUrl("http://www.google.com");
}
}
| 1,061 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/CordovaWebViewTestActivity.java | /*
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.cordova.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaChromeClient;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebViewClient;
import org.apache.cordova.test.R;
import com.amazon.android.webkit.AmazonWebKitFactories;
import com.amazon.android.webkit.AmazonWebKitFactory;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class CordovaWebViewTestActivity extends Activity implements CordovaInterface {
public CordovaWebView cordovaWebView;
private final ExecutorService threadPool = Executors.newCachedThreadPool();
private static boolean sFactoryInit = false;
private AmazonWebKitFactory factory = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// AWV Factory should be initialized before setting the layout
if (!sFactoryInit) {
factory = AmazonWebKitFactories.getDefaultFactory();
if (factory.isRenderProcess(this)) {
return; // Do nothing if this is on render process
}
factory.initialize(this);
sFactoryInit = true;
} else {
factory = AmazonWebKitFactories.getDefaultFactory();
}
setContentView(R.layout.main);
//CB-7238: This has to be added now, because it got removed from somewhere else
Config.init(this);
cordovaWebView = (CordovaWebView) findViewById(R.id.cordovaWebView);
factory.initializeWebView(cordovaWebView, 0xFFFFFF, false, null);
cordovaWebView.init(this, new CordovaWebViewClient(this, cordovaWebView), new CordovaChromeClient(this, cordovaWebView),
Config.getPluginEntries(), Config.getWhitelist(), Config.getExternalWhitelist(), Config.getPreferences());
cordovaWebView.loadUrl("file:///android_asset/www/index.html");
}
public Context getContext() {
return this;
}
public void startActivityForResult(CordovaPlugin command, Intent intent,
int requestCode) {
// TODO Auto-generated method stub
}
public void setActivityResultCallback(CordovaPlugin plugin) {
// TODO Auto-generated method stub
}
//Note: This must always return an activity!
public Activity getActivity() {
return this;
}
@Deprecated
public void cancelLoadUrl() {
// TODO Auto-generated method stub
}
public Object onMessage(String id, Object data) {
// TODO Auto-generated method stub
return null;
}
public ExecutorService getThreadPool() {
// TODO Auto-generated method stub
return threadPool;
}
@Override
/**
* The final call you receive before your activity is destroyed.
*/
public void onDestroy() {
super.onDestroy();
if (cordovaWebView != null) {
// Send destroy event to JavaScript
cordovaWebView.handleDestroy();
}
}
@Override
public AmazonWebKitFactory getFactory() {
return AmazonWebKitFactories.getDefaultFactory();
}
}
| 1,062 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/backgroundcolor.java | /*
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.cordova.test;
import android.graphics.Color;
import android.os.Bundle;
import org.apache.cordova.*;
public class backgroundcolor extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// backgroundColor can also be set in cordova.xml, but you must use the number equivalent of the color. For example, Color.RED is
// <preference name="backgroundColor" value="-65536" />
preferences.set("backgroundColor", Color.GREEN);
super.loadUrl("file:///android_asset/www/backgroundcolor/index.html");
}
}
| 1,063 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/fullscreen.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class fullscreen extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Properties must be set before init() is called, since some are processed during init().
// fullscreen can also be set in cordova.xml. For example,
// <preference name="fullscreen" value="true" />
preferences.set("fullscreen", true);
super.init();
super.loadUrl("file:///android_asset/www/fullscreen/index.html");
}
}
| 1,064 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/lifecycle.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class lifecycle extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/lifecycle/index.html");
}
}
| 1,065 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/whitelist.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
import com.amazon.android.webkit.AmazonWebView;
public class whitelist extends MainTestActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
appView.setWebViewClient(new TestViewClient(this, appView));
super.loadUrl("file:///android_asset/www/whitelist/index.html");
}
/**
* This class can be used to override the GapViewClient and receive notification of webview events.
*/
public class TestViewClient extends CordovaWebViewClient {
public TestViewClient(CordovaInterface ctx, CordovaWebView app) {
super(ctx, app);
}
@Override
public boolean shouldOverrideUrlLoading(AmazonWebView view, String url) {
LOG.d("whitelist", "shouldOverrideUrlLoading(" + url + ")");
LOG.d("whitelist", "originalUrl=" + view.getOriginalUrl());
return super.shouldOverrideUrlLoading(view, url);
}
}
}
| 1,066 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/basicauth.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class basicauth extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
// LogCat: onReceivedHttpAuthRequest(browserspy.dk:80,BrowserSpy.dk - HTTP Password Test)
AuthenticationToken token = new AuthenticationToken();
token.setUserName("test");
token.setPassword("test");
// classic webview includes port in hostname, Chromium webview does not. Handle both here.
// BTW, the realm is optional.
setAuthenticationToken(token, "browserspy.dk:80", "BrowserSpy.dk - HTTP Password Test");
setAuthenticationToken(token, "browserspy.dk", "BrowserSpy.dk - HTTP Password Test");
// Add web site to whitelist
Config.getWhitelist().addWhiteListEntry("http://browserspy.dk/*", true);
// Load test
super.loadUrl("file:///android_asset/www/basicauth/index.html");
}
}
| 1,067 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/MainTestActivity.java | /*
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.cordova.test;
import org.apache.cordova.CordovaActivity;
import android.os.Bundle;
public class MainTestActivity extends CordovaActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
}
}
| 1,068 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/htmlnotfound.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class htmlnotfound extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
super.loadUrl("file:///android_asset/www/htmlnotfound/index.html");
}
}
| 1,069 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/SabotagedActivity.java | /*
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.cordova.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaActivity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class SabotagedActivity extends CordovaActivity {
private String BAD_ASSET = "www/error.html";
private String LOG_TAG = "SabotagedActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// copyErrorAsset();
super.init();
super.loadUrl(Config.getStartUrl());
}
/*
* Sometimes we need to move code around before we can do anything. This will
* copy the bad code out of the assets before we initalize Cordova so that when Cordova actually
* initializes, we have something for it to navigate to.
*/
private void copyErrorAsset () {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list(BAD_ASSET);
} catch (IOException e) {
Log.e(LOG_TAG, e.getMessage());
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(BAD_ASSET);
out = new FileOutputStream(Environment.getExternalStorageDirectory().toString() +"/" + filename);
copy(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
//Quick and Dirty Copy!
private void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
}
| 1,070 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/loading.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class loading extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences.set("loadingDialog", "Testing,Loading...");
super.loadUrl("http://www.google.com");
}
}
| 1,071 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/backbuttonmultipage.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class backbuttonmultipage extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/backbuttonmultipage/index.html");
}
}
| 1,072 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/background.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class background extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//super.init(new FixWebView(this), new CordovaWebViewClient(this), new CordovaChromeClient(this));
preferences.set("keepRunning", false);
super.loadUrl("file:///android_asset/www/background/index.html");
}
}
| 1,073 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/tests.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class tests extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
//super.pluginManager.addService("Activity", "org.apache.cordova.test.ActivityPlugin");
super.loadUrl("file:///android_asset/www/index.html");
}
}
| 1,074 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/xhr.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class xhr extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/xhr/index.html");
}
}
| 1,075 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/AmazonWebViewOnUiThread.java | /*
* Copyright (C) 2011 The Android Open Source Project
*
* 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.
*/
package org.apache.cordova.test;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import android.os.Looper;
import android.test.InstrumentationTestCase;
import com.amazon.android.webkit.AmazonWebBackForwardList;
import com.amazon.android.webkit.AmazonWebHistoryItem;
import com.amazon.android.webkit.AmazonWebView;
import junit.framework.Assert;
/**
* Many tests need to run WebView code in the UI thread. This class wraps a WebView so that calls are ensured to arrive
* on the UI thread. All methods may be run on either the UI thread or test thread.
*/
public class AmazonWebViewOnUiThread {
/**
* The test that this class is being used in. Used for runTestOnUiThread.
*/
private InstrumentationTestCase mTest;
/**
* The WebView that calls will be made on.
*/
private AmazonWebView mWebView;
/**
* Initializes the webView with a WebViewClient, WebChromeClient, and PictureListener to prepare for
* loadUrlAndWaitForCompletion. A new WebViewOnUiThread should be called during setUp so as to reinitialize between
* calls.
*
* @param test
* The test in which this is being run.
* @param webView
* The webView that the methods should call.
* @see loadUrlAndWaitForCompletion
*/
public AmazonWebViewOnUiThread(InstrumentationTestCase test,
CordovaWebView webView) {
mTest = test;
mWebView = webView;
}
public void loadUrl(final String url) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mWebView.loadUrl(url);
}
});
}
public AmazonWebBackForwardList copyBackForwardList() {
return getValue(new ValueGetter<AmazonWebBackForwardList>() {
@Override
public AmazonWebBackForwardList capture() {
return mWebView.copyBackForwardList();
}
});
}
public void printBackForwardList() {
runOnUiThread(new Runnable() {
@Override
public void run() {
AmazonWebBackForwardList currentList = copyBackForwardList();
int currentSize = currentList.getSize();
for (int i = 0; i < currentSize; ++i) {
AmazonWebHistoryItem item = currentList.getItemAtIndex(i);
String url = item.getUrl();
LOG.d("cordovaamzn", "The URL at index: " + Integer.toString(i)
+ "is " + url);
}
}
});
}
public String getUrl() {
return getValue(new ValueGetter<String>() {
@Override
public String capture() {
return mWebView.getUrl();
}
});
}
public boolean backHistory() {
return getValue(new ValueGetter<Boolean>() {
@Override
public Boolean capture() {
// Check webview first to see if there is a history
// This is needed to support curPage#diffLink, since they are
// added to appView's history, but not our history url array
// (JQMobile behavior)
if (mWebView.canGoBack()) {
printBackForwardList();
mWebView.goBack();
return true;
}
return false;
}
});
}
/**
* Helper for running code on the UI thread where an exception is a test failure. If this is already the UI thread
* then it runs the code immediately.
*
* @see runTestOnUiThread
* @param r
* The code to run in the UI thread
*/
public void runOnUiThread(Runnable r) {
try {
if (isUiThread()) {
r.run();
} else {
mTest.runTestOnUiThread(r);
}
} catch (Throwable t) {
Assert.fail("Unexpected error while running on UI thread: "
+ t.getMessage());
}
}
private <T> T getValue(ValueGetter<T> getter) {
runOnUiThread(getter);
return getter.getValue();
}
private abstract class ValueGetter<T> implements Runnable {
private T mValue;
@Override
public void run() {
mValue = capture();
}
protected abstract T capture();
public T getValue() {
return mValue;
}
}
/*
* Returns true if the current thread is the UI thread based on the Looper.
*/
private static boolean isUiThread() {
return (Looper.myLooper() == Looper.getMainLooper());
}
}
| 1,076 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/splashscreen.java | /*
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.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class splashscreen extends CordovaActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
// Show splashscreen
preferences.set("splashscreen", "sandy");
super.loadUrl("file:///android_asset/www/splashscreen/index.html", 2000);
}
}
| 1,077 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/util/PollingCheck.java | /*
* Copyright (C) 2012 The Android Open Source Project
*
* 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.
*/
package org.apache.cordova.test.util;
import java.util.concurrent.Callable;
import junit.framework.Assert;
public abstract class PollingCheck {
private static final long TIME_SLICE = 50;
private long mTimeout = 3000;
public PollingCheck() {
}
public PollingCheck(long timeout) {
mTimeout = timeout;
}
protected abstract boolean check();
public void run() {
if (check()) {
return;
}
long timeout = mTimeout;
while (timeout > 0) {
try {
Thread.sleep(TIME_SLICE);
} catch (InterruptedException e) {
Assert.fail("unexpected InterruptedException");
}
if (check()) {
return;
}
timeout -= TIME_SLICE;
}
Assert.fail("unexpected timeout");
}
public static void check(CharSequence message, long timeout,
Callable<Boolean> condition) throws Exception {
while (timeout > 0) {
if (condition.call()) {
return;
}
Thread.sleep(TIME_SLICE);
timeout -= TIME_SLICE;
}
Assert.fail(message.toString());
}
}
| 1,078 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/util/Purity.java | /*
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.
*/
/*
* Purity is a small set of Android utility methods that allows us to simulate touch events on
* Android applications. This is important for simulating some of the most annoying tests.
*/
package org.apache.cordova.test.util;
import android.app.Instrumentation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Picture;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import com.amazon.android.webkit.AmazonWebView;
public class Purity {
Instrumentation inst;
int width, height;
float density;
Bitmap state;
boolean fingerDown = false;
public Purity(Context ctx, Instrumentation i)
{
inst = i;
DisplayMetrics display = ctx.getResources().getDisplayMetrics();
density = display.density;
width = display.widthPixels;
height = display.heightPixels;
}
/*
* WebKit doesn't give you real pixels anymore, this is done for subpixel fonts to appear on
* iOS and Android. However, Android automation requires real pixels
*/
private int getRealCoord(int coord)
{
return (int) (coord * density);
}
public int getViewportWidth()
{
return (int) (width/density);
}
public int getViewportHeight()
{
return (int) (height/density);
}
public void touch(int x, int y)
{
int realX = getRealCoord(x);
int realY = getRealCoord(y);
long downTime = SystemClock.uptimeMillis();
// event time MUST be retrieved only by this way!
long eventTime = SystemClock.uptimeMillis();
if(!fingerDown)
{
MotionEvent downEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, realX, realY, 0);
inst.sendPointerSync(downEvent);
}
MotionEvent upEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, realX, realY, 0);
inst.sendPointerSync(upEvent);
}
public void touchStart(int x, int y)
{
int realX = getRealCoord(x);
int realY = getRealCoord(y);
long downTime = SystemClock.uptimeMillis();
// event time MUST be retrieved only by this way!
long eventTime = SystemClock.uptimeMillis();
MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, realX, realY, 0);
inst.sendPointerSync(event);
fingerDown = true;
}
//Move from the touch start
public void touchMove(int x, int y)
{
if(!fingerDown)
touchStart(x,y);
else
{
int realX = getRealCoord(x);
int realY = getRealCoord(y);
long downTime = SystemClock.uptimeMillis();
// event time MUST be retrieved only by this way!
long eventTime = SystemClock.uptimeMillis();
MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, realX, realY, 0);
inst.sendPointerSync(event);
}
}
public void touchEnd(int x, int y)
{
if(!fingerDown)
{
touch(x, y);
}
else
{
int realX = getRealCoord(x);
int realY = getRealCoord(y);
long downTime = SystemClock.uptimeMillis();
// event time MUST be retrieved only by this way!
long eventTime = SystemClock.uptimeMillis();
MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, realX, realY, 0);
inst.sendPointerSync(event);
fingerDown = false;
}
}
public void setBitmap(AmazonWebView view)
{
Picture p = view.capturePicture();
state = Bitmap.createBitmap(p.getWidth(), p.getHeight(), Bitmap.Config.ARGB_8888);
}
public boolean checkRenderView(AmazonWebView view)
{
if(state == null)
{
setBitmap(view);
return false;
}
else
{
Picture p = view.capturePicture();
Bitmap newState = Bitmap.createBitmap(p.getWidth(), p.getHeight(), Bitmap.Config.ARGB_8888);
boolean result = newState.equals(state);
newState.recycle();
return result;
}
}
public void clearBitmap()
{
if(state != null)
state.recycle();
}
protected void finalize()
{
clearBitmap();
}
}
| 1,079 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/XhrTest.java | package org.apache.cordova.test.junit;
/*
*
* 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.
*
*/
import org.apache.cordova.test.xhr;
import android.test.ActivityInstrumentationTestCase2;
public class XhrTest extends ActivityInstrumentationTestCase2<xhr> {
public XhrTest()
{
super(xhr.class);
}
}
| 1,080 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/ErrorUrlTest.java | package org.apache.cordova.test.junit;
/*
*
* 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.
*
*/
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.test.errorurl;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class ErrorUrlTest extends ActivityInstrumentationTestCase2<errorurl> {
private int TIMEOUT = 1000;
errorurl testActivity;
private FrameLayout containerView;
private LinearLayout innerContainer;
private CordovaWebView testView;
public ErrorUrlTest() {
super("org.apache.cordova.test",errorurl.class);
}
protected void setUp() throws Exception {
super.setUp();
testActivity = this.getActivity();
containerView = (FrameLayout) testActivity.findViewById(android.R.id.content);
innerContainer = (LinearLayout) containerView.getChildAt(0);
testView = (CordovaWebView) innerContainer.getChildAt(0);
}
public void testPreconditions(){
assertNotNull(innerContainer);
assertNotNull(testView);
}
public void testUrl() throws Throwable
{
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String good_url = "file:///android_asset/www/htmlnotfound/error.html";
String url = testView.getUrl();
assertNotNull(url);
assertEquals(good_url, url);
}
});
}
private void sleep() {
try {
Thread.sleep(TIMEOUT);
} catch (InterruptedException e) {
fail("Unexpected Timeout");
}
}
}
| 1,081 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/IntentUriOverrideTest.java | /*
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.cordova.test.junit;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.test.SabotagedActivity;
import org.apache.cordova.test.splashscreen;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class IntentUriOverrideTest extends ActivityInstrumentationTestCase2<SabotagedActivity> {
private int TIMEOUT = 1000;
private SabotagedActivity testActivity;
private FrameLayout containerView;
private LinearLayout innerContainer;
private CordovaWebView testView;
private Instrumentation mInstr;
private String BAD_URL = "file:///sdcard/download/wl-exploit.htm";
@SuppressWarnings("deprecation")
public IntentUriOverrideTest()
{
super("org.apache.cordova.test",SabotagedActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
mInstr = this.getInstrumentation();
Intent badIntent = new Intent();
badIntent.setClassName("org.apache.cordova.test", "org.apache.cordova.test.SabotagedActivity");
badIntent.putExtra("url", BAD_URL);
setActivityIntent(badIntent);
testActivity = getActivity();
containerView = (FrameLayout) testActivity.findViewById(android.R.id.content);
innerContainer = (LinearLayout) containerView.getChildAt(0);
testView = (CordovaWebView) innerContainer.getChildAt(0);
}
public void testPreconditions(){
assertNotNull(innerContainer);
assertNotNull(testView);
}
public void testChangeStartUrl() throws Throwable
{
runTestOnUiThread(new Runnable() {
public void run()
{
sleep();
boolean isBadUrl = testView.getUrl().equals(BAD_URL);
assertFalse(isBadUrl);
}
});
}
private void sleep() {
try {
Thread.sleep(TIMEOUT);
} catch (InterruptedException e) {
fail("Unexpected Timeout");
}
}
}
| 1,082 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/CordovaTest.java | /*
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.cordova.test.junit;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginManager;
import org.apache.cordova.test.CordovaWebViewTestActivity;
import org.apache.cordova.test.R;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.view.View;
public class CordovaTest extends
ActivityInstrumentationTestCase2<CordovaWebViewTestActivity> {
private static final long TIMEOUT = 1000;
private CordovaWebViewTestActivity testActivity;
private View testView;
private String rString;
public CordovaTest() {
super("org.apache.cordova.test.activities", CordovaWebViewTestActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
testActivity = this.getActivity();
testView = testActivity.findViewById(R.id.cordovaWebView);
}
public void testPreconditions() {
assertNotNull(testView);
}
public void testForCordovaView() {
//Sleep for no reason!!!!
sleep();
String className = testView.getClass().getSimpleName();
assertTrue(className.equals("CordovaWebView"));
}
/*
public void testForPluginManager() {
CordovaWebView v = (CordovaWebView) testView;
PluginManager p = v.getPluginManager();
assertNotNull(p);
String className = p.getClass().getSimpleName();
assertTrue(className.equals("PluginManager"));
}
public void testBackButton() {
CordovaWebView v = (CordovaWebView) testView;
assertFalse(v.checkBackKey());
}
public void testLoadUrl() {
CordovaWebView v = (CordovaWebView) testView;
v.loadUrlIntoView("file:///android_asset/www/index.html");
sleep();
String url = v.getUrl();
boolean result = url.equals("file:///android_asset/www/index.html");
assertTrue(result);
int visible = v.getVisibility();
assertTrue(visible == View.VISIBLE);
}
public void testBackHistoryFalse() {
CordovaWebView v = (CordovaWebView) testView;
// Move back in the history
boolean test = v.backHistory();
assertFalse(test);
}
// Make sure that we can go back
public void testBackHistoryTrue() {
this.testLoadUrl();
CordovaWebView v = (CordovaWebView) testView;
v.loadUrlIntoView("file:///android_asset/www/compass/index.html");
sleep();
String url = v.getUrl();
assertTrue(url.equals("file:///android_asset/www/compass/index.html"));
// Move back in the history
boolean test = v.backHistory();
assertTrue(test);
sleep();
url = v.getUrl();
assertTrue(url.equals("file:///android_asset/www/index.html"));
}
*/
private void sleep() {
try {
Thread.sleep(TIMEOUT);
} catch (InterruptedException e) {
fail("Unexpected Timeout");
}
}
}
| 1,083 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/BackButtonMultiPageTest.java | package org.apache.cordova.test.junit;
/*
*
* 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.
*
*/
import org.apache.cordova.Config;
import org.apache.cordova.CordovaChromeClient;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewClient;
import org.apache.cordova.test.backbuttonmultipage;
import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import android.view.KeyEvent;
import android.view.inputmethod.BaseInputConnection;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class BackButtonMultiPageTest extends
ActivityInstrumentationTestCase2<backbuttonmultipage> {
private int TIMEOUT = 1000;
backbuttonmultipage testActivity;
private FrameLayout containerView;
private LinearLayout innerContainer;
private CordovaWebView testView;
public BackButtonMultiPageTest() {
super(backbuttonmultipage.class);
}
@UiThreadTest
protected void setUp() throws Exception {
super.setUp();
testActivity = this.getActivity();
containerView = (FrameLayout) testActivity.findViewById(android.R.id.content);
innerContainer = (LinearLayout) containerView.getChildAt(0);
testView = (CordovaWebView) innerContainer.getChildAt(0);
testView.loadUrl("file:///android_asset/www/backbuttonmultipage/index.html");
sleep();
}
@UiThreadTest
public void testPreconditions(){
assertNotNull(innerContainer);
assertNotNull(testView);
String url = testView.getUrl();
assertTrue(url.endsWith("index.html"));
}
public void testViaHref() throws Throwable {
runTestOnUiThread(new Runnable() {
public void run()
{
testView.sendJavascript("window.location = 'sample2.html';");
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertEquals("file:///android_asset/www/backbuttonmultipage/sample2.html", url);
testView.sendJavascript("window.location = 'sample3.html';"); }
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertEquals("file:///android_asset/www/backbuttonmultipage/sample3.html", url);
assertTrue(testView.backHistory());
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertEquals("file:///android_asset/www/backbuttonmultipage/sample2.html", url);
assertTrue(testView.backHistory());
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertEquals("file:///android_asset/www/backbuttonmultipage/index.html", url);
}
});
}
public void testViaLoadUrl() throws Throwable {
runTestOnUiThread(new Runnable() {
public void run()
{
testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample2.html");
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("sample2.html"));
testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample3.html");
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("sample3.html"));
testView.backHistory();
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("sample2.html"));
testView.backHistory();
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("index.html"));
testView.backHistory();
}
});
}
public void testViaBackButtonOnView() throws Throwable {
runTestOnUiThread(new Runnable() {
public void run()
{
testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample2.html");
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("sample2.html"));
testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample3.html");
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("sample3.html"));
BaseInputConnection viewConnection = new BaseInputConnection(testView, true);
KeyEvent backDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
KeyEvent backUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
viewConnection.sendKeyEvent(backDown);
viewConnection.sendKeyEvent(backUp);
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("sample2.html"));
BaseInputConnection viewConnection = new BaseInputConnection(testView, true);
KeyEvent backDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
KeyEvent backUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
viewConnection.sendKeyEvent(backDown);
viewConnection.sendKeyEvent(backUp);
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("index.html"));
}
});
}
public void testViaBackButtonOnLayout() throws Throwable {
runTestOnUiThread(new Runnable() {
public void run()
{
testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample2.html");
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("sample2.html"));
testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample3.html");
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("sample3.html"));
BaseInputConnection viewConnection = new BaseInputConnection(containerView, true);
KeyEvent backDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
KeyEvent backUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
viewConnection.sendKeyEvent(backDown);
viewConnection.sendKeyEvent(backUp);
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("sample2.html"));
BaseInputConnection viewConnection = new BaseInputConnection(containerView, true);
KeyEvent backDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
KeyEvent backUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
viewConnection.sendKeyEvent(backDown);
viewConnection.sendKeyEvent(backUp);
}
});
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("index.html"));
}
});
}
@UiThreadTest
private void sleep() {
try {
Thread.sleep(TIMEOUT);
} catch (InterruptedException e) {
fail("Unexpected Timeout");
}
}
}
| 1,084 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/SplashscreenTest.java | package org.apache.cordova.test.junit;
/*
*
* 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.
*
*/
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.test.splashscreen;
import android.app.Dialog;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class SplashscreenTest extends ActivityInstrumentationTestCase2<splashscreen> {
private splashscreen testActivity;
private Dialog containerView;
public SplashscreenTest()
{
super("org.apache.cordova.test",splashscreen.class);
}
protected void setUp() throws Exception {
super.setUp();
testActivity = this.getActivity();
//containerView = (FrameLayout) testActivity.findViewById(android.R.id.content);
//containerView = (Dialog) testActivity.findViewById(id);
}
}
| 1,085 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/IFrameTest.java | package org.apache.cordova.test.junit;
/*
*
* 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.
*
*/
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.test.iframe;
import org.apache.cordova.test.util.Purity;
import android.app.Activity;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.test.TouchUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class IFrameTest extends ActivityInstrumentationTestCase2 {
private Instrumentation mInstr;
private Activity testActivity;
private FrameLayout containerView;
private LinearLayout innerContainer;
private CordovaWebView testView;
private TouchUtils touch;
private Purity touchTool;
public IFrameTest() {
super("org.apache.cordova.test",iframe.class);
}
protected void setUp() throws Exception {
super.setUp();
mInstr = this.getInstrumentation();
testActivity = this.getActivity();
containerView = (FrameLayout) testActivity.findViewById(android.R.id.content);
innerContainer = (LinearLayout) containerView.getChildAt(0);
testView = (CordovaWebView) innerContainer.getChildAt(0);
touch = new TouchUtils();
touchTool = new Purity(testActivity, getInstrumentation());
}
public void testIframeDest() throws Throwable
{
runTestOnUiThread(new Runnable() {
public void run()
{
testView.sendJavascript("loadUrl('http://maps.google.com/maps?output=embed');");
}
});
sleep(3000);
runTestOnUiThread(new Runnable() {
public void run()
{
testView.sendJavascript("loadUrl('index2.html')");
}
});
sleep(1000);
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("index.html"));
}
});
}
public void testIframeHistory() throws Throwable
{
runTestOnUiThread(new Runnable() {
public void run()
{
testView.sendJavascript("loadUrl('http://maps.google.com/maps?output=embed');");
}
});
sleep(3000);
runTestOnUiThread(new Runnable() {
public void run()
{
testView.sendJavascript("loadUrl('index2.html')");
}
});
sleep(1000);
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
testView.backHistory();
}
});
sleep(1000);
runTestOnUiThread(new Runnable() {
public void run()
{
String url = testView.getUrl();
assertTrue(url.endsWith("index.html"));
}
});
}
private void sleep(int timeout) {
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
fail("Unexpected Timeout");
}
}
}
| 1,086 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/LifecycleTest.java | package org.apache.cordova.test.junit;
/*
*
* 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.
*
*/
import org.apache.cordova.test.lifecycle;
import android.test.ActivityInstrumentationTestCase2;
public class LifecycleTest extends ActivityInstrumentationTestCase2<lifecycle> {
public LifecycleTest()
{
super("org.apache.cordova.test",lifecycle.class);
}
}
| 1,087 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/CordovaActivityTest.java | /*
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.cordova.test.junit;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginManager;
import org.apache.cordova.test.MainTestActivity;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class CordovaActivityTest extends ActivityInstrumentationTestCase2<MainTestActivity> {
private MainTestActivity testActivity;
private FrameLayout containerView;
private LinearLayout innerContainer;
private CordovaWebView testView;
private Instrumentation mInstr;
private int TIMEOUT = 1000;
@SuppressWarnings("deprecation")
public CordovaActivityTest()
{
super("org.apache.cordova.test",MainTestActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
mInstr = this.getInstrumentation();
testActivity = this.getActivity();
containerView = (FrameLayout) testActivity.findViewById(android.R.id.content);
innerContainer = (LinearLayout) containerView.getChildAt(0);
testView = (CordovaWebView) innerContainer.getChildAt(0);
}
public void testPreconditions(){
assertNotNull(innerContainer);
assertNotNull(testView);
}
public void testForCordovaView() {
String className = testView.getClass().getSimpleName();
assertTrue(className.equals("CordovaWebView"));
}
public void testForLinearLayout() {
String className = innerContainer.getClass().getSimpleName();
assertTrue(className.equals("LinearLayoutSoftKeyboardDetect"));
}
private void sleep() {
try {
Thread.sleep(TIMEOUT);
} catch (InterruptedException e) {
fail("Unexpected Timeout");
}
}
}
| 1,088 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/CordovaResourceApiTest.java |
package org.apache.cordova.test.junit;
/*
*
* 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.
*
*/
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.test.ActivityInstrumentationTestCase2;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaResourceApi;
import org.apache.cordova.CordovaResourceApi.OpenForReadResult;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginEntry;
import org.apache.cordova.test.CordovaWebViewTestActivity;
import org.apache.cordova.test.R;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Scanner;
public class CordovaResourceApiTest extends ActivityInstrumentationTestCase2<CordovaWebViewTestActivity> {
public CordovaResourceApiTest()
{
super(CordovaWebViewTestActivity.class);
}
CordovaWebView cordovaWebView;
CordovaResourceApi resourceApi;
private CordovaWebViewTestActivity activity;
String execPayload;
Integer execStatus;
protected void setUp() throws Exception {
super.setUp();
activity = this.getActivity();
cordovaWebView = activity.cordovaWebView;
resourceApi = cordovaWebView.getResourceApi();
resourceApi.setThreadCheckingEnabled(false);
cordovaWebView.pluginManager.addService(new PluginEntry("CordovaResourceApiTestPlugin1", new CordovaPlugin() {
@Override
public Uri remapUri(Uri uri) {
if (uri.getQuery() != null && uri.getQuery().contains("pluginRewrite")) {
return cordovaWebView.getResourceApi().remapUri(
Uri.parse("data:text/plain;charset=utf-8,pass"));
}
return null;
}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
synchronized (CordovaResourceApiTest.this) {
execPayload = args.getString(0);
execStatus = args.getInt(1);
CordovaResourceApiTest.this.notify();
}
return true;
}
}));
}
private Uri createTestImageContentUri() {
Bitmap imageBitmap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.icon);
String stored = MediaStore.Images.Media.insertImage(activity.getContentResolver(),
imageBitmap, "app-icon", "desc");
return Uri.parse(stored);
}
private void performApiTest(Uri uri, String expectedMimeType, File expectedLocalFile,
boolean expectRead, boolean expectWrite) throws IOException {
uri = resourceApi.remapUri(uri);
assertEquals(expectedLocalFile, resourceApi.mapUriToFile(uri));
try {
OpenForReadResult readResult = resourceApi.openForRead(uri);
String mimeType2 = resourceApi.getMimeType(uri);
assertEquals("openForRead mime-type", expectedMimeType, readResult.mimeType);
assertEquals("getMimeType mime-type", expectedMimeType, mimeType2);
readResult.inputStream.read();
if (!expectRead) {
fail("Expected getInputStream to throw.");
}
} catch (IOException e) {
if (expectRead) {
throw e;
}
}
try {
OutputStream outStream = resourceApi.openOutputStream(uri);
outStream.write(123);
if (!expectWrite) {
fail("Expected getOutputStream to throw.");
}
outStream.close();
} catch (IOException e) {
if (expectWrite) {
throw e;
}
}
}
public void testValidContentUri() throws IOException
{
Uri contentUri = createTestImageContentUri();
File localFile = resourceApi.mapUriToFile(contentUri);
assertNotNull(localFile);
performApiTest(contentUri, "image/jpeg", localFile, true, true);
}
public void testInvalidContentUri() throws IOException
{
Uri contentUri = Uri.parse("content://media/external/images/media/999999999");
performApiTest(contentUri, null, null, false, false);
}
public void testValidAssetUri() throws IOException
{
Uri assetUri = Uri.parse("file:///android_asset/www/index.html?foo#bar"); // Also check for stripping off ? and # correctly.
performApiTest(assetUri, "text/html", null, true, false);
}
public void testInvalidAssetUri() throws IOException
{
Uri assetUri = Uri.parse("file:///android_asset/www/missing.html");
performApiTest(assetUri, "text/html", null, false, false);
}
public void testFileUriToExistingFile() throws IOException
{
File f = File.createTempFile("te s t", ".txt"); // Also check for dealing with spaces.
try {
Uri fileUri = Uri.parse(f.toURI().toString() + "?foo#bar"); // Also check for stripping off ? and # correctly.
performApiTest(fileUri, "text/plain", f, true, true);
} finally {
f.delete();
}
}
public void testFileUriToMissingFile() throws IOException
{
File f = new File(Environment.getExternalStorageDirectory() + "/somefilethatdoesntexist");
Uri fileUri = Uri.parse(f.toURI().toString());
try {
performApiTest(fileUri, null, f, false, true);
} finally {
f.delete();
}
}
public void testFileUriToMissingFileWithMissingParent() throws IOException
{
File f = new File(Environment.getExternalStorageDirectory() + "/somedirthatismissing" + System.currentTimeMillis() + "/somefilethatdoesntexist");
Uri fileUri = Uri.parse(f.toURI().toString());
performApiTest(fileUri, null, f, false, true);
}
public void testUnrecognizedUri() throws IOException
{
Uri uri = Uri.parse("somescheme://foo");
performApiTest(uri, null, null, false, false);
}
public void testRelativeUri()
{
try {
resourceApi.openForRead(Uri.parse("/foo"));
fail("Should have thrown for relative URI 1.");
} catch (Throwable t) {
}
try {
resourceApi.openForRead(Uri.parse("//foo/bar"));
fail("Should have thrown for relative URI 2.");
} catch (Throwable t) {
}
try {
resourceApi.openForRead(Uri.parse("foo.png"));
fail("Should have thrown for relative URI 3.");
} catch (Throwable t) {
}
}
public void testPluginOverride() throws IOException
{
Uri uri = Uri.parse("plugin-uri://foohost/android_asset/www/index.html?pluginRewrite=yes");
performApiTest(uri, "text/plain", null, true, false);
}
public void testMainThreadUsage() throws IOException
{
Uri assetUri = Uri.parse("file:///android_asset/www/index.html");
resourceApi.setThreadCheckingEnabled(true);
try {
resourceApi.openForRead(assetUri);
fail("Should have thrown for main thread check.");
} catch (Throwable t) {
}
}
public void testDataUriPlain() throws IOException
{
Uri uri = Uri.parse("data:text/plain;charset=utf-8,pa%20ss");
OpenForReadResult readResult = resourceApi.openForRead(uri);
assertEquals("text/plain", readResult.mimeType);
String data = new Scanner(readResult.inputStream, "UTF-8").useDelimiter("\\A").next();
assertEquals("pa ss", data);
}
public void testDataUriBase64() throws IOException
{
Uri uri = Uri.parse("data:text/js;charset=utf-8;base64,cGFzcw==");
OpenForReadResult readResult = resourceApi.openForRead(uri);
assertEquals("text/js", readResult.mimeType);
String data = new Scanner(readResult.inputStream, "UTF-8").useDelimiter("\\A").next();
assertEquals("pass", data);
}
public void testWebViewRequestIntercept() throws IOException
{
cordovaWebView.sendJavascript(
"var x = new XMLHttpRequest;\n" +
"x.open('GET', 'file://foo?pluginRewrite=1', false);\n" +
"x.send();\n" +
"cordova.require('cordova/exec')(null,null,'CordovaResourceApiTestPlugin1', 'foo', [x.responseText, x.status])");
execPayload = null;
execStatus = null;
try {
synchronized (this) {
this.wait(2000);
}
} catch (InterruptedException e) {
}
assertEquals("pass", execPayload);
assertEquals(execStatus.intValue(), 200);
}
public void testWebViewWhiteListRejection() throws IOException
{
cordovaWebView.sendJavascript(
"var x = new XMLHttpRequest;\n" +
"x.open('GET', 'http://foo/bar', false);\n" +
"x.send();\n" +
"cordova.require('cordova/exec')(null,null,'CordovaResourceApiTestPlugin1', 'foo', [x.responseText, x.status])");
execPayload = null;
execStatus = null;
try {
synchronized (this) {
this.wait(2000);
}
} catch (InterruptedException e) {
}
assertEquals("", execPayload);
assertEquals(execStatus.intValue(), 404);
}
}
| 1,089 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/FixWebView.java | /*
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.cordova.test.junit;
import com.amazon.android.webkit.AmazonWebView;
import android.content.Context;
public class FixWebView extends AmazonWebView {
public FixWebView(Context context) {
super(context);
}
@Override
public void pauseTimers() {
// Do nothing
}
/**
* This method is with different signature in order to stop the timers while move application to background
* @param realPause
*/
public void pauseTimers(@SuppressWarnings("unused") boolean realPause) {
super.pauseTimers();
}
}
| 1,090 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/MenuTest.java | /*
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.cordova.test.junit;
import org.apache.cordova.test.menus;
import android.test.ActivityInstrumentationTestCase2;
public class MenuTest extends ActivityInstrumentationTestCase2<menus> {
public MenuTest() {
super("org.apache.cordova.test", menus.class);
}
}
| 1,091 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/HtmlNotFoundTest.java | package org.apache.cordova.test.junit;
/*
*
* 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.
*
*/
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.test.htmlnotfound;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class HtmlNotFoundTest extends ActivityInstrumentationTestCase2<htmlnotfound> {
private int TIMEOUT = 1000;
private htmlnotfound testActivity;
private FrameLayout containerView;
private LinearLayout innerContainer;
private CordovaWebView testView;
public HtmlNotFoundTest() {
super("org.apache.cordova.test",htmlnotfound.class);
}
protected void setUp() throws Exception {
super.setUp();
testActivity = this.getActivity();
containerView = (FrameLayout) testActivity.findViewById(android.R.id.content);
innerContainer = (LinearLayout) containerView.getChildAt(0);
testView = (CordovaWebView) innerContainer.getChildAt(0);
}
public void testPreconditions(){
assertNotNull(innerContainer);
assertNotNull(testView);
}
public void testUrl() throws Throwable
{
sleep();
runTestOnUiThread(new Runnable() {
public void run()
{
String good_url = "file:///android_asset/www/htmlnotfound/error.html";
String url = testView.getUrl();
assertNotNull(url);
assertFalse(url.equals(good_url));
}
});
}
private void sleep() {
try {
Thread.sleep(TIMEOUT);
} catch (InterruptedException e) {
fail("Unexpected Timeout");
}
}
}
| 1,092 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/test/junit/PluginManagerTest.java | /*
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.cordova.test.junit;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginEntry;
import org.apache.cordova.PluginManager;
import org.apache.cordova.test.CordovaWebViewTestActivity;
import android.test.ActivityInstrumentationTestCase2;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class PluginManagerTest extends ActivityInstrumentationTestCase2<CordovaWebViewTestActivity> {
// Plugin1 and PLugin2 return true, indicating the event is handled by them. Remaining plugins return false
private static final String PLUGIN_PACKAGE = "org.apache.cordova.pluginApi.";
private static final String PLUGIN1_SERVICE = "Plugin1";
private static final String PLUGIN1_CLASS = PLUGIN_PACKAGE + PLUGIN1_SERVICE;
private static final String PLUGIN2_SERVICE = "Plugin2";
private static final String PLUGIN2_CLASS = PLUGIN_PACKAGE + PLUGIN2_SERVICE;
private static final String PLUGIN3_SERVICE = "Plugin3";
private static final String PLUGIN3_CLASS = PLUGIN_PACKAGE + PLUGIN3_SERVICE;
private static final String PLUGIN4_SERVICE = "Plugin4";
private static final String PLUGIN4_CLASS = PLUGIN_PACKAGE + PLUGIN4_SERVICE;
private static final String PLUGIN5_SERVICE = "Plugin5";
private static final String PLUGIN5_CLASS = PLUGIN_PACKAGE + PLUGIN5_SERVICE;
private static final String TEST_URL = "file:///android_asset/www/plugins/%s.html";
private static final String PLUGIN1_URL = String.format(TEST_URL, PLUGIN1_SERVICE);
private static final String PLUGIN3_URL = String.format(TEST_URL, PLUGIN3_SERVICE);
private static final String PLUGIN5_URL = String.format(TEST_URL, PLUGIN5_SERVICE);
private CordovaWebViewTestActivity testActivity;
private FrameLayout containerView;
private LinearLayout innerContainer;
private View testView;
private PluginManager pluginMgr;
private CordovaWebView mWebView;
public PluginManagerTest() {
super("org.apache.cordova.test.activities", CordovaWebViewTestActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
testActivity = this.getActivity();
containerView = (FrameLayout) testActivity.findViewById(android.R.id.content);
innerContainer = (LinearLayout) containerView.getChildAt(0);
testView = innerContainer.getChildAt(0);
mWebView = (CordovaWebView) testView;
pluginMgr = mWebView.pluginManager;
}
/**
* Test the preconditions to verify view is not null
*/
public void testPreconditions() {
assertNotNull(innerContainer);
assertNotNull(testView);
}
/**
* Verify Plugin Manager is not null
*/
public void testForPluginManager() {
assertNotNull(pluginMgr);
String className = pluginMgr.getClass().getSimpleName();
assertEquals(0, className.compareTo("PluginManager"));
}
/**
* Verify that Plugin1 which has higher priority will receive the event first and handle it. Verify that adding
* plugin multiple times will update entries
*
* @throws Throwable
*/
public void testPluginManagerPriority() throws Throwable {
addTestPlugin(PLUGIN4_SERVICE, PLUGIN4_CLASS, true, 1.5f);
addTestPlugin(PLUGIN1_SERVICE, PLUGIN1_CLASS, true, -1.5f);
addTestPlugin(PLUGIN4_SERVICE, PLUGIN4_CLASS, true, 1.5f);
pluginMgr.postMessage("plugintest", "test");
assertEquals(PLUGIN1_URL, getCurrentUrl());
}
/**
* Verify that event propagates to the next plugin when event is not handled.
*
* @throws Throwable
*/
public void testPluginManagerPropagate() throws Throwable {
addTestPlugin(PLUGIN2_SERVICE, PLUGIN2_CLASS, true, -1f);
addTestPlugin(PLUGIN3_SERVICE, PLUGIN3_CLASS, true, -1f);
pluginMgr.postMessage("plugintest", "test");
// Sleep to make sure the message is propagated.
Thread.sleep(1000);
assertEquals(PLUGIN3_URL, getCurrentUrl());
}
/**
* Verify that the event is not propagated when handled.
*
* @throws Throwable
*/
public void testPluginManagerHandle() throws Throwable {
addTestPlugin(PLUGIN1_SERVICE, PLUGIN1_CLASS, true, -1f);
addTestPlugin(PLUGIN3_SERVICE, PLUGIN3_CLASS, true, -1f);
pluginMgr.postMessage("plugintest", "test");
assertEquals(PLUGIN1_URL, getCurrentUrl());
}
/**
* Verify that Plugin entries can be updated after init()
*
* @throws Throwable
*/
public void testPluginManagerUpdateAfterInit() throws Throwable {
addTestPlugin(PLUGIN1_SERVICE, PLUGIN1_CLASS, true, -1.5f);
addTestPlugin(PLUGIN4_SERVICE, PLUGIN4_CLASS, true, -1.5f);
pluginMgr.postMessage("plugintest", "test");
assertEquals(PLUGIN1_URL, getCurrentUrl());
addTestPlugin(PLUGIN5_SERVICE, PLUGIN5_CLASS, true, -2.5f);
pluginMgr.postMessage("plugintest", "test");
assertEquals(PLUGIN5_URL, getCurrentUrl());
}
/**
* Test all plugins are added based on their priority.
*
* @throws Exception
*/
public void testPluginEntriesPriority() throws Exception {
addTestPlugin(PLUGIN5_SERVICE, PLUGIN5_CLASS, true, -96f);
addTestPlugin(PLUGIN1_SERVICE, PLUGIN1_CLASS, true, -100f);
addTestPlugin(PLUGIN4_SERVICE, PLUGIN4_CLASS, true, -97f);
addTestPlugin(PLUGIN2_SERVICE, PLUGIN2_CLASS, true, -99f);
addTestPlugin(PLUGIN3_SERVICE, PLUGIN3_CLASS, true, -98f);
Field entries = pluginMgr.getClass().getDeclaredField("entryMap");
entries.setAccessible(true);
@SuppressWarnings("unchecked")
LinkedHashMap<String, PluginEntry> testEntries = (LinkedHashMap<String, PluginEntry>) entries.get(pluginMgr);
List<PluginEntry> pluginList = new ArrayList<PluginEntry>();
for (PluginEntry entry : testEntries.values())
pluginList.add(entry);
int entryIndex = 0;
String[] serviceArray = { PLUGIN1_SERVICE, PLUGIN2_SERVICE, PLUGIN3_SERVICE, PLUGIN4_SERVICE, PLUGIN5_SERVICE };
for (PluginEntry entry : pluginList) {
if (entryIndex == 5)
break;
assertEquals(0, serviceArray[entryIndex].compareTo(entry.service));
entryIndex++;
}
}
/**
* Create a plugin object and add it
*
* @param service
* @param cls
* @param onload
* @param priority
*/
private void addTestPlugin(String service, String cls, boolean onload, final float priority) {
PluginEntry pEntry = new PluginEntry(service, cls, onload, priority);
pluginMgr.addService(pEntry);
pluginMgr.getPlugin(service);
}
/**
* Get the URL in the current WebView
*
* @return URL
* @throws Throwable
*/
private String getCurrentUrl() throws Throwable {
final Callable<String> awvUIThread = new Callable<String>() {
@Override
public String call() throws Exception {
String currentURL = mWebView.getUrl();
return currentURL;
}
};
FutureTask<String> runnableTask = new FutureTask<String>(awvUIThread);
// If AWV is not running on the UI Thread, a RunTimeException is thrown
runTestOnUiThread(runnableTask);
return runnableTask.get();
}
}
| 1,093 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/pluginApi/Plugin1.java | /*
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.cordova.pluginApi;
import org.apache.cordova.CordovaPlugin;
import android.util.Log;
public class Plugin1 extends CordovaPlugin {
private static final String TAG = "Plugin1";
private static final String PLUGIN1_URL = "file:///android_asset/www/plugins/Plugin1.html";
/**
* Handles onMessage call back
*
* @return true to stop from propagating {@inheritDoc}
*/
@Override
public Object onMessage(String id, Object data) {
if (id.equalsIgnoreCase("plugintest")) {
this.webView.loadUrl(PLUGIN1_URL);
Log.e(TAG, "plugintest -> data: " + data.toString());
}
return true;
}
}
| 1,094 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/pluginApi/Plugin5.java | /*
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.cordova.pluginApi;
import org.apache.cordova.CordovaPlugin;
import android.util.Log;
public class Plugin5 extends CordovaPlugin {
private static final String TAG = "Plugin5";
private static final String Plugin5_URL = "file:///android_asset/www/plugins/Plugin5.html";
/**
* Handles onMessage call back
*
* @return true to stop from propagating {@inheritDoc}
*/
@Override
public Object onMessage(String id, Object data) {
if (id.equals("plugintest")) {
this.webView.loadUrl(Plugin5_URL);
Log.e(TAG, "plugintest -> data: " + data.toString());
}
return true;
}
}
| 1,095 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/pluginApi/pluginStub.java | /*
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.
*/
/*
* This plugin is a test of all the message callbacks and actions available to plugins
*
*/
package org.apache.cordova.pluginApi;
import org.apache.cordova.CordovaPlugin;
public class pluginStub extends CordovaPlugin {
public String id;
public Object data;
public Object onMessage(String id, Object input)
{
this.data = input;
return input;
}
}
| 1,096 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/pluginApi/Plugin4.java | /*
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.cordova.pluginApi;
import org.apache.cordova.CordovaPlugin;
import android.util.Log;
public class Plugin4 extends CordovaPlugin {
private static final String TAG = "Plugin4";
private static final String Plugin4_URL = "file:///android_asset/www/plugins/Plugin4.html";
/**
* Handles onMessage call back
*
* @return true to stop from propagating {@inheritDoc}
*/
@Override
public Object onMessage(String id, Object data) {
if (id.equals("plugintest")) {
this.webView.loadUrl(Plugin4_URL);
Log.e(TAG, "plugintest -> data: " + data.toString());
}
return true;
}
}
| 1,097 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/pluginApi/Plugin3.java | /*
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.cordova.pluginApi;
import org.apache.cordova.CordovaPlugin;
import android.util.Log;
public class Plugin3 extends CordovaPlugin {
private static final String TAG = "Plugin3";
private static final String Plugin3_URL = "file:///android_asset/www/plugins/Plugin3.html";
/**
* Handles onMessage call back
*
* @return null and allow event to propagate. {@inheritDoc}
*/
@Override
public Object onMessage(String id, Object data) {
if (id.equals("plugintest")) {
this.webView.loadUrl(Plugin3_URL);
Log.e(TAG, "plugintest -> data: " + data.toString());
}
return null;
}
}
| 1,098 |
0 | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova | Create_ds/cordova-amazon-fireos/test/src/org/apache/cordova/pluginApi/Plugin2.java | /*
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.cordova.pluginApi;
import org.apache.cordova.CordovaPlugin;
import android.util.Log;
public class Plugin2 extends CordovaPlugin {
private static final String TAG = "Plugin2";
private static final String Plugin2_URL = "file:///android_asset/www/plugins/Plugin2.html";
/**
* Handles onMessage call back
*
* @return null and allow event to propagate. {@inheritDoc}
*/
@Override
public Object onMessage(String id, Object data) {
if (id.equals("plugintest")) {
this.webView.loadUrl(Plugin2_URL);
Log.e(TAG, "plugintest -> data: " + data.toString());
}
return null;
}
}
| 1,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.