repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
xiaoymin/LlmInAction | https://github.com/xiaoymin/LlmInAction/blob/11723c550071102640f26e251cd6564bedde1fd4/llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/listener/ConsoleEventSourceListener.java | llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/listener/ConsoleEventSourceListener.java | /*
* THIS FILE IS PART OF Zhejiang LiShi Technology CO.,LTD.
* Copyright (c) 2019-2023 Zhejiang LiShi Technology CO.,LTD.
* It is forbidden to distribute or copy the code under this software without the consent of the Zhejiang LiShi Technology
*
* https://www.lishiots.com/
*
* 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.github.xiaoymin.llm.listener;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
/**
* 描述: sse event listener
*/
@AllArgsConstructor
@Slf4j
public class ConsoleEventSourceListener extends EventSourceListener {
final CountDownLatch countDownLatch;
@Override
public void onOpen(EventSource eventSource, Response response) {
//log.info("LLM建立sse连接...");
}
@Override
public void onEvent(EventSource eventSource, String id, String type, String data) {
// log.info("LLM返回,id:{},type:{},数据:{}", id, type, data);
System.out.print(data);
if (data.contains("\n")){
System.out.println("换行了");
}
if (StrUtil.equalsIgnoreCase(type,"finish")){
//end
System.out.println(StrUtil.EMPTY);
}
}
@Override
public void onClosed(EventSource eventSource) {
// log.info("LLM关闭sse连接...");
countDownLatch.countDown();
}
@SneakyThrows
@Override
public void onFailure( EventSource eventSource, Throwable t, Response response) {
countDownLatch.countDown();
if (Objects.isNull(response)) {
log.error("LLM sse连接异常", t);
eventSource.cancel();
return;
}
ResponseBody body = response.body();
if (Objects.nonNull(body)) {
log.error("error1-----------------");
log.error("LLM sse连接异常data:{}", body.string(), t);
} else {
log.error("error2-----------------");
log.error("LLM sse连接异常data:{}", response, t);
}
eventSource.cancel();
}
}
| java | Apache-2.0 | 11723c550071102640f26e251cd6564bedde1fd4 | 2026-01-05T02:38:26.882818Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/standalone-multipart/src/test/java/dev/resteasy/examples/multipart/UploadTestCase.java | standalone-multipart/src/test/java/dev/resteasy/examples/multipart/UploadTestCase.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.multipart;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;
import jakarta.ws.rs.SeBootstrap;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.EntityPart;
import jakarta.ws.rs.core.GenericEntity;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
public class UploadTestCase {
private static SeBootstrap.Instance INSTANCE;
@BeforeAll
public static void startInstance() throws Exception {
INSTANCE = SeBootstrap.start(RestActivator.class)
.toCompletableFuture().get(10, TimeUnit.SECONDS);
Assertions.assertNotNull(INSTANCE, "Failed to start instance");
}
@AfterAll
public static void stopInstance() throws Exception {
if (INSTANCE != null) {
INSTANCE.stop()
.toCompletableFuture()
.get(10, TimeUnit.SECONDS);
}
}
@Test
public void upload() throws Exception {
try (Client client = ClientBuilder.newClient()) {
final List<EntityPart> multipart = List.of(
EntityPart.withName("name")
.content("RESTEasy")
.mediaType(MediaType.TEXT_PLAIN_TYPE)
.build(),
EntityPart.withName("data")
.content("test content".getBytes(StandardCharsets.UTF_8))
.mediaType(MediaType.APPLICATION_OCTET_STREAM_TYPE)
.build(),
EntityPart.withName("entity")
.content("entity-data")
.mediaType(MediaType.TEXT_PLAIN_TYPE)
.build());
try (
Response response = client.target(INSTANCE.configuration().baseUriBuilder().path("api/upload"))
.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(new GenericEntity<>(multipart) {
}, MediaType.MULTIPART_FORM_DATA))) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo());
}
}
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/standalone-multipart/src/main/java/dev/resteasy/examples/multipart/UploadResource.java | standalone-multipart/src/main/java/dev/resteasy/examples/multipart/UploadResource.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.multipart;
import java.io.IOException;
import java.io.InputStream;
import jakarta.json.Json;
import jakarta.json.JsonObjectBuilder;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.ServerErrorException;
import jakarta.ws.rs.core.EntityPart;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
/**
* A simple resource for creating a greeting.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@Path("/")
public class UploadResource {
@POST
@Path("upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response upload(@FormParam("name") final String name, @FormParam("data") final InputStream data,
@FormParam("entity") final EntityPart entityPart) {
final JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("name", name);
// Read the data into a string
try (data) {
builder.add("data", new String(data.readAllBytes()));
} catch (IOException e) {
throw new ServerErrorException("Failed to read data " + data, Response.Status.BAD_REQUEST);
}
try {
builder.add(entityPart.getName(), entityPart.getContent(String.class));
} catch (IOException e) {
throw new ServerErrorException("Failed to read entity " + entityPart, Response.Status.BAD_REQUEST);
}
return Response.ok(builder.build()).build();
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/standalone-multipart/src/main/java/dev/resteasy/examples/multipart/RestActivator.java | standalone-multipart/src/main/java/dev/resteasy/examples/multipart/RestActivator.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.multipart;
import jakarta.enterprise.inject.Vetoed;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* Activates the REST application.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ApplicationPath("/api")
// Currently required to enable multipart/form-data in Undertow see https://issues.redhat.com/browse/RESTEASY-3376
@MultipartConfig
// See https://issues.redhat.com/browse/RESTEASY-3376
@Vetoed
public class RestActivator extends Application {
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/standalone-multipart/src/main/java/dev/resteasy/examples/multipart/Main.java | standalone-multipart/src/main/java/dev/resteasy/examples/multipart/Main.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.multipart;
import java.nio.charset.StandardCharsets;
import java.util.List;
import jakarta.ws.rs.SeBootstrap;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.EntityPart;
import jakarta.ws.rs.core.GenericEntity;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
/**
* An entry point for starting a REST container
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
public class Main {
public static void main(final String[] args) throws Exception {
System.setProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager");
// Start the container
final SeBootstrap.Instance instance = SeBootstrap.start(RestActivator.class)
.thenApply(i -> {
System.out.printf("Container running at %s%n", i.configuration().baseUri());
return i;
}).toCompletableFuture().get();
// Create the client and make a multipart/form-data request
try (Client client = ClientBuilder.newClient()) {
// Create the entity parts for the request
final List<EntityPart> multipart = List.of(
EntityPart.withName("name")
.content("RESTEasy")
.mediaType(MediaType.TEXT_PLAIN_TYPE)
.build(),
EntityPart.withName("entity")
.content("entity-part")
.mediaType(MediaType.TEXT_PLAIN_TYPE)
.build(),
EntityPart.withName("data")
.content("test content".getBytes(StandardCharsets.UTF_8))
.mediaType(MediaType.APPLICATION_OCTET_STREAM_TYPE)
.build());
try (
Response response = client.target(instance.configuration().baseUriBuilder().path("/api/upload"))
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(new GenericEntity<>(multipart) {
}, MediaType.MULTIPART_FORM_DATA_TYPE))) {
printResponse(response);
}
}
}
private static void printResponse(final Response response) {
System.out.println(response.getStatusInfo());
System.out.println(response.readEntity(String.class));
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/servlet-example/src/main/java/dev/resteasy/examples/servlet/MyApplication.java | servlet-example/src/main/java/dev/resteasy/examples/servlet/MyApplication.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.servlet;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
@ApplicationPath("/app")
public class MyApplication extends Application {
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/servlet-example/src/main/java/dev/resteasy/examples/servlet/GreetingResource.java | servlet-example/src/main/java/dev/resteasy/examples/servlet/GreetingResource.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.servlet;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
@Path("/greet")
public class GreetingResource {
@GET
public String get() {
return "Hello, world!";
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/tracing-example/src/test/java/dev/resteasy/examples/tracing/TracingTest.java | tracing-example/src/test/java/dev/resteasy/examples/tracing/TracingTest.java | package dev.resteasy.examples.tracing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.net.URI;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.UriBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit5.ArquillianExtension;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import org.jboss.resteasy.tracing.RESTEasyTracingLogger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ExtendWith(ArquillianExtension.class)
@RunAsClient
public class TracingTest {
@ArquillianResource
private URI uri;
@Deployment
public static WebArchive deployment() {
return ShrinkWrap.create(WebArchive.class, TracingTest.class.getSimpleName() + ".war")
.addClasses(TracingApp.class, TracingConfigResource.class)
.addAsWebInfResource(new StringAsset("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<web-app xmlns=\"https://jakarta.ee/xml/ns/jakartaee\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" xsi:schemaLocation=\"https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd\"\n"
+
" version=\"5.0\">\n" +
" <display-name>tracing-example</display-name>\n" +
" <context-param>\n" +
" <param-name>resteasy.server.tracing.type</param-name>\n" +
" <param-value>ALL</param-value>\n" +
" </context-param>\n" +
" <context-param>\n" +
" <param-name>resteasy.server.tracing.threshold</param-name>\n" +
" <param-value>VERBOSE</param-value>\n" +
" </context-param>\n" +
"</web-app>"), "web.xml");
}
@Test
public void basicTest() {
try (Client client = ClientBuilder.newClient()) {
WebTarget target = client.target(uriBuilder().path("trace/type"));
assertEquals(ResteasyContextParameters.RESTEASY_TRACING_TYPE_ALL, target.request().get(String.class));
target = client.target(uriBuilder().path("trace/level"));
assertEquals(ResteasyContextParameters.RESTEASY_TRACING_LEVEL_VERBOSE, target.request().get(String.class));
target = client.target(uriBuilder().path("trace/logger"));
assertEquals(RESTEasyTracingLogger.class.getName(), target.request().get(String.class));
}
}
private UriBuilder uriBuilder() {
return UriBuilder.fromUri(uri);
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/tracing-example/src/main/java/dev/resteasy/examples/tracing/TracingConfigResource.java | tracing-example/src/main/java/dev/resteasy/examples/tracing/TracingConfigResource.java | package dev.resteasy.examples.tracing;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Configuration;
import jakarta.ws.rs.core.Context;
import org.jboss.resteasy.tracing.RESTEasyTracingLogger;
import org.jboss.resteasy.tracing.api.RESTEasyTracing;
@Path("/")
public class TracingConfigResource {
@GET
@Path("/type")
public String type(@Context Configuration config) {
return RESTEasyTracingLogger.getTracingConfig(config);
}
@GET
@Path("/level")
public String level(@Context Configuration config) {
return RESTEasyTracingLogger.getTracingThreshold(config);
}
@GET
@Path("/logger")
public String logger(@Context HttpServletRequest request) {
RESTEasyTracingLogger logger = (RESTEasyTracingLogger) request.getAttribute(RESTEasyTracing.PROPERTY_NAME);
if (logger == null) {
return "";
} else {
return RESTEasyTracingLogger.class.getName();
}
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/tracing-example/src/main/java/dev/resteasy/examples/tracing/TracingApp.java | tracing-example/src/main/java/dev/resteasy/examples/tracing/TracingApp.java | package dev.resteasy.examples.tracing;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
@ApplicationPath("/trace")
public class TracingApp extends Application {
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/tracing-example/src/main/java/dev/resteasy/examples/tracing/TraceMethodResource.java | tracing-example/src/main/java/dev/resteasy/examples/tracing/TraceMethodResource.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.tracing;
import jakarta.enterprise.context.RequestScoped;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@Path("/headers")
@RequestScoped
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public class TraceMethodResource {
@GET
@Path("get")
public String get() {
return "GET trace";
}
@POST
@Path("post")
public String post(final String value) {
return String.format("POST trace: %s", value);
}
@PUT
@Path("put")
public String put(final String value) {
return String.format("PUT trace: %s", value);
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/bootable-jar/src/test/java/dev/resteasy/examples/bootablejar/ProductTestIT.java | bootable-jar/src/test/java/dev/resteasy/examples/bootablejar/ProductTestIT.java | package dev.resteasy.examples.bootablejar;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit5.ArquillianExtension;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(ArquillianExtension.class)
@RunAsClient
public class ProductTestIT {
@Deployment(testable = false)
public static WebArchive createDeployment() {
// Dummy deployment
return ShrinkWrap.create(WebArchive.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Test
public void testResponse() {
try (Client client = ClientBuilder.newClient()) {
final WebTarget target = client.target("http://localhost:8080/products");
try (Response response = target.request().get()) {
Assertions.assertEquals(200, response.getStatus());
final Product[] products = response.readEntity(Product[].class);
Assertions.assertEquals(3, products.length);
checkProduct(products[0], 111);
checkProduct(products[1], 222);
checkProduct(products[2], 333);
}
}
}
private void checkProduct(final Product product, final int expectedId) {
Assertions.assertEquals(expectedId, product.getId(), () -> String.format("Expected %d got %s", expectedId, product));
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/bootable-jar/src/main/java/dev/resteasy/examples/bootablejar/Product.java | bootable-jar/src/main/java/dev/resteasy/examples/bootablejar/Product.java | package dev.resteasy.examples.bootablejar;
import java.util.Objects;
public class Product implements Comparable<Product> {
private String name;
private int id;
public Product() {
}
public Product(final int id, final String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Product)) {
return false;
}
final Product other = (Product) obj;
return id == other.id;
}
@Override
public String toString() {
return "Product[id=" + id + ", name=" + name + "]";
}
@Override
public int compareTo(final Product o) {
return Integer.compare(id, o.id);
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/bootable-jar/src/main/java/dev/resteasy/examples/bootablejar/ProductApplication.java | bootable-jar/src/main/java/dev/resteasy/examples/bootablejar/ProductApplication.java | package dev.resteasy.examples.bootablejar;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
@ApplicationPath("/")
public class ProductApplication extends Application {
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/bootable-jar/src/main/java/dev/resteasy/examples/bootablejar/ProductResource.java | bootable-jar/src/main/java/dev/resteasy/examples/bootablejar/ProductResource.java | package dev.resteasy.examples.bootablejar;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("/products")
public class ProductResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Product[] getProducts() {
return new Product[] { new Product(111, "JBoss EAP"), new Product(222, "RHEL"),
new Product(333, "CentOS") };
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/smime/src/test/java/dev/resteasy/example/smime/SMIMETest.java | smime/src/test/java/dev/resteasy/example/smime/SMIMETest.java | package dev.resteasy.example.smime;
import java.io.InputStream;
import java.net.URI;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.GenericType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit5.ArquillianExtension;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.security.PemUtils;
import org.jboss.resteasy.security.smime.EnvelopedInput;
import org.jboss.resteasy.security.smime.EnvelopedOutput;
import org.jboss.resteasy.security.smime.SignedInput;
import org.jboss.resteasy.security.smime.SignedOutput;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@ExtendWith(ArquillianExtension.class)
@RunAsClient
public class SMIMETest {
private static PrivateKey privateKey;
private static X509Certificate cert;
private static Client client;
@ArquillianResource
private URI uri;
@Deployment
public static WebArchive deployment() {
return ShrinkWrap.create(WebArchive.class, SMIMETest.class.getSimpleName() + ".war")
.addClasses(Customer.class, SMIMEApplication.class, SMIMEResource.class)
.addAsWebInfResource(SMIMETest.class.getResource("/cert.pem"), "classes/cert.pem")
.addAsWebInfResource(SMIMETest.class.getResource("/private.pem"), "classes/private.pem")
// Required until WFLY-13917 is resolved
.addAsManifestResource(new StringAsset("Dependencies: org.bouncycastle import\n"), "MANIFEST.MF");
}
@BeforeAll
public static void setup() throws Exception {
InputStream certPem = Thread.currentThread().getContextClassLoader().getResourceAsStream("cert.pem");
Assertions.assertNotNull(certPem);
cert = PemUtils.decodeCertificate(certPem);
InputStream privatePem = Thread.currentThread().getContextClassLoader().getResourceAsStream("private.pem");
privateKey = PemUtils.decodePrivateKey(privatePem);
client = ((ResteasyClientBuilder) (ClientBuilder.newBuilder())).connectTimeout(120, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS).build();
}
@AfterAll
public static void shutdown() throws Exception {
client.close();
}
@Test
public void testEncryptedGet() throws Exception {
WebTarget target = client.target(generateUri("smime/encrypted"));
EnvelopedInput input = target.request().get(EnvelopedInput.class);
Customer cust = (Customer) input.getEntity(Customer.class, privateKey, cert);
System.out.println("Encrypted Message From Server:");
System.out.println(cust);
}
@Test
public void testEncryptedPost() throws Exception {
WebTarget target = client.target(generateUri("smime/encrypted"));
Customer cust = new Customer();
cust.setName("Bill");
EnvelopedOutput output = new EnvelopedOutput(cust, "application/xml");
output.setCertificate(cert);
Response res = target.request().post(Entity.entity(output, "application/pkcs7-mime"));
Assertions.assertEquals(204, res.getStatus());
res.close();
}
@Test
public void testSigned() throws Exception {
WebTarget target = client.target(generateUri("smime/signed"));
SignedInput input = target.request().get(SignedInput.class);
Customer cust = (Customer) input.getEntity(Customer.class);
System.out.println("Signed Message From Server: ");
System.out.println(cust);
input.verify(cert);
}
@Test
public void testSignedPost() throws Exception {
WebTarget target = client.target(generateUri("smime/signed"));
Customer cust = new Customer();
cust.setName("Bill");
SignedOutput output = new SignedOutput(cust, "application/xml");
output.setPrivateKey(privateKey);
output.setCertificate(cert);
Response res = target.request().post(Entity.entity(output, "multipart/signed"));
Assertions.assertEquals(204, res.getStatus());
res.close();
}
@Test
public void testEncryptedAndSignedGet() throws Exception {
WebTarget target = client.target(generateUri("smime/encrypted/signed"));
EnvelopedInput<Customer> enveloped = target.request().get(new GenericType<>() {
});
SignedInput<Customer> signed = enveloped.getEntity(SignedInput.class, privateKey, cert);
Customer cust = signed.getEntity(Customer.class);
System.out.println(cust);
Assertions.assertTrue(signed.verify(cert));
}
@Test
public void testEncryptedSignedPost() throws Exception {
WebTarget target = client.target(generateUri("smime/encrypted/signed"));
Customer cust = new Customer();
cust.setName("Bill");
SignedOutput signed = new SignedOutput(cust, "application/xml");
signed.setPrivateKey(privateKey);
signed.setCertificate(cert);
EnvelopedOutput output = new EnvelopedOutput(signed, "multipart/signed");
output.setCertificate(cert);
Response res = target.request().post(Entity.entity(output, "application/pkcs7-mime"));
Assertions.assertEquals(204, res.getStatus());
res.close();
}
private UriBuilder generateUri(final String path) {
return UriBuilder.fromUri(uri).path(path);
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/smime/src/main/java/dev/resteasy/example/smime/SMIMEResource.java | smime/src/main/java/dev/resteasy/example/smime/SMIMEResource.java | package dev.resteasy.example.smime;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import org.jboss.resteasy.security.smime.EnvelopedInput;
import org.jboss.resteasy.security.smime.EnvelopedOutput;
import org.jboss.resteasy.security.smime.SignedInput;
import org.jboss.resteasy.security.smime.SignedOutput;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@Path("/smime")
public class SMIMEResource {
private final PrivateKey privateKey;
private final X509Certificate certificate;
public SMIMEResource(PrivateKey privateKey, X509Certificate certificate) {
this.privateKey = privateKey;
this.certificate = certificate;
}
@Path("encrypted")
@GET
public EnvelopedOutput getEncrypted() {
System.out.println("HERE!!!!!");
Customer cust = new Customer();
cust.setName("Bill");
EnvelopedOutput output = new EnvelopedOutput(cust, MediaType.APPLICATION_XML_TYPE);
output.setCertificate(certificate);
return output;
}
@Path("encrypted")
@POST
public void postEncrypted(EnvelopedInput<Customer> input) {
Customer cust = input.getEntity(privateKey, certificate);
System.out.println("Encrypted Server Input: ");
System.out.println(cust);
}
@Path("signed")
@GET
@Produces("multipart/signed")
public SignedOutput getSigned() {
Customer cust = new Customer();
cust.setName("Bill");
SignedOutput output = new SignedOutput(cust, MediaType.APPLICATION_XML_TYPE);
output.setPrivateKey(privateKey);
output.setCertificate(certificate);
return output;
}
@Path("signed")
@POST
public void postSigned(SignedInput<Customer> input) throws Exception {
Customer cust = input.getEntity();
System.out.println("Signed Server Input: ");
System.out.println(cust);
if (!input.verify(certificate)) {
throw new WebApplicationException(500);
}
}
@Path("/encrypted/signed")
@GET
public EnvelopedOutput getEncryptedSigned() {
Customer cust = new Customer();
cust.setName("Bill");
SignedOutput signed = new SignedOutput(cust, MediaType.APPLICATION_XML_TYPE);
signed.setCertificate(certificate);
signed.setPrivateKey(privateKey);
EnvelopedOutput output = new EnvelopedOutput(signed, "multipart/signed");
output.setCertificate(certificate);
return output;
}
@Path("/encrypted/signed")
@POST
public void postEncryptedSigned(EnvelopedInput<SignedInput<Customer>> input) throws Exception {
SignedInput<Customer> signed = input.getEntity(privateKey, certificate);
Customer cust = signed.getEntity();
System.out.println("Encrypted and Signed Server Input: ");
System.out.println(cust);
if (!signed.verify(certificate)) {
throw new WebApplicationException(500);
}
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/smime/src/main/java/dev/resteasy/example/smime/SMIMEApplication.java | smime/src/main/java/dev/resteasy/example/smime/SMIMEApplication.java | package dev.resteasy.example.smime;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import java.util.Set;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
import org.jboss.resteasy.security.PemUtils;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@ApplicationPath("/")
public class SMIMEApplication extends Application {
private final Set<Object> resources = new HashSet<>();
public SMIMEApplication() throws Exception {
InputStream privatePem = Thread.currentThread().getContextClassLoader().getResourceAsStream("private.pem");
PrivateKey privateKey = PemUtils.decodePrivateKey(privatePem);
InputStream certPem = Thread.currentThread().getContextClassLoader().getResourceAsStream("cert.pem");
X509Certificate cert = PemUtils.decodeCertificate(certPem);
SMIMEResource resource = new SMIMEResource(privateKey, cert);
resources.add(resource);
}
@Override
public Set<Object> getSingletons() {
return resources;
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/smime/src/main/java/dev/resteasy/example/smime/Customer.java | smime/src/main/java/dev/resteasy/example/smime/Customer.java | package dev.resteasy.example.smime;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@XmlRootElement(name = "customer")
public class Customer {
private String name;
@XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Customer{" +
"name='" + name + '\'' +
'}';
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/grpc-bridge-example/src/main/java/dev/resteasy/example/grpc/greet/Greeter.java | grpc-bridge-example/src/main/java/dev/resteasy/example/grpc/greet/Greeter.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.example.grpc.greet;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
@Path("")
public class Greeter {
@GET
@Path("greet/{s}")
@Produces(MediaType.APPLICATION_JSON)
public Greeting greet(@PathParam("s") String s) {
return new Greeting("hello, " + s);
}
@GET
@Path("salute/{s}")
@Produces(MediaType.APPLICATION_JSON)
public GeneralGreeting generalGreet(@QueryParam("salute") String salute, @PathParam("s") String s) {
return getGeneralGreeting(salute, s);
}
private GeneralGreeting getGeneralGreeting(String salute, String name) {
return new GeneralGreeting(salute, name);
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/grpc-bridge-example/src/main/java/dev/resteasy/example/grpc/greet/GeneralGreeting.java | grpc-bridge-example/src/main/java/dev/resteasy/example/grpc/greet/GeneralGreeting.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.example.grpc.greet;
public class GeneralGreeting extends Greeting {
private String salute;
public GeneralGreeting() {
}
public GeneralGreeting(String salute, String s) {
super(s);
this.salute = salute;
}
public String getSalute() {
return salute;
}
public void setSalute(String salute) {
this.salute = salute;
}
public String toString() {
return salute + ", " + getS();
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/grpc-bridge-example/src/main/java/dev/resteasy/example/grpc/greet/Greeting.java | grpc-bridge-example/src/main/java/dev/resteasy/example/grpc/greet/Greeting.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.example.grpc.greet;
public class Greeting {
private String s;
public Greeting() {
}
public Greeting(String s) {
this.s = s;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public String toString() {
return "Hello, " + s;
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/async-job-service/src/test/java/dev/resteasy/examples/asyncjob/AsyncJobTest.java | async-job-service/src/test/java/dev/resteasy/examples/asyncjob/AsyncJobTest.java | package dev.resteasy.examples.asyncjob;
import java.net.URI;
import jakarta.json.JsonArray;
import jakarta.json.JsonObject;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit5.ArquillianExtension;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@ExtendWith(ArquillianExtension.class)
@RunAsClient
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class AsyncJobTest {
@ArquillianResource
private URI uri;
@Deployment
public static WebArchive deployment() {
return ShrinkWrap.create(WebArchive.class, AsyncJobTest.class.getSimpleName() + ".war")
.addClasses(AsyncResource.class, RestApplication.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Test
@Order(1)
public void post() {
try (
Client client = ClientBuilder.newClient();
Response response = client.target(createUriBuilder())
.request().post(Entity.entity("post message", MediaType.TEXT_PLAIN_TYPE))) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(), () -> response.readEntity(String.class));
Assertions.assertEquals(1, response.readEntity(Integer.class));
}
}
@Test
@Order(2)
public void put() {
try (
Client client = ClientBuilder.newClient();
Response response = client.target(createUriBuilder())
.request().put(Entity.entity("put message", MediaType.TEXT_PLAIN_TYPE))) {
Assertions.assertEquals(Response.Status.NO_CONTENT, response.getStatusInfo(),
() -> response.readEntity(String.class));
}
}
@Test
@Order(3)
public void get() {
try (
Client client = ClientBuilder.newClient();
Response response = client.target(createUriBuilder())
.request(MediaType.APPLICATION_JSON).get()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> response.readEntity(String.class));
final JsonObject json = response.readEntity(JsonObject.class);
final JsonArray array = json.getJsonArray("post");
Assertions.assertEquals(1, array.size(), () -> "Expect a single array entry got: " + array);
Assertions.assertEquals("post message", array.getString(0));
Assertions.assertEquals("put message", json.getString("put"));
}
}
@Test
@Order(4)
public void getPushMessage() {
try (
Client client = ClientBuilder.newClient();
Response response = client.target(createUriBuilder().path("1"))
.request(MediaType.TEXT_PLAIN_TYPE).get()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> response.readEntity(String.class));
final String msg = response.readEntity(String.class);
Assertions.assertEquals("post message", msg);
}
}
@Test
@Order(5)
public void getPutMessage() {
try (
Client client = ClientBuilder.newClient();
Response response = client.target(createUriBuilder().path("current"))
.request(MediaType.TEXT_PLAIN_TYPE).get()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> response.readEntity(String.class));
final String msg = response.readEntity(String.class);
Assertions.assertEquals("put message", msg);
}
}
@Test
@Order(6)
public void addAndPut() {
try (Client client = ClientBuilder.newClient()) {
final WebTarget target = client.target(createUriBuilder());
try (Response response = target.request().post(Entity.entity("new message", MediaType.TEXT_PLAIN_TYPE))) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(), () -> response.readEntity(String.class));
Assertions.assertEquals(2, response.readEntity(Integer.class));
}
try (
Response response = target.request()
.put(Entity.entity("changed put message", MediaType.TEXT_PLAIN_TYPE))) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> response.readEntity(String.class));
Assertions.assertEquals("put message", response.readEntity(String.class));
}
try (Response response = target.request(MediaType.APPLICATION_JSON_TYPE).get()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> response.readEntity(String.class));
final JsonObject json = response.readEntity(JsonObject.class);
final JsonArray array = json.getJsonArray("post");
Assertions.assertEquals(2, array.size(), () -> "Expect two array entries got: " + array);
Assertions.assertEquals("post message", array.getString(0));
Assertions.assertEquals("new message", array.getString(1));
Assertions.assertEquals("changed put message", json.getString("put"));
}
}
}
private UriBuilder createUriBuilder() {
return UriBuilder.fromUri(uri).path("resource");
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/async-job-service/src/main/java/dev/resteasy/examples/asyncjob/AsyncResource.java | async-job-service/src/main/java/dev/resteasy/examples/asyncjob/AsyncResource.java | package dev.resteasy.examples.asyncjob;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import jakarta.annotation.Resource;
import jakarta.enterprise.concurrent.ManagedExecutorService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.json.Json;
import jakarta.json.JsonArrayBuilder;
import jakarta.json.JsonObjectBuilder;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.container.AsyncResponse;
import jakarta.ws.rs.container.Suspended;
import jakarta.ws.rs.core.MediaType;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@Path("/resource")
@ApplicationScoped
public class AsyncResource {
private final Map<Integer, String> postMessages = new ConcurrentHashMap<>();
private final AtomicReference<String> putMessage = new AtomicReference<>();
private final AtomicInteger post = new AtomicInteger(0);
@Resource
private ManagedExecutorService executor;
@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
public void post(final String msg, @Suspended final AsyncResponse response) {
submit(response, () -> {
final int id = post.incrementAndGet();
postMessages.put(id, msg);
return Integer.toString(id);
});
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public void get(@Suspended final AsyncResponse response) {
submit(response, () -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
response.resume(e);
}
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
postMessages.values().forEach(arrayBuilder::add);
final JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
jsonBuilder.add("post", arrayBuilder);
final String current = putMessage.get();
if (current != null) {
jsonBuilder.add("put", current);
}
return jsonBuilder.build();
});
}
@GET
@Path("{id}")
@Produces(MediaType.TEXT_PLAIN)
public void getPostMessage(@PathParam("id") final int id, @Suspended final AsyncResponse response) {
submit(response, () -> postMessages.get(id));
}
@GET
@Path("current")
@Produces(MediaType.TEXT_PLAIN)
public void getPutMessage(@Suspended final AsyncResponse response) {
submit(response, putMessage::get);
}
@PUT
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
public void put(final String msg, @Suspended final AsyncResponse response) {
submit(response, () -> putMessage.getAndSet(msg));
}
private void submit(final AsyncResponse response, final Supplier<Object> resume) {
response.setTimeout(10L, TimeUnit.SECONDS);
executor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
response.resume(e);
}
response.resume(resume.get());
});
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/async-job-service/src/main/java/dev/resteasy/examples/asyncjob/RestApplication.java | async-job-service/src/main/java/dev/resteasy/examples/asyncjob/RestApplication.java | package dev.resteasy.examples.asyncjob;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ApplicationPath("/")
public class RestApplication extends Application {
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/microprofile-openapi/src/test/java/dev/resteasy/examples/openapi/OpenApiTestIT.java | microprofile-openapi/src/test/java/dev/resteasy/examples/openapi/OpenApiTestIT.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.openapi;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class OpenApiTestIT {
@Test
public void testResponse() {
try (Client client = ClientBuilder.newClient()) {
final WebTarget target = client.target("http://localhost:8080/openapi");
try (Response response = target.request().get()) {
Assertions.assertEquals(200, response.getStatus());
final String doc = response.readEntity(String.class);
Assertions.assertNotNull(doc);
Assertions.assertTrue(doc.contains("title: ProductApplication"));
Assertions.assertTrue(doc.contains("return a list of products"));
}
}
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/microprofile-openapi/src/main/java/dev/resteasy/examples/openapi/Product.java | microprofile-openapi/src/main/java/dev/resteasy/examples/openapi/Product.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.openapi;
import java.util.Objects;
public class Product implements Comparable<Product> {
private String name;
private int id;
public Product() {
}
public Product(final int id, final String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Product)) {
return false;
}
final Product other = (Product) obj;
return id == other.id;
}
@Override
public String toString() {
return "Product[id=" + id + ", name=" + name + "]";
}
@Override
public int compareTo(final Product o) {
return Integer.compare(id, o.id);
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/microprofile-openapi/src/main/java/dev/resteasy/examples/openapi/ProductApplication.java | microprofile-openapi/src/main/java/dev/resteasy/examples/openapi/ProductApplication.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.openapi;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
import org.eclipse.microprofile.openapi.annotations.OpenAPIDefinition;
import org.eclipse.microprofile.openapi.annotations.info.Info;
@ApplicationPath("/")
@OpenAPIDefinition(info = @Info(title = "ProductApplication", version = "1.0.0"))
public class ProductApplication extends Application {
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/microprofile-openapi/src/main/java/dev/resteasy/examples/openapi/ProductResource.java | microprofile-openapi/src/main/java/dev/resteasy/examples/openapi/ProductResource.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.openapi;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
@Path("/products")
public class ProductResource {
@APIResponse(description = "return a list of products")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Product[] getProducts() {
return new Product[] { new Product(111, "JBoss EAP"), new Product(222, "RHEL"),
new Product(333, "CentOS") };
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/contacts/src/test/java/dev/resteasy/examples/resources/ContactResourceTest.java | contacts/src/test/java/dev/resteasy/examples/resources/ContactResourceTest.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.resources;
import java.net.URI;
import java.util.Collection;
import java.util.Objects;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.GenericType;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit5.ArquillianExtension;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import dev.resteasy.examples.data.ContactRegistry;
import dev.resteasy.examples.model.Contact;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ExtendWith(ArquillianExtension.class)
@RunAsClient
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ContactResourceTest {
private static final Contact DEFAULT_CONTACT = new Contact();
static {
DEFAULT_CONTACT.setFirstName("Jane");
DEFAULT_CONTACT.setLastName("Doe");
DEFAULT_CONTACT.setEmail("jdoe@redhat.com");
DEFAULT_CONTACT.setCompanyName("Red Hat, Inc.");
DEFAULT_CONTACT.setPhoneNumber("8887334281");
}
@Deployment
public static WebArchive deployment() {
return ShrinkWrap.create(WebArchive.class, ContactResourceTest.class.getSimpleName() + ".war")
.addClasses(
ContactRegistry.class,
Contact.class,
ContactListener.class,
ContactResource.class,
Producers.class,
RestActivator.class)
.addAsResource("META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@ArquillianResource
private URI uri;
@Test
@Order(1)
public void addContact() {
try (
Client client = ClientBuilder.newClient();
Response createdResponse = client.target(UriBuilder.fromUri(uri).path("api/contact/add")).request()
.post(Entity.json(DEFAULT_CONTACT))) {
Assertions.assertEquals(Response.Status.CREATED, createdResponse.getStatusInfo(),
() -> String.format("Invalid status: %s", createdResponse.readEntity(String.class)));
// We should have the location
try (Response response = client.target(createdResponse.getLocation()).request().get()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> String.format("Invalid status: %s - %s", createdResponse.readEntity(String.class),
createdResponse.getLocation()));
final Contact resolvedContact = response.readEntity(Contact.class);
// Set the ID
DEFAULT_CONTACT.setId(resolvedContact.getId());
contactsArqEqual(resolvedContact);
}
}
}
@Test
@Order(2)
public void singleContact() {
try (
Client client = ClientBuilder.newClient();
Response response = client.target(UriBuilder.fromUri(uri).path("api/contact/"))
.request(MediaType.APPLICATION_JSON)
.get()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> String.format("Invalid status: %s", response.readEntity(String.class)));
final Collection<Contact> contacts = response.readEntity(new GenericType<>() {
});
Assertions.assertEquals(1, contacts.size(),
() -> String.format("Expected a single contact, but got %s", contacts));
contactsArqEqual(contacts.iterator().next());
}
}
@Test
@Order(3)
public void getContact() {
try (
Client client = ClientBuilder.newClient();
Response response = client.target(UriBuilder.fromUri(uri).path("api/contact/1"))
.request(MediaType.APPLICATION_JSON)
.get()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> String.format("Invalid status: %s", response.readEntity(String.class)));
final Contact resolvedContact = response.readEntity(Contact.class);
contactsArqEqual(resolvedContact);
}
}
@Test
@Order(4)
public void editContact() {
DEFAULT_CONTACT.setFirstName("Changed");
DEFAULT_CONTACT.setLastName("Another");
try (
Client client = ClientBuilder.newClient();
Response createdResponse = client.target(UriBuilder.fromUri(uri).path("api/contact/edit"))
.request(MediaType.APPLICATION_JSON)
.put(Entity.json(DEFAULT_CONTACT))) {
Assertions.assertEquals(Response.Status.CREATED, createdResponse.getStatusInfo(),
() -> String.format("Invalid status: %s", createdResponse.readEntity(String.class)));
// We should have the location
try (Response response = client.target(createdResponse.getLocation()).request().get()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> String.format("Invalid status: %s - %s", createdResponse.readEntity(String.class),
createdResponse.getLocation()));
final Contact resolvedContact = response.readEntity(Contact.class);
contactsArqEqual(resolvedContact);
}
}
}
@Test
@Order(5)
public void deleteContact() {
try (
Client client = ClientBuilder.newClient();
Response response = client.target(UriBuilder.fromUri(uri).path("api/contact/delete/1"))
.request(MediaType.APPLICATION_JSON)
.delete()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> String.format("Invalid status: %s", response.readEntity(String.class)));
final Contact resolvedContact = response.readEntity(Contact.class);
contactsArqEqual(resolvedContact);
}
}
@Test
@Order(6)
public void emptyContacts() {
try (
Client client = ClientBuilder.newClient();
Response response = client.target(UriBuilder.fromUri(uri).path("api/contact/"))
.request(MediaType.APPLICATION_JSON)
.get()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> String.format("Invalid status: %s", response.readEntity(String.class)));
final Collection<Contact> contacts = response.readEntity(new GenericType<>() {
});
Assertions.assertTrue(contacts.isEmpty(),
() -> String.format("Expected an empty set of contacts, but got %s", contacts));
}
}
private static void contactsArqEqual(final Contact secondary) {
boolean equal = Objects.equals(DEFAULT_CONTACT.getId(), secondary.getId())
&& Objects.equals(DEFAULT_CONTACT.getFirstName(), secondary.getFirstName())
&& Objects.equals(DEFAULT_CONTACT.getLastName(), secondary.getLastName())
&& Objects.equals(DEFAULT_CONTACT.getCompanyName(), secondary.getCompanyName())
&& Objects.equals(DEFAULT_CONTACT.getEmail(), secondary.getEmail())
&& Objects.equals(DEFAULT_CONTACT.getPhoneNumber(), secondary.getPhoneNumber());
Assertions.assertTrue(equal,
() -> String.format("Expected contact %s%nFound contact %s", DEFAULT_CONTACT, secondary));
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/contacts/src/main/java/dev/resteasy/examples/model/Contact.java | contacts/src/main/java/dev/resteasy/examples/model/Contact.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.model;
import java.util.Objects;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Pattern;
import jakarta.ws.rs.FormParam;
import dev.resteasy.examples.resources.ContactListener;
/**
* An entity which represents a contact.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = "email"))
@EntityListeners(ContactListener.class)
@NamedQuery(name = "findAll", query = "SELECT c FROM Contact c ORDER BY c.lastName ASC, c.firstName ASC")
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@Column(name = "first_name")
@Pattern(regexp = "[^0-9]*", message = "Must not contain numbers")
@FormParam("firstName")
private String firstName;
@Column(name = "last_name")
@Pattern(regexp = "[^0-9]*", message = "Must not contain numbers")
@FormParam("lastName")
private String lastName;
@Column(name = "company_name")
@FormParam("companyName")
private String companyName;
@Column(name = "phone_number")
@FormParam("phoneNumber")
private String phoneNumber;
@Column
@Email
@FormParam("email")
private String email;
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(final String companyName) {
this.companyName = companyName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Contact)) {
return false;
}
final Contact other = (Contact) obj;
return Objects.equals(getId(), other.getId());
}
@Override
public String toString() {
return getClass().getSimpleName() + "[id=" + getId()
+ ", firstName=" + getFirstName()
+ ", lastName=" + getLastName()
+ ", companyName=" + getCompanyName()
+ ", phonNumner=" + getPhoneNumber()
+ ", email=" + getEmail()
+ "]";
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/contacts/src/main/java/dev/resteasy/examples/data/ContactRegistry.java | contacts/src/main/java/dev/resteasy/examples/data/ContactRegistry.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.data;
import java.util.Collection;
import jakarta.enterprise.context.RequestScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import jakarta.validation.constraints.NotNull;
import dev.resteasy.examples.model.Contact;
/**
* Manages the contact repository.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@RequestScoped
@Transactional
public class ContactRegistry {
@PersistenceContext(unitName = "primary")
private EntityManager em;
/**
* Returns all the current contacts.
*
* @return a collection of the current contacts
*/
public Collection<Contact> getContacts() {
return em.createNamedQuery("findAll", Contact.class)
.getResultList();
}
/**
* Finds the contact given the id.
*
* @param id the contact id
* @return the contact or {@code null} if not found
*/
public Contact getContactById(final long id) {
return em.find(Contact.class, id);
}
/**
* Updates, or adds if missing, the contact.
*
* @param contact the contact to update
* @return the updated contact
*/
public Contact update(@NotNull final Contact contact) {
return em.merge(contact);
}
/**
* Adds a contact to the repository.
*
* @param contact the contact to add
* @return the contact
*/
public Contact add(@NotNull final Contact contact) {
em.persist(contact);
return contact;
}
/**
* Deletes the contact, if it exists, from the repository.
*
* @param id the contact id
* @return the deleted contact
*/
public Contact delete(final long id) {
final Contact contact = em.find(Contact.class, id);
if (contact != null) {
em.remove(contact);
}
return contact;
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/contacts/src/main/java/dev/resteasy/examples/resources/ContactResource.java | contacts/src/main/java/dev/resteasy/examples/resources/ContactResource.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.resources;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import dev.resteasy.examples.data.ContactRegistry;
import dev.resteasy.examples.model.Contact;
/**
* A REST endpoint to manage contacts.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@RequestScoped
@Path("/contact")
public class ContactResource {
@Inject
private ContactRegistry contactRegistry;
@Inject
private UriInfo uriInfo;
/**
* Returns all current contacts.
*
* @return all the current contacts
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response get() {
return Response.ok(contactRegistry.getContacts())
.build();
}
/**
* Returns the contact, if it exists, with the given id. If the contact does not exist a 404 is returned.
*
* @param id the contact id
* @return the contact or a 404 if not found
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
public Response get(@PathParam("id") final long id) {
final Contact contact = contactRegistry.getContactById(id);
return contact == null ? Response.status(Response.Status.NOT_FOUND).build() : Response.ok(contact).build();
}
/**
* Updates the contact.
*
* @param contact the contact to update
* @return the location to the updated contact
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("/edit")
public Response edit(@Valid final Contact contact) {
return Response
.created(uriInfo.getBaseUriBuilder().path("contact/" + contactRegistry.update(contact).getId()).build())
.build();
}
/**
* Adds the contact.
*
* @param contact the contact to add
* @return the location to the added contact
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/add")
public Response add(@Valid final Contact contact) {
return Response
.created(uriInfo.getBaseUriBuilder().path("contact/" + contactRegistry.add(contact).getId()).build())
.build();
}
/**
* Deletes the contact with the given id.
*
* @param id the contact id
* @return the deleted contact or a 404 if not found
*/
@DELETE
@Path("/delete/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response delete(@PathParam("id") final long id) {
final Contact contact = contactRegistry.delete(id);
return contact == null ? Response.status(Response.Status.NOT_FOUND).build() : Response.ok(contact).build();
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/contacts/src/main/java/dev/resteasy/examples/resources/Producers.java | contacts/src/main/java/dev/resteasy/examples/resources/Producers.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.resources;
import java.util.concurrent.atomic.AtomicReference;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Inject;
import jakarta.ws.rs.sse.Sse;
import jakarta.ws.rs.sse.SseBroadcaster;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ApplicationScoped
public class Producers {
private final AtomicReference<SseBroadcaster> broadcaster = new AtomicReference<>();
@Inject
private Sse sse;
/**
* Creates the broadcaster used for the application via injection.
*
* @return the broadcaster to use
*/
@Produces
@ApplicationScoped
public SseBroadcaster broadcaster() {
return broadcaster.updateAndGet(sseBroadcaster -> {
SseBroadcaster result = sseBroadcaster;
if (result == null) {
result = sse.newBroadcaster();
}
return result;
});
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/contacts/src/main/java/dev/resteasy/examples/resources/RestActivator.java | contacts/src/main/java/dev/resteasy/examples/resources/RestActivator.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.resources;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* Indicates that the deployment is a REST deployment.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ApplicationPath("/api")
public class RestActivator extends Application {
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/contacts/src/main/java/dev/resteasy/examples/resources/ContactListener.java | contacts/src/main/java/dev/resteasy/examples/resources/ContactListener.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2023 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.resources;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.persistence.PostPersist;
import jakarta.persistence.PostRemove;
import jakarta.persistence.PostUpdate;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.sse.Sse;
import jakarta.ws.rs.sse.SseBroadcaster;
import jakarta.ws.rs.sse.SseEventSink;
import org.jboss.logging.Logger;
import dev.resteasy.examples.model.Contact;
/**
* A listener for changes of contact entities. Once an add, update or delete has been made a notification is sent to
* registered subscribers.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ApplicationScoped
@Path("/subscribe")
public class ContactListener {
private static final Logger LOGGER = Logger.getLogger(ContactListener.class);
@Inject
private Sse sse;
@Inject
private SseBroadcaster broadcaster;
@PreDestroy
public void close() {
broadcaster.close(true);
}
/**
* Subscribes a client to the events of an entity.
*
* @param sink the event sink to register
*/
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public void subscribe(@Context final SseEventSink sink) {
broadcaster.register(sink);
}
/**
* Sends a notification to the subscribed clients that an entity as been added.
*
* @param contact the contact that has been added
*/
@PostPersist
public void notifyAdded(final Contact contact) {
notifyClient(contact, "contact.persist.added");
}
/**
* Sends a notification to the subscribed clients that an entity as been updated.
*
* @param contact the contact that has been updated
*/
@PostUpdate
public void notifyUpdated(final Contact contact) {
notifyClient(contact, "contact.persist.updated");
}
/**
* Sends a notification to the subscribed clients that an entity as been deleted.
*
* @param contact the contact that has been deleted
*/
@PostRemove
public void notifyRemoved(final Contact contact) {
notifyClient(contact, "contact.persist.removed");
}
private void notifyClient(final Contact contact, final String name) {
broadcaster.broadcast(sse.newEventBuilder()
.name(name)
.data(contact)
.mediaType(MediaType.APPLICATION_JSON_TYPE).build())
.whenComplete((value, error) -> {
if (error != null) {
LOGGER.errorf(error, "Failed to notify clients of event %s: %s", name, value);
}
});
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/examples-jsapi/src/test/java/dev/resteasy/examples/OrdersTest.java | examples-jsapi/src/test/java/dev/resteasy/examples/OrdersTest.java | package dev.resteasy.examples;
import java.util.Set;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import dev.resteasy.junit.extension.annotations.RequestPath;
import dev.resteasy.junit.extension.annotations.RestBootstrap;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@RestBootstrap(OrdersTest.TestApplication.class)
public class OrdersTest {
@Test
public void createOrder(@RequestPath("/orders/1") final WebTarget target) {
final Response response = target.request().get();
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(), () -> response.readEntity(String.class));
final Order order = response.readEntity(Order.class);
Assertions.assertEquals(1, order.getId());
}
@ApplicationPath("/")
public static class TestApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
return Set.of(Orders.class);
}
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/examples-jsapi/src/main/java/dev/resteasy/examples/Order.java | examples-jsapi/src/main/java/dev/resteasy/examples/Order.java | package dev.resteasy.examples;
import java.math.BigDecimal;
import java.util.Objects;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
public class Order {
private int id;
private int items;
private BigDecimal total;
public Order() {
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public int getItems() {
return items;
}
public void setItems(final int items) {
this.items = items;
}
public BigDecimal getTotal() {
return total;
}
public void setTotal(final BigDecimal total) {
this.total = total;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Order)) {
return false;
}
return id == ((Order) obj).id;
}
@Override
public String toString() {
return "Order[id=" + id + ", items=" + items + ", total=" + total + "]";
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/examples-jsapi/src/main/java/dev/resteasy/examples/OrdersApplication.java | examples-jsapi/src/main/java/dev/resteasy/examples/OrdersApplication.java | package dev.resteasy.examples;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* @author <a href="mailto:l.weinan@gmail.com">Weinan Li</a>
*/
@ApplicationPath("/resteasy")
public class OrdersApplication extends Application {
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/examples-jsapi/src/main/java/dev/resteasy/examples/Orders.java | examples-jsapi/src/main/java/dev/resteasy/examples/Orders.java | package dev.resteasy.examples;
import java.math.BigDecimal;
import java.util.Random;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("orders")
public class Orders {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Order createOrder(@PathParam("id") final int id) {
return createRandomOrder(id);
}
private static Order createRandomOrder(final int id) {
final Random random = new Random();
final Order order = new Order();
order.setId(id);
order.setItems(nonZero(random, 30));
final String total = String.format("%d.%02d", nonZero(random, 300), random.nextInt(99));
order.setTotal(new BigDecimal(total));
return order;
}
private static int nonZero(final Random random, final int bound) {
return nonZero(random, bound, 0);
}
private static int nonZero(final Random random, final int bound, final int count) {
final int result = random.nextInt(bound);
if (result == 0) {
if (count == 10) {
return 1;
}
return nonZero(random, bound, count + 1);
}
return result;
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/json-binding/src/test/java/dev/resteasy/examples/JsonBindingTest.java | json-binding/src/test/java/dev/resteasy/examples/JsonBindingTest.java | package dev.resteasy.examples;
import java.net.URI;
import java.util.Set;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit5.ArquillianExtension;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import dev.resteasy.examples.data.Book;
import dev.resteasy.examples.data.BookListing;
import dev.resteasy.examples.data.BookListingDeserializer;
import dev.resteasy.examples.service.Library;
import dev.resteasy.examples.service.LibraryApplication;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ExtendWith(ArquillianExtension.class)
@RunAsClient
public class JsonBindingTest {
@Deployment
public static WebArchive deployment() {
return ShrinkWrap.create(WebArchive.class, JsonBindingTest.class.getSimpleName() + ".war")
.addClasses(Book.class, BookListing.class, BookListingDeserializer.class, Library.class,
LibraryApplication.class);
}
@ArquillianResource
private URI uri;
@Test
public void books() {
try (
Client client = ClientBuilder.newClient();
Response response = client.target(UriBuilder.fromUri(uri).path("library/books"))
.request(MediaType.APPLICATION_JSON).get()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> response.readEntity(String.class));
final BookListing bookListing = response.readEntity(BookListing.class);
Assertions.assertNotNull(bookListing);
// We should have 3 books
final Set<Book> books = bookListing.getBooks();
Assertions.assertEquals(3, books.size(),
() -> "Expected 3 books, but got " + books);
// The books should be in the ISBN order
final Book[] array = books.toArray(new Book[0]);
Assertions.assertEquals(9780596009786L, array[0].getISBN());
Assertions.assertEquals(9780596158040L, array[1].getISBN());
Assertions.assertEquals(9780596529260L, array[2].getISBN());
}
}
@Test
public void singleBook() {
try (
Client client = ClientBuilder.newClient();
Response response = client.target(UriBuilder.fromUri(uri).path("library/books/9780596158040"))
.request(MediaType.APPLICATION_JSON).get()) {
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> response.readEntity(String.class));
final Book book = response.readEntity(Book.class);
Assertions.assertNotNull(book);
Assertions.assertEquals(9780596158040L, book.getISBN());
Assertions.assertEquals("Bill Burke", book.getAuthor());
Assertions.assertEquals("RESTful Java with JAX-RS", book.getTitle());
}
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/json-binding/src/main/java/dev/resteasy/examples/service/LibraryApplication.java | json-binding/src/main/java/dev/resteasy/examples/service/LibraryApplication.java | package dev.resteasy.examples.service;
import java.util.Set;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@ApplicationPath("/")
public class LibraryApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
return Set.of(Library.class);
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/json-binding/src/main/java/dev/resteasy/examples/service/Library.java | json-binding/src/main/java/dev/resteasy/examples/service/Library.java | package dev.resteasy.examples.service;
import java.util.List;
import java.util.Map;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import dev.resteasy.examples.data.Book;
import dev.resteasy.examples.data.BookListing;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@Path("library")
public class Library {
private final Map<Long, Book> books;
public Library() {
books = Map.ofEntries(
Map.entry(9780596529260L, new Book("Leonard Richardson", 9780596529260L, "RESTful Web Services")),
Map.entry(9780596009786L, new Book("Bill Burke", 9780596009786L, "EJB 3.0")),
Map.entry(9780596158040L, new Book("Bill Burke", 9780596158040L, "RESTful Java with JAX-RS")));
}
@GET
@Path("books")
@Produces(MediaType.APPLICATION_JSON)
public BookListing getBooksMapped() {
return new BookListing(List.copyOf(books.values()));
}
@GET
@Path("books/{isbn}")
@Produces(MediaType.APPLICATION_JSON)
public Response getBook(@PathParam("isbn") final long isbn) {
final Book book = books.get(isbn);
if (book == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(book).build();
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/json-binding/src/main/java/dev/resteasy/examples/data/Book.java | json-binding/src/main/java/dev/resteasy/examples/data/Book.java | package dev.resteasy.examples.data;
import java.util.Objects;
import jakarta.json.bind.annotation.JsonbPropertyOrder;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@JsonbPropertyOrder({
"title",
"author",
"ISBN"
})
public class Book implements Comparable<Book> {
private String author;
private long ISBN;
private String title;
public Book() {
}
public Book(String author, long ISBN, String title) {
this.author = author;
this.ISBN = ISBN;
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public long getISBN() {
return ISBN;
}
public void setISBN(long ISBN) {
this.ISBN = ISBN;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public int compareTo(final Book o) {
return Long.compare(ISBN, o.ISBN);
}
@Override
public int hashCode() {
return Objects.hash(Long.hashCode(ISBN));
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Book)) {
return false;
}
final Book other = (Book) obj;
return ISBN == other.ISBN;
}
@Override
public String toString() {
return "Book[title=" + title + ", author=" + author + ", ISBN=" + ISBN + "]";
}
} | java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/json-binding/src/main/java/dev/resteasy/examples/data/BookListingDeserializer.java | json-binding/src/main/java/dev/resteasy/examples/data/BookListingDeserializer.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.data;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import jakarta.json.bind.serializer.DeserializationContext;
import jakarta.json.bind.serializer.JsonbDeserializer;
import jakarta.json.stream.JsonParser;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
public class BookListingDeserializer implements JsonbDeserializer<BookListing> {
@Override
public BookListing deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) {
final List<Book> books = new ArrayList<>();
while (parser.hasNext()) {
final JsonParser.Event event = parser.next();
if (event == JsonParser.Event.START_OBJECT) {
books.add(ctx.deserialize(Book.class, parser));
}
if (event == JsonParser.Event.END_OBJECT) {
break;
}
}
return new BookListing(books);
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/json-binding/src/main/java/dev/resteasy/examples/data/BookListing.java | json-binding/src/main/java/dev/resteasy/examples/data/BookListing.java | package dev.resteasy.examples.data;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
import jakarta.json.bind.annotation.JsonbCreator;
import jakarta.json.bind.annotation.JsonbProperty;
import jakarta.json.bind.annotation.JsonbTypeDeserializer;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@JsonbTypeDeserializer(BookListingDeserializer.class)
public class BookListing {
private final Set<Book> books;
@JsonbCreator
public BookListing(@JsonbProperty Collection<Book> books) {
this.books = new TreeSet<>(books);
}
public Set<Book> getBooks() {
return books;
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/bootstrap-cdi/src/test/java/dev/resteasy/quickstart/bootstrap/GreeterTestCase.java | bootstrap-cdi/src/test/java/dev/resteasy/quickstart/bootstrap/GreeterTestCase.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.quickstart.bootstrap;
import java.util.concurrent.TimeUnit;
import jakarta.ws.rs.SeBootstrap;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
public class GreeterTestCase {
private static SeBootstrap.Instance INSTANCE;
@BeforeAll
public static void startInstance() throws Exception {
INSTANCE = SeBootstrap.start(RestActivator.class)
.toCompletableFuture().get(10, TimeUnit.SECONDS);
Assertions.assertNotNull(INSTANCE, "Failed to start instance");
}
@AfterAll
public static void stopInstance() throws Exception {
if (INSTANCE != null) {
INSTANCE.stop()
.toCompletableFuture()
.get(10, TimeUnit.SECONDS);
}
}
@Test
public void greet() {
try (Client client = ClientBuilder.newClient()) {
final String name = System.getProperty("user.name", "RESTEasy");
final Response response = client.target(INSTANCE.configuration().baseUriBuilder().path("/rest/" + name))
.request()
.get();
Assertions.assertEquals(Response.Status.OK, response.getStatusInfo(),
() -> String.format("Expected 200 got %d: %s", response.getStatus(), response.readEntity(String.class)));
Assertions.assertEquals(String.format("Hello %s!", name), response.readEntity(String.class));
}
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/bootstrap-cdi/src/main/java/dev/resteasy/quickstart/bootstrap/Greeter.java | bootstrap-cdi/src/main/java/dev/resteasy/quickstart/bootstrap/Greeter.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.quickstart.bootstrap;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.validation.constraints.NotNull;
/**
* A simple greeter CDI bean.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ApplicationScoped
public class Greeter {
/**
* Returns a greeting for the name provided.
*
* @param name the name to add to the greeting
* @return a greeting
*/
public String greet(@NotNull final String name) {
return "Hello " + name + "!";
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/bootstrap-cdi/src/main/java/dev/resteasy/quickstart/bootstrap/RestActivator.java | bootstrap-cdi/src/main/java/dev/resteasy/quickstart/bootstrap/RestActivator.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.quickstart.bootstrap;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* Activates the REST application.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ApplicationPath("/rest")
public class RestActivator extends Application {
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/bootstrap-cdi/src/main/java/dev/resteasy/quickstart/bootstrap/Main.java | bootstrap-cdi/src/main/java/dev/resteasy/quickstart/bootstrap/Main.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.quickstart.bootstrap;
import jakarta.ws.rs.SeBootstrap;
/**
* An entry point for starting a REST container
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
public class Main {
private static final boolean USE_CONSOLE = System.console() != null;
public static void main(final String[] args) throws Exception {
System.setProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager");
SeBootstrap.start(RestActivator.class)
.thenAccept(instance -> {
instance.stopOnShutdown(stopResult -> print("Stopped container (%s)", stopResult.unwrap(Object.class)));
print("Container running at %s",
instance.configuration().baseUri());
print("Example: %s",
instance.configuration().baseUriBuilder().path("rest/" + System.getProperty("user.name")).build());
print("Send SIGKILL to shutdown container");
});
Thread.currentThread().join();
}
private static void print(final String fmt, final Object... args) {
if (USE_CONSOLE) {
System.console().format(fmt, args)
.printf("%n");
} else {
System.out.printf(fmt, args);
System.out.println();
}
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/bootstrap-cdi/src/main/java/dev/resteasy/quickstart/bootstrap/GreetingResource.java | bootstrap-cdi/src/main/java/dev/resteasy/quickstart/bootstrap/GreetingResource.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.quickstart.bootstrap;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
/**
* A simple resource for creating a greeting.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@Path("/")
public class GreetingResource {
@Inject
private Greeter greeter;
/**
* A {@link GET} method which returns a greeting for the name passed in, in plain text.
*
* @param name the name for the greeting
* @return a response with a greeting in plain text
*/
@GET
@Path("/{name}")
@Produces(MediaType.TEXT_PLAIN)
public Response greet(@PathParam("name") final String name) {
return Response.ok(greeter.greet(name)).build();
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/file-upload/src/test/java/dev/resteasy/examples/resources/FileResourceTest.java | file-upload/src/test/java/dev/resteasy/examples/resources/FileResourceTest.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2025 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.resources;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import jakarta.json.JsonArray;
import jakarta.json.JsonObject;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.EntityPart;
import jakarta.ws.rs.core.GenericEntity;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit5.container.annotation.ArquillianTest;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import dev.resteasy.examples.Environment;
import dev.resteasy.examples.SizeUnit;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ArquillianTest
@RunAsClient
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class FileResourceTest {
@ArquillianResource
private URI baseURI;
@Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(
FileResource.class,
RestActivator.class,
Environment.class,
SizeUnit.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Test
@Order(1)
public void uploadFile() throws Exception {
final Path file = createTestFile(100);
try (Client client = ClientBuilder.newClient()) {
// Create the entity parts for the request
final List<EntityPart> multipart = List.of(
EntityPart.withName("file")
.content(Files.readAllBytes(file))
.fileName(file.getFileName().toString())
.mediaType(MediaType.APPLICATION_OCTET_STREAM_TYPE)
.build());
try (Response response = client.target(createUri("/api/upload")).request()
.post(Entity.entity(new GenericEntity<>(multipart) {
}, MediaType.MULTIPART_FORM_DATA_TYPE))) {
Assertions.assertEquals(200, response.getStatus(),
() -> String.format("File upload failed: %s", response.readEntity(String.class)));
final JsonObject json = response.readEntity(JsonObject.class);
Assertions.assertEquals(file.getFileName().toString(), json.getString("fileName"),
() -> String.format("Expected file name of %s in %s", file.getFileName().toString(), json));
}
}
}
@Test
@Order(2)
public void downloadFile() throws Exception {
final Path file = createTestFile(1000);
try (Client client = ClientBuilder.newClient()) {
// Create the entity parts for the request
final List<EntityPart> multipart = List.of(
EntityPart.withName("file")
.content(Files.readAllBytes(file))
.fileName(file.getFileName().toString())
.mediaType(MediaType.APPLICATION_OCTET_STREAM_TYPE)
.build());
try (Response response = client.target(createUri("/api/upload")).request()
.post(Entity.entity(new GenericEntity<>(multipart) {
}, MediaType.MULTIPART_FORM_DATA_TYPE))) {
Assertions.assertEquals(200, response.getStatus(),
() -> String.format("File upload failed: %s", response.readEntity(String.class)));
final JsonObject json = response.readEntity(JsonObject.class);
Assertions.assertEquals(file.getFileName().toString(), json.getString("fileName"),
() -> String.format("Expected file name of %s in %s", file.getFileName().toString(), json));
}
// The file has been uploaded, attempt to download it
try (Response response = client
.target(createUri(
"/api/upload/" + URLEncoder.encode(file.getFileName().toString(), StandardCharsets.UTF_8)))
.request().get()) {
Assertions.assertEquals(200, response.getStatus(),
() -> String.format("File download failed: %s", response.readEntity(String.class)));
// Check that the download String matches the data from the file
Assertions.assertEquals(Files.readString(file), response.readEntity(String.class));
}
}
}
@Test
@Order(3)
public void directoryListing() {
try (Client client = ClientBuilder.newClient()) {
try (Response response = client.target(createUri("/api/upload")).request().get()) {
Assertions.assertEquals(200, response.getStatus(),
() -> String.format("File query failed: %s", response.readEntity(String.class)));
// The download object should be a JSON array and there should be two entries
final JsonArray json = response.readEntity(JsonArray.class);
Assertions.assertEquals(2, json.size());
}
}
}
private URI createUri(final String path) {
return (UriBuilder.fromUri(baseURI).path(path)).build();
}
private static Path createTestFile(final int len) throws IOException {
final Path file = Files.createTempFile("file-upload-", ".txt");
Files.writeString(file, ("a" + System.lineSeparator()).repeat(len));
return file;
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/file-upload/src/main/java/dev/resteasy/examples/Environment.java | file-upload/src/main/java/dev/resteasy/examples/Environment.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2025 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Optional;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
public class Environment {
private static final Path UPLOAD_DIRECTORY;
private static final boolean SUPPORTS_POSIX;
static {
final String user = System.getProperty("user.name", "anonymous");
final String uploadDirectory = System.getProperty("upload.directory");
Path dir = null;
if (uploadDirectory == null) {
final String jbossHome = System.getProperty("jboss.home.dir");
if (jbossHome != null) {
dir = Path.of(jbossHome, "file-uploads", user);
}
} else {
dir = Path.of(uploadDirectory, user);
}
try {
if (dir == null) {
dir = Files.createTempDirectory("file-uploads").resolve(user);
}
if (Files.notExists(dir)) {
Files.createDirectories(dir);
}
UPLOAD_DIRECTORY = dir;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
SUPPORTS_POSIX = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
}
public static Path uploadDirectory() {
return UPLOAD_DIRECTORY;
}
public static boolean supportsPosix() {
return SUPPORTS_POSIX;
}
public static Optional<String> resolvePermissions(final Path file) {
if (Files.isRegularFile(file)) {
if (SUPPORTS_POSIX) {
try {
return Optional.of(PosixFilePermissions.toString(Files.getPosixFilePermissions(file)));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
return Optional.empty();
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/file-upload/src/main/java/dev/resteasy/examples/SizeUnit.java | file-upload/src/main/java/dev/resteasy/examples/SizeUnit.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2025 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples;
import java.text.DecimalFormat;
public enum SizeUnit {
BYTE(1L, "B") {
@Override
public String toString(final long size) {
return size + "B";
}
},
KILOBYTE(BYTE, "KB"),
MEGABYTE(KILOBYTE, "MB"),
GIGABYTE(MEGABYTE, "GB"),
TERABYTE(GIGABYTE, "TB"),
PETABYTE(TERABYTE, "PB"),
EXABYTE(TERABYTE, "EB"),
;
private static final DecimalFormat FORMAT = new DecimalFormat("#.##");
private final long sizeInBytes;
private final String abbreviation;
SizeUnit(final long sizeInBytes, final String abbreviation) {
this.sizeInBytes = sizeInBytes;
this.abbreviation = abbreviation;
}
SizeUnit(final SizeUnit base, final String abbreviation) {
this.sizeInBytes = base.sizeInBytes << 10;
this.abbreviation = abbreviation;
}
/**
* Returns the abbreviation for the unit.
*
* @return the abbreviation for the unit
*/
public String abbreviation() {
return abbreviation;
}
/**
* Converts the given size to bytes from this unit. For example {@code SizeUnit.KILOBYTES.toBytes(1L)} would return
* 1024.
*
* @param size the size to convert
*
* @return the size in bytes
*/
public long toBytes(final long size) {
return Math.multiplyExact(sizeInBytes, size);
}
/**
* Converts the given size to the given unit to this unit.
*
* @param size the size to convert
* @param unit the unit to convert the size to
*
* @return the converted units
*/
public double convert(final long size, final SizeUnit unit) {
if (unit == BYTE) {
return toBytes(size);
}
final long bytes = toBytes(size);
return ((double) bytes / unit.sizeInBytes);
}
/**
* Converts the size to a human-readable string format.
* <p>
* For example {@code SizeUnit.KILOBYTE.toString(1024L)} would return "1 KB".
* </p>
*
* @param size the size, in bytes
*
* @return a human-readable size
*/
public String toString(final long size) {
return FORMAT.format((double) size / sizeInBytes) + abbreviation;
}
/**
* Converts the size, in bytes, to a human-readable form. For example {@code 1024} bytes return "1 KB".
*
* @param size the size, in bytes, to convert
*
* @return a human-readable size
*/
public static String toHumanReadable(final long size) {
if (size == 0L) {
return "0B";
}
final SizeUnit[] values = values();
for (int i = values.length - 1; i >= 0; i--) {
final SizeUnit unit = values[i];
if (size >= unit.sizeInBytes) {
return unit.toString(size);
}
}
return size + "B";
}
} | java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/file-upload/src/main/java/dev/resteasy/examples/resources/RestActivator.java | file-upload/src/main/java/dev/resteasy/examples/resources/RestActivator.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2025 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.resources;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* Indicates that the deployment is a REST deployment.
*
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@ApplicationPath("/api")
public class RestActivator extends Application {
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
resteasy/resteasy-examples | https://github.com/resteasy/resteasy-examples/blob/2135273a1334b59f52979ce7e0dd3c712f342084/file-upload/src/main/java/dev/resteasy/examples/resources/FileResource.java | file-upload/src/main/java/dev/resteasy/examples/resources/FileResource.java | /*
* JBoss, Home of Professional Open Source.
*
* Copyright 2025 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 dev.resteasy.examples.resources;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.stream.Collectors;
import jakarta.json.Json;
import jakarta.json.JsonArray;
import jakarta.json.JsonArrayBuilder;
import jakarta.json.JsonObject;
import jakarta.json.JsonObjectBuilder;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.EntityPart;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import dev.resteasy.examples.Environment;
import dev.resteasy.examples.SizeUnit;
/**
* @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a>
*/
@Path("/upload")
public class FileResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/dir")
public Response dir() {
return Response.ok(Json.createObjectBuilder().add("dir", Environment.uploadDirectory().toString()).build()).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonArray listDirectory() throws IOException {
final JsonArrayBuilder builder = Json.createArrayBuilder();
try (var paths = Files.walk(Environment.uploadDirectory())) {
for (var path : paths.filter(p -> !p.equals(Environment.uploadDirectory())).sorted().collect(Collectors.toList())) {
builder.add(toJson(path));
}
}
return builder.build();
}
@GET
@Path("{fileName}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response download(@PathParam("fileName") String fileName) throws IOException {
final var file = Environment.uploadDirectory().resolve(fileName);
if (Files.notExists(file)) {
return Response.status(Response.Status.NOT_FOUND).build();
}
final Response.ResponseBuilder builder = Response.ok(Files.newInputStream(file));
builder.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
builder.header("Content-Length", Files.size(file));
return Response.ok(Files.newInputStream(file)).build();
}
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public JsonObject uploadFile(@FormParam("file") final EntityPart file) throws IOException {
if (file.getFileName().isEmpty()) {
throw new BadRequestException("No fle was uploaded.");
}
final String fileName = file.getFileName().get();
if (fileName.isBlank()) {
throw new BadRequestException("The file name could not be determined.");
}
// Copy the contents to a file
final var uploadFile = Environment.uploadDirectory().resolve(fileName);
Files.copy(file.getContent(), uploadFile, StandardCopyOption.REPLACE_EXISTING);
return toJson(uploadFile);
}
private static JsonObject toJson(final java.nio.file.Path file) throws IOException {
final String mimeType = Files.probeContentType(file);
final JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("fileName", Environment.uploadDirectory().relativize(file).toString());
if (mimeType == null) {
builder.addNull("mimeType");
} else {
builder.add("mimeType", mimeType);
}
builder.add("size", SizeUnit.toHumanReadable(Files.size(file)));
Environment.resolvePermissions(file)
.ifPresent(permissions -> builder.add("permissions", permissions));
return builder.build();
}
}
| java | Apache-2.0 | 2135273a1334b59f52979ce7e0dd3c712f342084 | 2026-01-05T02:38:34.394954Z | false |
aJIEw/PhoneCallApp | https://github.com/aJIEw/PhoneCallApp/blob/54ade14439d949d2bd9b5b75ea346d2803dc0cf6/app/src/test/java/com/ajiew/phonecallapp/ExampleUnitTest.java | app/src/test/java/com/ajiew/phonecallapp/ExampleUnitTest.java | package com.ajiew.phonecallapp;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | java | Apache-2.0 | 54ade14439d949d2bd9b5b75ea346d2803dc0cf6 | 2026-01-05T02:38:23.385121Z | false |
aJIEw/PhoneCallApp | https://github.com/aJIEw/PhoneCallApp/blob/54ade14439d949d2bd9b5b75ea346d2803dc0cf6/app/src/main/java/com/ajiew/phonecallapp/MainActivity.java | app/src/main/java/com/ajiew/phonecallapp/MainActivity.java | package com.ajiew.phonecallapp;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.role.RoleManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.telecom.TelecomManager;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.ajiew.phonecallapp.listenphonecall.CallListenerService;
import java.lang.reflect.Field;
public class MainActivity extends AppCompatActivity {
@SuppressLint("UseSwitchCompatOrMaterialCode")
private Switch switchPhoneCall;
@SuppressLint("UseSwitchCompatOrMaterialCode")
private Switch switchListenCall;
private CompoundButton.OnCheckedChangeListener switchCallCheckChangeListener;
private final ActivityResultLauncher<Intent> dialerRequestLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
Toast.makeText(MainActivity.this, getString(R.string.app_name) + " 已成为默认电话应用",
Toast.LENGTH_SHORT).show();
}
});
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
EdgeToEdge.enable(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
switchPhoneCall = findViewById(R.id.switch_default_phone_call);
switchListenCall = findViewById(R.id.switch_call_listenr);
switchPhoneCall.setOnClickListener(v -> {
// 发起将本应用设为默认电话应用的请求,仅支持 Android M 及以上
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (switchPhoneCall.isChecked()) {
// Android 10 之后需要通过 RoleManager 修改默认电话应用
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
RoleManager roleManager = (RoleManager) getSystemService(Context.ROLE_SERVICE);
Intent intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_DIALER);
dialerRequestLauncher.launch(intent);
} else {
Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, getPackageName());
startActivity(intent);
}
} else {
// 取消时跳转到默认设置页面
startActivity(new Intent("android.settings.MANAGE_DEFAULT_APPS_SETTINGS"));
}
} else {
Toast.makeText(MainActivity.this, "Android 6.0 以上才支持修改默认电话应用!", Toast.LENGTH_LONG)
.show();
switchPhoneCall.setChecked(false);
}
});
// 检查是否开启了权限
switchCallCheckChangeListener = (buttonView, isChecked) -> {
if (isChecked && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !Settings.canDrawOverlays(MainActivity.this)) {
// 请求 悬浮框 权限
askForDrawOverlay();
// 未开启时清除选中状态,同时避免回调
switchListenCall.setOnCheckedChangeListener(null);
switchListenCall.setChecked(false);
switchListenCall.setOnCheckedChangeListener(switchCallCheckChangeListener);
return;
}
boolean granted = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
if (isChecked && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !granted) {
Toast.makeText(this, "缺少获取电话状态权限", Toast.LENGTH_SHORT).show();
return;
}
Intent callListener = new Intent(MainActivity.this, CallListenerService.class);
if (isChecked) {
startService(callListener);
Toast.makeText(this, "电话监听服务已开启", Toast.LENGTH_SHORT).show();
} else {
stopService(callListener);
Toast.makeText(this, "电话监听服务已关闭", Toast.LENGTH_SHORT).show();
}
};
switchListenCall.setOnCheckedChangeListener(switchCallCheckChangeListener);
}
private void askForDrawOverlay() {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("允许显示悬浮框")
.setMessage("为了使电话监听服务正常工作,请允许这项权限")
.setPositiveButton("去设置", (dialog, which) -> {
openDrawOverlaySettings();
dialog.dismiss();
})
.setNegativeButton("稍后再说", (dialog, which) -> dialog.dismiss())
.create();
//noinspection ConstantConditions
alertDialog.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
alertDialog.show();
}
/**
* 跳转悬浮窗管理设置界面
*/
private void openDrawOverlaySettings() {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M 以上引导用户去系统设置中打开允许悬浮窗
// 使用反射是为了用尽可能少的代码保证在大部分机型上都可用
try {
Context context = this;
Class clazz = Settings.class;
Field field = clazz.getDeclaredField("ACTION_MANAGE_OVERLAY_PERMISSION");
Intent intent = new Intent(field.get(null).toString());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("package:" + context.getPackageName()));
context.startActivity(intent);
} catch (Exception e) {
Toast.makeText(this, "请在悬浮窗管理中打开权限", Toast.LENGTH_LONG).show();
}
}
}
@Override
protected void onResume() {
super.onResume();
switchPhoneCall.setChecked(isDefaultPhoneCallApp());
switchListenCall.setChecked(isServiceRunning(CallListenerService.class));
}
/**
* Android M 及以上检查是否是系统默认电话应用
*/
public boolean isDefaultPhoneCallApp() {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
TelecomManager manger = (TelecomManager) getSystemService(TELECOM_SERVICE);
if (manger != null && manger.getDefaultDialerPackage() != null) {
return manger.getDefaultDialerPackage().equals(getPackageName());
}
}
return false;
}
public boolean isServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
if (manager == null) return false;
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(
Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | 54ade14439d949d2bd9b5b75ea346d2803dc0cf6 | 2026-01-05T02:38:23.385121Z | false |
aJIEw/PhoneCallApp | https://github.com/aJIEw/PhoneCallApp/blob/54ade14439d949d2bd9b5b75ea346d2803dc0cf6/app/src/main/java/com/ajiew/phonecallapp/ActivityStack.java | app/src/main/java/com/ajiew/phonecallapp/ActivityStack.java | package com.ajiew.phonecallapp;
import android.app.Activity;
import java.util.ArrayList;
import java.util.List;
public class ActivityStack {
private static final ActivityStack INSTANCE = new ActivityStack();
private List<Activity> activities = new ArrayList<>();
public static ActivityStack getInstance() {
return INSTANCE;
}
public void addActivity(Activity activity) {
activities.add(activity);
}
public Activity getTopActivity() {
if (activities.isEmpty()) {
return null;
}
return activities.get(activities.size() - 1);
}
public void finishTopActivity() {
if (!activities.isEmpty()) {
activities.remove(activities.size() - 1).finish();
}
}
public void finishActivity(Activity activity) {
if (activity != null) {
activities.remove(activity);
activity.finish();
}
}
public void finishActivity(Class activityClass) {
for (Activity activity : activities) {
if (activity.getClass().equals(activityClass)) {
finishActivity(activity);
}
}
}
public void finishAllActivity() {
if (!activities.isEmpty()) {
for (Activity activity : activities) {
activity.finish();
activities.remove(activity);
}
}
}
}
| java | Apache-2.0 | 54ade14439d949d2bd9b5b75ea346d2803dc0cf6 | 2026-01-05T02:38:23.385121Z | false |
aJIEw/PhoneCallApp | https://github.com/aJIEw/PhoneCallApp/blob/54ade14439d949d2bd9b5b75ea346d2803dc0cf6/app/src/main/java/com/ajiew/phonecallapp/phonecallui/PhoneCallService.java | app/src/main/java/com/ajiew/phonecallapp/phonecallui/PhoneCallService.java | package com.ajiew.phonecallapp.phonecallui;
import android.os.Build;
import android.telecom.Call;
import android.telecom.InCallService;
import androidx.annotation.RequiresApi;
import com.ajiew.phonecallapp.ActivityStack;
/**
* 监听电话通信状态的服务,实现该类的同时必须提供电话管理的 UI
*
* @author aJIEw
* @see PhoneCallActivity
* @see android.telecom.InCallService
*/
@RequiresApi(api = Build.VERSION_CODES.M)
public class PhoneCallService extends InCallService {
private final Call.Callback callback = new Call.Callback() {
@Override
public void onStateChanged(Call call, int state) {
super.onStateChanged(call, state);
switch (state) {
case Call.STATE_ACTIVE: {
break;
}
case Call.STATE_DISCONNECTED: {
ActivityStack.getInstance().finishActivity(PhoneCallActivity.class);
break;
}
}
}
};
@Override
public void onCallAdded(Call call) {
super.onCallAdded(call);
call.registerCallback(callback);
PhoneCallManager.call = call;
CallType callType = null;
if (call.getState() == Call.STATE_RINGING) {
callType = CallType.CALL_IN;
} else if (call.getState() == Call.STATE_CONNECTING) {
callType = CallType.CALL_OUT;
}
if (callType != null) {
Call.Details details = call.getDetails();
String phoneNumber = details.getHandle().getSchemeSpecificPart();
PhoneCallActivity.actionStart(this, phoneNumber, callType);
}
}
@Override
public void onCallRemoved(Call call) {
super.onCallRemoved(call);
call.unregisterCallback(callback);
PhoneCallManager.call = null;
}
public enum CallType {
CALL_IN,
CALL_OUT,
}
}
| java | Apache-2.0 | 54ade14439d949d2bd9b5b75ea346d2803dc0cf6 | 2026-01-05T02:38:23.385121Z | false |
aJIEw/PhoneCallApp | https://github.com/aJIEw/PhoneCallApp/blob/54ade14439d949d2bd9b5b75ea346d2803dc0cf6/app/src/main/java/com/ajiew/phonecallapp/phonecallui/PhoneCallActivity.java | app/src/main/java/com/ajiew/phonecallapp/phonecallui/PhoneCallActivity.java | package com.ajiew.phonecallapp.phonecallui;
import static com.ajiew.phonecallapp.listenphonecall.CallListenerService.formatPhoneNumber;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import com.ajiew.phonecallapp.ActivityStack;
import com.ajiew.phonecallapp.R;
import java.util.Timer;
import java.util.TimerTask;
/**
* 提供接打电话的界面,仅支持 Android M (6.0, API 23) 及以上的系统
*
* @author aJIEw
*/
@RequiresApi(api = Build.VERSION_CODES.M)
public class PhoneCallActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tvCallNumberLabel;
private TextView tvCallNumber;
private TextView tvPickUp;
private TextView tvCallingTime;
private TextView tvHangUp;
private PhoneCallManager phoneCallManager;
private PhoneCallService.CallType callType;
private String phoneNumber;
private Timer onGoingCallTimer;
private int callingTime;
public static void actionStart(Context context, String phoneNumber,
PhoneCallService.CallType callType) {
Intent intent = new Intent(context, PhoneCallActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_MIME_TYPES, callType);
intent.putExtra(Intent.EXTRA_PHONE_NUMBER, phoneNumber);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
EdgeToEdge.enable(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_call);
ActivityStack.getInstance().addActivity(this);
initData();
initView();
}
private void initData() {
phoneCallManager = new PhoneCallManager(this);
onGoingCallTimer = new Timer();
if (getIntent() != null) {
phoneNumber = getIntent().getStringExtra(Intent.EXTRA_PHONE_NUMBER);
callType = (PhoneCallService.CallType) getIntent().getSerializableExtra(Intent.EXTRA_MIME_TYPES);
}
}
private void initView() {
int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION //hide navigationBar
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
getWindow().getDecorView().setSystemUiVisibility(uiOptions);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
tvCallNumberLabel = findViewById(R.id.tv_call_number_label);
tvCallNumber = findViewById(R.id.tv_call_number);
tvPickUp = findViewById(R.id.tv_phone_pick_up);
tvCallingTime = findViewById(R.id.tv_phone_calling_time);
tvHangUp = findViewById(R.id.tv_phone_hang_up);
tvCallNumber.setText(formatPhoneNumber(phoneNumber));
tvPickUp.setOnClickListener(this);
tvHangUp.setOnClickListener(this);
// 打进的电话
if (callType == PhoneCallService.CallType.CALL_IN) {
tvCallNumberLabel.setText("来电号码");
tvPickUp.setVisibility(View.VISIBLE);
}
// 打出的电话
else if (callType == PhoneCallService.CallType.CALL_OUT) {
tvCallNumberLabel.setText("呼叫号码");
tvPickUp.setVisibility(View.GONE);
phoneCallManager.openSpeaker();
}
showOnLockScreen();
}
public void showOnLockScreen() {
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.tv_phone_pick_up) {
phoneCallManager.answer();
tvPickUp.setVisibility(View.GONE);
tvCallingTime.setVisibility(View.VISIBLE);
onGoingCallTimer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@SuppressLint("SetTextI18n")
@Override
public void run() {
callingTime++;
tvCallingTime.setText("通话中:" + getCallingTime());
}
});
}
}, 0, 1000);
} else if (v.getId() == R.id.tv_phone_hang_up) {
phoneCallManager.disconnect();
stopTimer();
}
}
private String getCallingTime() {
int minute = callingTime / 60;
int second = callingTime % 60;
return (minute < 10 ? "0" + minute : minute) +
":" +
(second < 10 ? "0" + second : second);
}
private void stopTimer() {
if (onGoingCallTimer != null) {
onGoingCallTimer.cancel();
}
callingTime = 0;
}
@Override
protected void onDestroy() {
super.onDestroy();
phoneCallManager.destroy();
}
}
| java | Apache-2.0 | 54ade14439d949d2bd9b5b75ea346d2803dc0cf6 | 2026-01-05T02:38:23.385121Z | false |
aJIEw/PhoneCallApp | https://github.com/aJIEw/PhoneCallApp/blob/54ade14439d949d2bd9b5b75ea346d2803dc0cf6/app/src/main/java/com/ajiew/phonecallapp/phonecallui/PhoneCallManager.java | app/src/main/java/com/ajiew/phonecallapp/phonecallui/PhoneCallManager.java | package com.ajiew.phonecallapp.phonecallui;
import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.telecom.Call;
import android.telecom.VideoProfile;
import androidx.annotation.RequiresApi;
@RequiresApi(api = Build.VERSION_CODES.M)
public class PhoneCallManager {
public static Call call;
private Context context;
private AudioManager audioManager;
public PhoneCallManager(Context context) {
this.context = context;
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
/**
* 接听电话
*/
public void answer() {
if (call != null) {
call.answer(VideoProfile.STATE_AUDIO_ONLY);
openSpeaker();
}
}
/**
* 断开电话,包括来电时的拒接以及接听后的挂断
*/
public void disconnect() {
if (call != null) {
call.disconnect();
}
}
/**
* 打开免提
*/
public void openSpeaker() {
if (audioManager != null) {
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
}
}
/**
* 销毁资源
*/
public void destroy() {
call = null;
context = null;
audioManager = null;
}
}
| java | Apache-2.0 | 54ade14439d949d2bd9b5b75ea346d2803dc0cf6 | 2026-01-05T02:38:23.385121Z | false |
aJIEw/PhoneCallApp | https://github.com/aJIEw/PhoneCallApp/blob/54ade14439d949d2bd9b5b75ea346d2803dc0cf6/app/src/main/java/com/ajiew/phonecallapp/listenphonecall/CallListenerService.java | app/src/main/java/com/ajiew/phonecallapp/listenphonecall/CallListenerService.java | package com.ajiew.phonecallapp.listenphonecall;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyCallback;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.ajiew.phonecallapp.MainActivity;
import com.ajiew.phonecallapp.R;
public class CallListenerService extends Service {
private View phoneCallView;
private TextView tvCallNumber;
private Button btnOpenApp;
private WindowManager windowManager;
private WindowManager.LayoutParams params;
private PhoneStateListenerCompat phoneStateListenerCompat;
private String callNumber;
private boolean hasShown;
private boolean isCallingIn;
@Override
public void onCreate() {
super.onCreate();
initPhoneStateListener();
initPhoneCallView();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* 初始化来电状态监听器
*/
private void initPhoneStateListener() {
phoneStateListenerCompat = new PhoneStateListenerCompat() {
@Override
public void onCallStateChanged(int state) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE: // 待机,即无电话时,挂断时触发
dismiss();
break;
case TelephonyManager.CALL_STATE_RINGING: // 响铃,来电时触发
isCallingIn = true;
updateUI();
show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK: // 摘机,接听或拨出电话时触发
updateUI();
show();
break;
default:
break;
}
}
};
phoneStateListenerCompat.startListening(this);
}
private void initPhoneCallView() {
windowManager = (WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE);
int width = windowManager.getDefaultDisplay().getWidth();
int height = windowManager.getDefaultDisplay().getHeight();
params = new WindowManager.LayoutParams();
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
params.width = width;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
// 设置图片格式,效果为背景透明
params.format = PixelFormat.TRANSLUCENT;
// 设置 Window flag 为系统级弹框 | 覆盖表层
params.type = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
WindowManager.LayoutParams.TYPE_PHONE;
// 不可聚集(不响应返回键)| 全屏
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
// API 19 以上则还可以开启透明状态栏与导航栏
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
params.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
}
FrameLayout interceptorLayout = new FrameLayout(this) {
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
return true;
}
}
return super.dispatchKeyEvent(event);
}
};
phoneCallView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.view_phone_call, interceptorLayout);
tvCallNumber = phoneCallView.findViewById(R.id.tv_call_number);
btnOpenApp = phoneCallView.findViewById(R.id.btn_open_app);
btnOpenApp.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
CallListenerService.this.startActivity(intent);
});
}
/**
* 显示顶级弹框展示通话信息
*/
private void show() {
if (!hasShown) {
windowManager.addView(phoneCallView, params);
hasShown = true;
}
}
/**
* 取消显示
*/
private void dismiss() {
if (hasShown) {
windowManager.removeView(phoneCallView);
isCallingIn = false;
hasShown = false;
}
}
private void updateUI() {
tvCallNumber.setText(formatPhoneNumber(callNumber));
int callTypeDrawable = isCallingIn ? R.drawable.ic_phone_call_in : R.drawable.ic_phone_call_out;
tvCallNumber.setCompoundDrawablesWithIntrinsicBounds(null, null,
getResources().getDrawable(callTypeDrawable), null);
}
public static String formatPhoneNumber(String phoneNum) {
if (!TextUtils.isEmpty(phoneNum) && phoneNum.length() == 11) {
return phoneNum.substring(0, 3) + "-"
+ phoneNum.substring(3, 7) + "-"
+ phoneNum.substring(7);
}
return phoneNum;
}
@Override
public void onDestroy() {
super.onDestroy();
phoneStateListenerCompat.stopListening(this);
}
}
| java | Apache-2.0 | 54ade14439d949d2bd9b5b75ea346d2803dc0cf6 | 2026-01-05T02:38:23.385121Z | false |
aJIEw/PhoneCallApp | https://github.com/aJIEw/PhoneCallApp/blob/54ade14439d949d2bd9b5b75ea346d2803dc0cf6/app/src/main/java/com/ajiew/phonecallapp/listenphonecall/PhoneStateListenerCompat.java | app/src/main/java/com/ajiew/phonecallapp/listenphonecall/PhoneStateListenerCompat.java | package com.ajiew.phonecallapp.listenphonecall;
import android.content.Context;
import android.os.Build;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import androidx.annotation.RequiresApi;
/**
* 新的电话状态监听器,适配 {@link android.telephony.TelephonyCallback} 以及老版本的 {@link PhoneStateListener}
*
* @author aJIEw
* Created on: 2025/5/6 16:45
*/
public abstract class PhoneStateListenerCompat {
private PhoneStateListener phoneStateListener;
private TelephonyCallback telephonyCallback;
public void startListening(Context context) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
telephonyCallback = new TelephonyCallback() {
@Override
public void onCallStateChanged(int state) {
Log.d(PhoneStateListenerCompat.class.getSimpleName(), "onCallStateChanged: ");
PhoneStateListenerCompat.this.onCallStateChanged(state);
}
};
tm.registerTelephonyCallback(context.getMainExecutor(), telephonyCallback);
} else {
phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String phoneNumber) {
PhoneStateListenerCompat.this.onCallStateChanged(state);
}
};
tm.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
public void stopListening(Context context) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (telephonyCallback != null) {
tm.unregisterTelephonyCallback(telephonyCallback);
}
} else {
if (phoneStateListener != null) {
tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
}
}
public abstract void onCallStateChanged(int state);
}
@RequiresApi(api = Build.VERSION_CODES.S)
class TelephonyCallback extends android.telephony.TelephonyCallback
implements android.telephony.TelephonyCallback.CallStateListener {
@Override
public void onCallStateChanged(int state) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
// 空闲状态
break;
case TelephonyManager.CALL_STATE_RINGING:
// 来电响铃
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
// 通话中
break;
}
}
}
| java | Apache-2.0 | 54ade14439d949d2bd9b5b75ea346d2803dc0cf6 | 2026-01-05T02:38:23.385121Z | false |
aJIEw/PhoneCallApp | https://github.com/aJIEw/PhoneCallApp/blob/54ade14439d949d2bd9b5b75ea346d2803dc0cf6/app/src/androidTest/java/com/ajiew/phonecallapp/ExampleInstrumentedTest.java | app/src/androidTest/java/com/ajiew/phonecallapp/ExampleInstrumentedTest.java | package com.ajiew.phonecallapp;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.ajiew.phonecallapp", appContext.getPackageName());
}
}
| java | Apache-2.0 | 54ade14439d949d2bd9b5b75ea346d2803dc0cf6 | 2026-01-05T02:38:23.385121Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/WatchlistApp.java | app/src/main/java/com/ronakmanglani/watchlist/WatchlistApp.java | package com.ronakmanglani.watchlist;
import android.app.Application;
import android.content.Context;
public class WatchlistApp extends Application {
// Tag for fragment manager
public static final String TAG_GRID_FRAGMENT = "movie_grid_fragment";
// SharedPreference Keys
public static final String TABLE_USER = "user_settings";
public static final String LAST_SELECTED = "last_drawer_selection";
public static final String THUMBNAIL_SIZE = "thumbnail_size";
public static final String VIEW_MODE = "view_mode";
public static final String VIEW_TYPE = "view_type";
public static final int VIEW_MODE_GRID = 1;
public static final int VIEW_MODE_LIST = 2;
public static final int VIEW_MODE_COMPACT = 3;
public static final int VIEW_TYPE_POPULAR = 1;
public static final int VIEW_TYPE_RATED = 2;
public static final int VIEW_TYPE_UPCOMING = 3;
public static final int VIEW_TYPE_PLAYING = 4;
public static final int VIEW_TYPE_WATCHED = 5;
public static final int VIEW_TYPE_TO_SEE = 6;
// Intent Extra + Bundle Argument + Saved Instance State
public static final String TOOLBAR_TITLE = "toolbar_title";
public static final String MOVIE_ID = "movie_id";
public static final String MOVIE_NAME = "movie_name";
public static final String MOVIE_OBJECT = "movie_object";
public static final String MOVIE_LIST = "movie_list";
public static final String REVIEW_OBJECT = "review_object";
public static final String REVIEW_LIST = "review_list";
public static final String VIDEO_LIST = "video_list";
public static final String PHOTO_LIST = "photo_list";
public static final String CREDIT_TYPE = "credit_type";
public static final String CREDIT_LIST = "credit_list";
public static final String SEARCH_QUERY = "search_query";
public static final String PAGE_TO_DOWNLOAD = "page_to_download";
public static final String TOTAL_PAGES = "total_pages";
public static final String IS_LOADING = "is_loading";
public static final String IS_LOCKED = "is_locked";
public static final int CREDIT_TYPE_CAST = 1;
public static final int CREDIT_TYPE_CREW = 2;
// Initialize context
@Override
public void onCreate() {
super.onCreate();
mAppContext = getApplicationContext();
}
// To access context from any class
private static Context mAppContext;
public static Context getAppContext() {
return mAppContext;
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/util/FileUtil.java | app/src/main/java/com/ronakmanglani/watchlist/util/FileUtil.java | package com.ronakmanglani.watchlist.util;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.ronakmanglani.watchlist.data.MovieColumns;
import com.ronakmanglani.watchlist.data.MovieDatabase;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FileUtil {
// Constructor
private FileUtil() { }
// Copy file from source to destination
public static void copyFile(File source, File destination) throws IOException {
FileInputStream fromFile = new FileInputStream(source);
FileOutputStream toFile = new FileOutputStream(destination);
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = fromFile.getChannel();
toChannel = toFile.getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
try {
if (fromChannel != null) {
fromChannel.close();
}
} finally {
if (toChannel != null) {
toChannel.close();
}
}
}
}
// Function to check if file is a valid database
public static boolean isValidDbFile(File db) {
try {
// Open file as a database
SQLiteDatabase sqlDb = SQLiteDatabase.openDatabase(db.getPath(), null, SQLiteDatabase.OPEN_READONLY);
// Get cursors for both tables
Cursor cursor1 = sqlDb.query(true, MovieDatabase.WATCHED, null, null, null, null, null, null, null);
Cursor cursor2 = sqlDb.query(true, MovieDatabase.TO_SEE, null, null, null, null, null, null, null);
// Check if "TMDB_ID" column exists (else throw exception)
cursor1.getColumnIndexOrThrow(MovieColumns.TMDB_ID);
cursor2.getColumnIndexOrThrow(MovieColumns.TMDB_ID);
// Close database and cursors
sqlDb.close();
cursor1.close();
cursor2.close();
// No exceptions = Valid database
return true;
} catch (Exception e) {
// Exception thrown - Invalid database
return false;
}
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/util/FontUtil.java | app/src/main/java/com/ronakmanglani/watchlist/util/FontUtil.java | package com.ronakmanglani.watchlist.util;
import android.content.Context;
import android.graphics.Typeface;
import com.ronakmanglani.watchlist.WatchlistApp;
import java.util.Hashtable;
public class FontUtil {
public static final String ROBOTO_REGULAR = "fonts/Roboto-Regular.ttf";
public static final String ROBOTO_LIGHT = "fonts/Roboto-Light.ttf";
public static final String ROBOTO_BOLD = "fonts/Roboto-Bold.ttf";
// Constructor
private FontUtil() { }
// Cache fonts in hash table
private static Hashtable<String, Typeface> fontCache = new Hashtable<String, Typeface>();
public static Typeface getTypeface(String name) {
Typeface tf = fontCache.get(name);
if(tf == null) {
try {
tf = Typeface.createFromAsset(WatchlistApp.getAppContext().getAssets(), name);
}
catch (Exception e) {
return null;
}
fontCache.put(name, tf);
}
return tf;
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/util/TextUtil.java | app/src/main/java/com/ronakmanglani/watchlist/util/TextUtil.java | package com.ronakmanglani.watchlist.util;
public class TextUtil {
// Constructor
private TextUtil() { }
// Check if given string is null or empty
public static boolean isNullOrEmpty(String str) {
return (str == null || str.equals("null") || str.equals(""));
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/model/Movie.java | app/src/main/java/com/ronakmanglani/watchlist/model/Movie.java | package com.ronakmanglani.watchlist.model;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
public class Movie implements Parcelable, Serializable {
// Attributes
public String id;
public String title;
public String year;
public String overview;
public String rating;
public String posterImage;
public String backdropImage;
// Constructors
public Movie(String id, String title, String year, String overview, String rating, String posterImage, String backdropImage) {
this.id = id;
this.title = title;
this.year = year;
this.overview = overview;
this.rating = rating;
this.posterImage = posterImage;
this.backdropImage = backdropImage;
}
public Movie(Parcel in) {
this.id = in.readString();
this.title = in.readString();
this.year = in.readString();
this.overview = in.readString();
this.rating = in.readString();
this.posterImage = in.readString();
this.backdropImage = in.readString();
}
// Parcelable Creator
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
public Movie[] newArray(int size) {
return new Movie[size];
}
};
// Parcelling methods
@Override
public void writeToParcel(Parcel out, int i) {
out.writeString(id);
out.writeString(title);
out.writeString(year);
out.writeString(overview);
out.writeString(rating);
out.writeString(posterImage);
out.writeString(backdropImage);
}
@Override
public int describeContents() {
return 0;
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/model/Credit.java | app/src/main/java/com/ronakmanglani/watchlist/model/Credit.java | package com.ronakmanglani.watchlist.model;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
public class Credit implements Parcelable, Serializable {
// Attributes
public String id;
public String name;
public String role;
public String imagePath;
// Constructors
public Credit(String id, String name, String role, String imagePath) {
this.id = id;
this.name = name;
this.role = role;
this.imagePath = imagePath;
}
public Credit(Parcel in) {
this.id = in.readString();
this.name = in.readString();
this.role = in.readString();
this.imagePath = in.readString();
}
// Parcelable Creator
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Credit createFromParcel(Parcel in) {
return new Credit(in);
}
public Credit[] newArray(int size) {
return new Credit[size];
}
};
// Parcelling methods
@Override
public void writeToParcel(Parcel out, int i) {
out.writeString(id);
out.writeString(name);
out.writeString(role);
out.writeString(imagePath);
}
@Override
public int describeContents() {
return 0;
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/model/MovieDetail.java | app/src/main/java/com/ronakmanglani/watchlist/model/MovieDetail.java | package com.ronakmanglani.watchlist.model;
import android.os.Parcel;
import android.os.Parcelable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MovieDetail implements Parcelable {
// Attributes
public String id;
public String imdbId;
public String title;
public String tagline;
public String releaseDate;
public String runtime;
public String overview;
public String voteAverage;
public String voteCount;
public String backdropImage;
public String posterImage;
public String video;
public ArrayList<Credit> cast;
public ArrayList<Credit> crew;
// Getters
public String getYear() {
String year = "";
if (releaseDate != null && !releaseDate.equals("null")) {
year = releaseDate.substring(0, 4);
}
return year;
}
// Constructors
public MovieDetail(String id, String imdbId, String title, String tagline, String releaseDate, String runtime,
String overview, String voteAverage, String voteCount, String backdropImage, String posterImage,
String video, ArrayList<Credit> cast, ArrayList<Credit> crew) {
this.id = id;
this.imdbId = imdbId;
this.title = title;
this.tagline = tagline;
this.releaseDate = releaseDate;
this.runtime = runtime;
this.overview = overview;
this.voteAverage = voteAverage;
this.voteCount = voteCount;
this.backdropImage = backdropImage;
this.posterImage = posterImage;
this.video = video;
this.cast = cast;
this.crew = crew;
}
public MovieDetail(Parcel in) {
this.id = in.readString();
this.imdbId = in.readString();
this.title = in.readString();
this.tagline = in.readString();
this.releaseDate = in.readString();
this.runtime = in.readString();
this.overview = in.readString();
this.voteAverage = in.readString();
this.voteCount = in.readString();
this.backdropImage = in.readString();
this.posterImage = in.readString();
this.video = in.readString();
in.readList(cast, Credit.class.getClassLoader());
in.readList(crew, Credit.class.getClassLoader());
}
// Parcelable Creator
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public MovieDetail createFromParcel(Parcel in) {
return new MovieDetail(in);
}
public MovieDetail[] newArray(int size) {
return new MovieDetail[size];
}
};
// Helper methods
public String getSubtitle() {
try {
boolean isReleaseDateNull = (releaseDate == null || releaseDate.equals("null"));
boolean isRuntimeNull = (runtime == null || runtime.equals("null") || runtime.equals("0"));
if (isReleaseDateNull && isRuntimeNull) {
return "";
} else if (isReleaseDateNull) {
return runtime + " mins";
} else if (isRuntimeNull) {
return getFormattedDate();
} else {
return getFormattedDate() + "\n" + runtime + " mins";
}
} catch (Exception ex) {
return "";
}
}
private String getFormattedDate() {
SimpleDateFormat oldFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = oldFormat.parse(releaseDate);
} catch (Exception ignored) { }
SimpleDateFormat newFormat = new SimpleDateFormat("dd MMMM yyyy");
return newFormat.format(date);
}
// Parcelling methods
@Override
public void writeToParcel(Parcel out, int i) {
out.writeString(id);
out.writeString(imdbId);
out.writeString(title);
out.writeString(tagline);
out.writeString(releaseDate);
out.writeString(runtime);
out.writeString(overview);
out.writeString(voteAverage);
out.writeString(voteCount);
out.writeString(backdropImage);
out.writeString(posterImage);
out.writeString(video);
out.writeList(cast);
out.writeList(crew);
}
@Override
public int describeContents() {
return 0;
}
} | java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/model/Person.java | app/src/main/java/com/ronakmanglani/watchlist/model/Person.java | package com.ronakmanglani.watchlist.model;
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable {
// Attributes
public String id;
public String name;
public String placeOfBirth;
public String birthDay;
public String deathDay;
public String biography;
public String homepage;
public String imagePath;
// Constructor
public Person(String id, String name, String placeOfBirth, String birthDay, String deathDay,
String biography, String homepage, String imagePath) {
this.id = id;
this.name = name;
this.placeOfBirth = placeOfBirth;
this.birthDay = birthDay;
this.deathDay = deathDay;
this.biography = biography;
this.homepage = homepage;
this.imagePath = imagePath;
}
public Person(Parcel in) {
this.id = in.readString();
this.name = in.readString();
this.placeOfBirth = in.readString();
this.birthDay = in.readString();
this.deathDay = in.readString();
this.biography = in.readString();
this.homepage = in.readString();
this.imagePath = in.readString();
}
// Parcelable Creator
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Person createFromParcel(Parcel in) {
return new Person(in);
}
public Person[] newArray(int size) {
return new Person[size];
}
};
// Parcelling methods
@Override
public void writeToParcel(Parcel out, int i) {
out.writeString(id);
out.writeString(name);
out.writeString(placeOfBirth);
out.writeString(birthDay);
out.writeString(deathDay);
out.writeString(biography);
out.writeString(homepage);
out.writeString(imagePath);
}
@Override
public int describeContents() {
return 0;
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/model/Video.java | app/src/main/java/com/ronakmanglani/watchlist/model/Video.java | package com.ronakmanglani.watchlist.model;
import android.os.Parcel;
import android.os.Parcelable;
public class Video implements Parcelable {
// Attributes
public String title;
public String size;
public String youtubeID;
public String imageURL;
public String videoURL;
// Constructors
public Video(String title, String size, String youtubeID, String imageURL, String videoURL) {
this.title = title;
this.size = size;
this.youtubeID = youtubeID;
this.imageURL = imageURL;
this.videoURL = videoURL;
}
public Video(Parcel in) {
this.title = in.readString();
this.size = in.readString();
this.youtubeID = in.readString();
this.imageURL = in.readString();
this.videoURL = in.readString();
}
// Parcelable Creator
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Video createFromParcel(Parcel in) {
return new Video(in);
}
public Video[] newArray(int size) {
return new Video[size];
}
};
// Parcelling methods
@Override
public void writeToParcel(Parcel out, int i) {
out.writeString(title);
out.writeString(size);
out.writeString(youtubeID);
out.writeString(imageURL);
out.writeString(videoURL);
}
@Override
public int describeContents() {
return 0;
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/model/Review.java | app/src/main/java/com/ronakmanglani/watchlist/model/Review.java | package com.ronakmanglani.watchlist.model;
import android.os.Parcel;
import android.os.Parcelable;
public class Review implements Parcelable {
// Attributes
public String id;
public String userName;
public String comment;
public String createdAt;
public boolean hasSpoiler;
// Constructors
public Review(String id, String userName, String comment, String createdAt, boolean hasSpoiler) {
this.id = id;
this.userName = userName;
this.comment = comment;
this.createdAt = createdAt;
this.hasSpoiler = hasSpoiler;
}
public Review(Parcel in) {
this.id = in.readString();
this.userName = in.readString();
this.comment = in.readString();
this.createdAt = in.readString();
this.hasSpoiler = (in.readInt() == 1);
}
// Parcelable Creator
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Review createFromParcel(Parcel in) {
return new Review(in);
}
public Review[] newArray(int size) {
return new Review[size];
}
};
// Parcelling methods
@Override
public void writeToParcel(Parcel out, int i) {
out.writeString(id);
out.writeString(userName);
out.writeString(comment);
out.writeString(createdAt);
if (hasSpoiler) {
out.writeInt(1);
} else {
out.writeInt(0);
}
}
@Override
public int describeContents() {
return 0;
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/api/VolleySingleton.java | app/src/main/java/com/ronakmanglani/watchlist/api/VolleySingleton.java | package com.ronakmanglani.watchlist.api;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.ronakmanglani.watchlist.WatchlistApp;
public class VolleySingleton {
// Singleton Instance
private static VolleySingleton instance;
public static VolleySingleton getInstance() {
if (instance == null) {
instance = new VolleySingleton();
}
return instance;
}
// Member objects
public RequestQueue requestQueue;
public ImageLoader imageLoader;
// Constructor
private VolleySingleton() {
requestQueue = Volley.newRequestQueue(WatchlistApp.getAppContext());
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/api/ApiHelper.java | app/src/main/java/com/ronakmanglani/watchlist/api/ApiHelper.java | package com.ronakmanglani.watchlist.api;
import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import com.ronakmanglani.watchlist.R;
public class ApiHelper {
// Constructor
private ApiHelper() { }
// Get API keys
public static String getTMDBKey(Context context) {
return context.getString(R.string.tmdb_api_key);
}
public static String getTraktKey(Context context) {
return context.getString(R.string.trakt_api_key);
}
// API Endpoints
public static String getMostPopularMoviesLink(Context context, int page) {
return "http://api.themoviedb.org/3/movie/popular?&page=" + page + "&api_key=" + getTMDBKey(context);
}
public static String getHighestRatedMoviesLink(Context context, int page) {
return "http://api.themoviedb.org/3/movie/top_rated?&page=" + page + "&api_key=" + getTMDBKey(context);
}
public static String getUpcomingMoviesLink(Context context, int page) {
return "http://api.themoviedb.org/3/movie/upcoming?&page=" + page + "&api_key=" + getTMDBKey(context);
}
public static String getNowPlayingMoviesLink(Context context, int page) {
return "http://api.themoviedb.org/3/movie/now_playing?&page=" + page + "&api_key=" + getTMDBKey(context);
}
public static String getSearchMoviesLink(Context context, String query, int page) {
return Uri.parse("http://api.themoviedb.org/3/search/movie")
.buildUpon()
.appendQueryParameter("api_key", getTMDBKey(context))
.appendQueryParameter("query", query)
.appendQueryParameter("page", page + "")
.build().toString();
}
public static String getMovieDetailLink(Context context, String id) {
return "http://api.themoviedb.org/3/movie/" + id + "?api_key=" + getTMDBKey(context) + "&append_to_response=credits,trailers";
}
public static String getMovieReviewsLink(String imdbId, int page) {
return "https://api-v2launch.trakt.tv/movies/" + imdbId + "/comments/newest?page=" + page;
}
public static String getVideosLink(Context context, String id) {
return "http://api.themoviedb.org/3/movie/" + id + "/videos?api_key=" + getTMDBKey(context);
}
public static String getPhotosLink(Context context, String id) {
return "http://api.themoviedb.org/3/movie/" + id + "/images?api_key=" + getTMDBKey(context);
}
// URLs for getting images
public static String getImageURL(String baseURL, int widthPx) {
if (widthPx > 500) {
return "http://image.tmdb.org/t/p/w780/" + baseURL;
} else if (widthPx > 342 && widthPx <= 500) {
return "http://image.tmdb.org/t/p/w500/" + baseURL;
} else if (widthPx > 185 && widthPx <= 342) {
return "http://image.tmdb.org/t/p/w342/" + baseURL;
} else if (widthPx > 154 && widthPx <= 185) {
return "http://image.tmdb.org/t/p/w185/" + baseURL;
} else if (widthPx > 92 && widthPx <= 154) {
return "http://image.tmdb.org/t/p/w154/" + baseURL;
} else if (widthPx > 0 && widthPx <= 92) {
return "http://image.tmdb.org/t/p/w92/" + baseURL;
} else {
return "http://image.tmdb.org/t/p/w185/" + baseURL; // Default Value
}
}
public static String getOriginalImageURL(String baseURL) {
return "http://image.tmdb.org/t/p/original/" + baseURL;
}
public static String getVideoThumbnailURL(String youtubeID) {
return "http://img.youtube.com/vi/" + youtubeID + "/0.jpg";
}
// URLs for Sharing
public static String getMovieShareURL(String id) {
return "https://www.themoviedb.org/movie/" + id;
}
public static String getVideoURL(String youtubeID) {
return "https://www.youtube.com/watch?v=" + youtubeID;
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/data/MovieProvider.java | app/src/main/java/com/ronakmanglani/watchlist/data/MovieProvider.java | package com.ronakmanglani.watchlist.data;
import android.net.Uri;
import net.simonvt.schematic.annotation.ContentProvider;
import net.simonvt.schematic.annotation.ContentUri;
import net.simonvt.schematic.annotation.TableEndpoint;
@ContentProvider(authority = MovieProvider.AUTHORITY, database = MovieDatabase.class)
public class MovieProvider {
public static final String AUTHORITY = "com.ronakmanglani.watchlist.database.MovieProvider";
// Table for movies seen
@TableEndpoint(table = MovieDatabase.WATCHED) public static class Watched {
@ContentUri(
path = "watched",
type = "vnd.android.cursor.dir/list",
defaultSort = MovieColumns.TITLE + " ASC")
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/watched");
}
// Table for movies to see
@TableEndpoint(table = MovieDatabase.TO_SEE) public static class ToSee {
@ContentUri(
path = "to_see",
type = "vnd.android.cursor.dir/list",
defaultSort = MovieColumns.TITLE + " ASC")
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/to_see");
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/data/MovieColumns.java | app/src/main/java/com/ronakmanglani/watchlist/data/MovieColumns.java | package com.ronakmanglani.watchlist.data;
import net.simonvt.schematic.annotation.AutoIncrement;
import net.simonvt.schematic.annotation.DataType;
import net.simonvt.schematic.annotation.NotNull;
import net.simonvt.schematic.annotation.PrimaryKey;
import static net.simonvt.schematic.annotation.DataType.Type.INTEGER;
import static net.simonvt.schematic.annotation.DataType.Type.TEXT;
public interface MovieColumns {
@DataType(INTEGER) @PrimaryKey @AutoIncrement String _ID = "_id";
@DataType(TEXT) @NotNull String TMDB_ID = "tmdb_id";
@DataType(TEXT) @NotNull String TITLE = "title";
@DataType(TEXT) @NotNull String YEAR = "year";
@DataType(TEXT) @NotNull String OVERVIEW = "overview";
@DataType(TEXT) @NotNull String RATING = "rating";
@DataType(TEXT) @NotNull String POSTER = "poster";
@DataType(TEXT) @NotNull String BACKDROP = "backdrop";
} | java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/data/MovieDatabase.java | app/src/main/java/com/ronakmanglani/watchlist/data/MovieDatabase.java | package com.ronakmanglani.watchlist.data;
import net.simonvt.schematic.annotation.Database;
import net.simonvt.schematic.annotation.Table;
@Database(version = MovieDatabase.VERSION)
public class MovieDatabase {
public static final int VERSION = 1;
@Table(MovieColumns.class) public static final String WATCHED = "watched";
@Table(MovieColumns.class) public static final String TO_SEE = "to_see";
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/MovieListFragment.java | app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/MovieListFragment.java | package com.ronakmanglani.watchlist.ui.fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.activity.MovieActivity;
import com.ronakmanglani.watchlist.ui.activity.MovieDetailActivity;
import com.ronakmanglani.watchlist.ui.adapter.MovieAdapter;
import com.ronakmanglani.watchlist.model.Movie;
import com.ronakmanglani.watchlist.api.ApiHelper;
import com.ronakmanglani.watchlist.util.TextUtil;
import com.ronakmanglani.watchlist.api.VolleySingleton;
import com.ronakmanglani.watchlist.ui.view.PaddingDecorationView;
import org.json.JSONArray;
import org.json.JSONObject;
import butterknife.BindView;
import butterknife.BindBool;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class MovieListFragment extends Fragment implements MovieAdapter.OnMovieClickListener {
private Context context;
private Unbinder unbinder;
private MovieAdapter adapter;
private GridLayoutManager layoutManager;
private int pageToDownload;
private static final int TOTAL_PAGES = 999;
private int viewType;
private boolean isLoading;
private boolean isLoadingLocked;
@BindBool(R.bool.is_tablet) boolean isTablet;
@BindView(R.id.error_message) View errorMessage;
@BindView(R.id.progress_circle) View progressCircle;
@BindView(R.id.loading_more) View loadingMore;
@BindView(R.id.swipe_refresh) SwipeRefreshLayout swipeRefreshLayout;
@BindView(R.id.movie_grid) RecyclerView recyclerView;
// Fragment lifecycle
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_movie_list,container,false);
context = getContext();
unbinder = ButterKnife.bind(this, v);
// Initialize variables
pageToDownload = 1;
viewType = getArguments().getInt(WatchlistApp.VIEW_TYPE);
// Setup RecyclerView
adapter = new MovieAdapter(context, this);
layoutManager = new GridLayoutManager(context, getNumberOfColumns());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new PaddingDecorationView(context, R.dimen.recycler_item_padding));
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// Load more if RecyclerView has reached the end and isn't already loading
if (layoutManager.findLastVisibleItemPosition() == adapter.movieList.size() - 1 && !isLoadingLocked && !isLoading) {
if (pageToDownload < TOTAL_PAGES) {
loadingMore.setVisibility(View.VISIBLE);
downloadMoviesList();
}
}
}
});
// Setup swipe refresh
swipeRefreshLayout.setColorSchemeResources(R.color.accent);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// Toggle visibility
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
// Remove cache
VolleySingleton.getInstance().requestQueue.getCache().remove(getUrlToDownload(1));
// Download again
pageToDownload = 1;
adapter = null;
downloadMoviesList();
}
});
// Get the movies list
if (savedInstanceState == null || !savedInstanceState.containsKey(WatchlistApp.MOVIE_LIST)) {
downloadMoviesList();
} else {
adapter.movieList = savedInstanceState.getParcelableArrayList(WatchlistApp.MOVIE_LIST);
pageToDownload = savedInstanceState.getInt(WatchlistApp.PAGE_TO_DOWNLOAD);
isLoadingLocked = savedInstanceState.getBoolean(WatchlistApp.IS_LOCKED);
isLoading = savedInstanceState.getBoolean(WatchlistApp.IS_LOADING);
// Download again if stopped, else show list
if (isLoading) {
if (pageToDownload == 1) {
progressCircle.setVisibility(View.VISIBLE);
loadingMore.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
swipeRefreshLayout.setVisibility(View.GONE);
} else {
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.VISIBLE);
swipeRefreshLayout.setVisibility(View.VISIBLE);
}
downloadMoviesList();
} else {
onDownloadSuccessful();
}
}
return v;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (layoutManager != null && adapter != null) {
outState.putBoolean(WatchlistApp.IS_LOADING, isLoading);
outState.putBoolean(WatchlistApp.IS_LOCKED, isLoadingLocked);
outState.putInt(WatchlistApp.PAGE_TO_DOWNLOAD, pageToDownload);
outState.putParcelableArrayList(WatchlistApp.MOVIE_LIST, adapter.movieList);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
VolleySingleton.getInstance().requestQueue.cancelAll(this.getClass().getName());
unbinder.unbind();
}
// JSON parsing and display
public String getUrlToDownload(int page) {
if (viewType == WatchlistApp.VIEW_TYPE_POPULAR) {
return ApiHelper.getMostPopularMoviesLink(getActivity(), page);
} else if (viewType == WatchlistApp.VIEW_TYPE_RATED) {
return ApiHelper.getHighestRatedMoviesLink(getActivity(), page);
} else if (viewType == WatchlistApp.VIEW_TYPE_UPCOMING) {
return ApiHelper.getUpcomingMoviesLink(getActivity(), page);
} else if (viewType == WatchlistApp.VIEW_TYPE_PLAYING) {
return ApiHelper.getNowPlayingMoviesLink(getActivity(), page);
}
return null;
}
private void downloadMoviesList() {
if (adapter == null) {
adapter = new MovieAdapter(context, this);
recyclerView.setAdapter(adapter);
}
String urlToDownload = getUrlToDownload(pageToDownload);
final JsonObjectRequest request = new JsonObjectRequest (
Request.Method.GET, urlToDownload, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
try {
JSONArray result = jsonObject.getJSONArray("results");
for (int i = 0; i < result.length(); i++) {
JSONObject movie = (JSONObject) result.get(i);
String poster = movie.getString("poster_path");
String overview = movie.getString("overview");
String year = movie.getString("release_date");
if (!TextUtil.isNullOrEmpty(year)) {
year = year.substring(0, 4);
}
String id = movie.getString("id");
String title = movie.getString("title");
String backdrop = movie.getString("backdrop_path");
String rating = movie.getString("vote_average");
Movie thumb = new Movie(id, title, year, overview, rating, poster, backdrop);
adapter.movieList.add(thumb);
}
// Load detail fragment if in tablet mode
if (isTablet && pageToDownload == 1 && adapter.movieList.size() > 0) {
((MovieActivity)getActivity()).loadDetailFragmentWith(adapter.movieList.get(0).id);
}
pageToDownload++;
onDownloadSuccessful();
} catch (Exception ex) {
// JSON parsing error
onDownloadFailed();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
// Network error
onDownloadFailed();
}
});
isLoading = true;
request.setTag(this.getClass().getName());
VolleySingleton.getInstance().requestQueue.add(request);
}
private void onDownloadSuccessful() {
isLoading = false;
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
swipeRefreshLayout.setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
swipeRefreshLayout.setEnabled(true);
adapter.notifyDataSetChanged();
}
private void onDownloadFailed() {
isLoading = false;
if (pageToDownload == 1) {
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
swipeRefreshLayout.setVisibility(View.GONE);
errorMessage.setVisibility(View.VISIBLE);
} else {
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
errorMessage.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
swipeRefreshLayout.setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
swipeRefreshLayout.setEnabled(true);
isLoadingLocked = true;
}
}
// Helper methods
public void refreshLayout() {
Parcelable state = layoutManager.onSaveInstanceState();
layoutManager = new GridLayoutManager(getContext(), getNumberOfColumns());
recyclerView.setLayoutManager(layoutManager);
layoutManager.onRestoreInstanceState(state);
}
public int getNumberOfColumns() {
// Get screen width
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float widthPx = displayMetrics.widthPixels;
if (isTablet) {
widthPx = widthPx / 3;
}
// Calculate desired width
SharedPreferences preferences = context.getSharedPreferences(WatchlistApp.TABLE_USER, Context.MODE_PRIVATE);
if (preferences.getInt(WatchlistApp.VIEW_MODE, WatchlistApp.VIEW_MODE_GRID) == WatchlistApp.VIEW_MODE_GRID) {
float desiredPx = getResources().getDimensionPixelSize(R.dimen.movie_card_width);
int columns = Math.round(widthPx / desiredPx);
return columns > 2 ? columns : 2;
} else {
float desiredPx = getResources().getDimensionPixelSize(R.dimen.movie_list_card_width);
int columns = Math.round(widthPx / desiredPx);
return columns > 1 ? columns : 1;
}
}
// Click events
@OnClick(R.id.try_again)
public void onTryAgainClicked() {
// Hide all views
errorMessage.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
swipeRefreshLayout.setVisibility(View.GONE);
// Show progress circle
progressCircle.setVisibility(View.VISIBLE);
// Try to download the data again
pageToDownload = 1;
adapter = null;
downloadMoviesList();
}
@Override
public void onMovieClicked(int position) {
if (isTablet) {
((MovieActivity)getActivity()).loadDetailFragmentWith(adapter.movieList.get(position).id);
} else {
Intent intent = new Intent(context, MovieDetailActivity.class);
intent.putExtra(WatchlistApp.MOVIE_ID, adapter.movieList.get(position).id);
startActivity(intent);
}
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/CreditFragment.java | app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/CreditFragment.java | package com.ronakmanglani.watchlist.ui.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.adapter.CreditAdapter;
import com.ronakmanglani.watchlist.ui.adapter.CreditAdapter.OnCreditClickListener;
import com.ronakmanglani.watchlist.model.Credit;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class CreditFragment extends Fragment implements OnCreditClickListener {
private Unbinder unbinder;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.toolbar_title) TextView toolbarTitle;
@BindView(R.id.toolbar_subtitle) TextView toolbarSubtitle;
@BindView(R.id.credit_list) RecyclerView creditView;
// Fragment lifecycle
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_credit, container, false);
unbinder = ButterKnife.bind(this, v);
int creditType = getArguments().getInt(WatchlistApp.CREDIT_TYPE);
String movieName = getArguments().getString(WatchlistApp.MOVIE_NAME);
ArrayList<Credit> creditList = getArguments().getParcelableArrayList(WatchlistApp.CREDIT_LIST);
toolbar.setTitle("");
if (creditType == WatchlistApp.CREDIT_TYPE_CAST) {
toolbarTitle.setText(R.string.cast_title);
} else if (creditType == WatchlistApp.CREDIT_TYPE_CREW) {
toolbarTitle.setText(R.string.crew_title);
}
toolbarSubtitle.setText(movieName);
toolbar.setNavigationIcon(ContextCompat.getDrawable(getActivity(), R.drawable.action_home));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().finish();
}
});
CreditAdapter adapter = new CreditAdapter(getContext(), creditList, this);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
creditView.setHasFixedSize(true);
creditView.setLayoutManager(layoutManager);
creditView.setAdapter(adapter);
return v;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
// Click events
@Override
public void onCreditClicked(int position) {
// TODO
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/BackupFragment.java | app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/BackupFragment.java | package com.ronakmanglani.watchlist.ui.fragment;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.widget.Toast;
import com.nononsenseapps.filepicker.FilePickerActivity;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.util.FileUtil;
import java.io.File;
public class BackupFragment extends PreferenceFragment {
private static final String DATABASE_NAME = "movieDatabase.db";
private static final int BACKUP_CODE = 42;
private static final int RESTORE_CODE = 43;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(WatchlistApp.TABLE_USER);
addPreferencesFromResource(R.xml.pref_backup);
Preference backupPreference = findPreference(getString(R.string.pref_key_backup));
backupPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Intent i = new Intent(getActivity(), FilePickerActivity.class);
i.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
i.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, true);
i.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_DIR);
i.putExtra(FilePickerActivity.EXTRA_START_PATH, Environment.getExternalStorageDirectory().getPath());
startActivityForResult(i, BACKUP_CODE);
Toast.makeText(getActivity(), R.string.backup_select, Toast.LENGTH_SHORT).show();
return true;
}
});
Preference restorePreference = findPreference(getString(R.string.pref_key_restore));
restorePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Intent i = new Intent(getActivity(), FilePickerActivity.class);
i.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
i.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, false);
i.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_FILE);
i.putExtra(FilePickerActivity.EXTRA_START_PATH, Environment.getExternalStorageDirectory().getPath());
startActivityForResult(i, RESTORE_CODE);
Toast.makeText(getActivity(), R.string.restore_select, Toast.LENGTH_SHORT).show();
return true;
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BACKUP_CODE && resultCode == Activity.RESULT_OK) {
try {
File srcFile = getActivity().getDatabasePath(DATABASE_NAME);
File dstFile = new File(data.getData().getPath() + File.separator
+ "Watchlist-" + (System.currentTimeMillis()/1000) + ".bak");
FileUtil.copyFile(srcFile, dstFile);
Toast.makeText(getActivity(), R.string.backup_complete, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getActivity(), R.string.backup_failed, Toast.LENGTH_SHORT).show();
}
} else if (requestCode == RESTORE_CODE && resultCode == Activity.RESULT_OK) {
File srcFile = new File(data.getData().getPath());
if (FileUtil.isValidDbFile(srcFile)) {
try {
File dstFile = getActivity().getDatabasePath(DATABASE_NAME);
FileUtil.copyFile(srcFile, dstFile);
Toast.makeText(getActivity(), R.string.restore_complete, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getActivity(), R.string.restore_failed, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getActivity(), R.string.restore_invalid, Toast.LENGTH_SHORT).show();
}
}
}
} | java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/MovieDrawerFragment.java | app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/MovieDrawerFragment.java | package com.ronakmanglani.watchlist.ui.fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.Toolbar.OnMenuItemClickListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.activity.BackupActivity;
import com.ronakmanglani.watchlist.ui.activity.SearchActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import static android.support.design.widget.NavigationView.OnNavigationItemSelectedListener;
public class MovieDrawerFragment extends Fragment implements OnMenuItemClickListener, OnNavigationItemSelectedListener {
private Fragment fragment;
private Unbinder unbinder;
private SharedPreferences preferences;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.drawer_layout) DrawerLayout drawerLayout;
@BindView(R.id.navigation_view) NavigationView navigationView;
// Fragment lifecycle
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_movie_drawer, container, false);
unbinder = ButterKnife.bind(this, v);
preferences = getContext().getSharedPreferences(WatchlistApp.TABLE_USER, Context.MODE_PRIVATE);
// Setup toolbar
toolbar.inflateMenu(R.menu.menu_movie);
toolbar.setOnMenuItemClickListener(this);
onRefreshToolbarMenu();
// Setup navigation drawer
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.app_name, R.string.app_name) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
navigationView.setNavigationItemSelectedListener(this);
actionBarDrawerToggle.syncState();
// Load previously selected drawer item
int lastPosition = preferences.getInt(WatchlistApp.LAST_SELECTED, 0);
if (savedInstanceState == null) {
setSelectedDrawerItem(lastPosition);
} else {
fragment = getActivity().getSupportFragmentManager().findFragmentByTag(WatchlistApp.TAG_GRID_FRAGMENT);
if (savedInstanceState.containsKey(WatchlistApp.TOOLBAR_TITLE)) {
toolbar.setTitle(savedInstanceState.getString(WatchlistApp.TOOLBAR_TITLE));
} else {
toolbar.setTitle(navigationView.getMenu().getItem(lastPosition).getTitle());
}
}
return v;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(WatchlistApp.TOOLBAR_TITLE, toolbar.getTitle().toString());
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
// Toolbar action menu
@Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_search:
startActivity(new Intent(getContext(), SearchActivity.class));
return true;
case R.id.action_grid:
SharedPreferences.Editor editor1 = preferences.edit();
editor1.putInt(WatchlistApp.VIEW_MODE, WatchlistApp.VIEW_MODE_GRID);
editor1.apply();
onRefreshToolbarMenu();
onRefreshFragmentLayout();
return true;
case R.id.action_list:
SharedPreferences.Editor editor2 = preferences.edit();
editor2.putInt(WatchlistApp.VIEW_MODE, WatchlistApp.VIEW_MODE_LIST);
editor2.apply();
onRefreshToolbarMenu();
onRefreshFragmentLayout();
return true;
case R.id.action_compact:
SharedPreferences.Editor editor3 = preferences.edit();
editor3.putInt(WatchlistApp.VIEW_MODE, WatchlistApp.VIEW_MODE_COMPACT);
editor3.apply();
onRefreshToolbarMenu();
onRefreshFragmentLayout();
return true;
case R.id.action_backup:
Intent backupIntent = new Intent(getContext(), BackupActivity.class);
startActivity(backupIntent);
return true;
case R.id.action_rate:
Intent rateIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getContext().getPackageName()));
startActivity(rateIntent);
return true;
case R.id.action_twitter:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/Ronak_LM"));
startActivity(browserIntent);
return true;
case R.id.action_email:
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto","ronak_lm@outlook.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
try {
startActivity(Intent.createChooser(emailIntent, getString(R.string.action_email_using)));
} catch (Exception e) {
Toast.makeText(getContext(), R.string.action_email_error, Toast.LENGTH_SHORT).show();
}
return true;
case R.id.action_about:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_about, null);
view.findViewById(R.id.tmdb_link).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://themoviedb.org"));
startActivity(browserIntent);
}
});
builder.setView(view);
builder.show();
return true;
default: return false;
}
}
private void onRefreshToolbarMenu() {
int viewMode = preferences.getInt(WatchlistApp.VIEW_MODE, WatchlistApp.VIEW_MODE_GRID);
if (viewMode == WatchlistApp.VIEW_MODE_GRID) {
// Change from grid to list
Menu menu = toolbar.getMenu();
menu.findItem(R.id.action_grid).setVisible(false);
menu.findItem(R.id.action_list).setVisible(true);
menu.findItem(R.id.action_compact).setVisible(false);
} else if (viewMode == WatchlistApp.VIEW_MODE_LIST) {
// Change from list to compact
Menu menu = toolbar.getMenu();
menu.findItem(R.id.action_grid).setVisible(false);
menu.findItem(R.id.action_list).setVisible(false);
menu.findItem(R.id.action_compact).setVisible(true);
} else {
// Change from compact to grid
Menu menu = toolbar.getMenu();
menu.findItem(R.id.action_grid).setVisible(true);
menu.findItem(R.id.action_list).setVisible(false);
menu.findItem(R.id.action_compact).setVisible(false);
}
}
private void onRefreshFragmentLayout() {
if (fragment instanceof MovieListFragment) {
((MovieListFragment) fragment).refreshLayout();
} else if (fragment instanceof MovieSavedFragment) {
((MovieSavedFragment) fragment).refreshLayout();
}
}
// Drawer item selection
@Override
public boolean onNavigationItemSelected(MenuItem item) {
drawerLayout.closeDrawers();
int id = item.getItemId();
switch (id) {
case R.id.drawer_popular:
setSelectedDrawerItem(0);
return true;
case R.id.drawer_rated:
setSelectedDrawerItem(1);
return true;
case R.id.drawer_upcoming:
setSelectedDrawerItem(2);
return true;
case R.id.drawer_playing:
setSelectedDrawerItem(3);
return true;
case R.id.drawer_watched:
setSelectedDrawerItem(4);
return true;
case R.id.drawer_to_see:
setSelectedDrawerItem(5);
return true;
default:
return false;
}
}
private void setSelectedDrawerItem(int position) {
MenuItem item = navigationView.getMenu().getItem(position);
item.setChecked(true);
toolbar.setTitle(item.getTitle());
// Create and setup bundle args
Bundle args = new Bundle();
if (position == 0) {
args.putInt(WatchlistApp.VIEW_TYPE, WatchlistApp.VIEW_TYPE_POPULAR);
} else if (position == 1) {
args.putInt(WatchlistApp.VIEW_TYPE, WatchlistApp.VIEW_TYPE_RATED);
} else if (position == 2) {
args.putInt(WatchlistApp.VIEW_TYPE, WatchlistApp.VIEW_TYPE_UPCOMING);
} else if (position == 3) {
args.putInt(WatchlistApp.VIEW_TYPE, WatchlistApp.VIEW_TYPE_PLAYING);
} else if (position == 4) {
args.putInt(WatchlistApp.VIEW_TYPE, WatchlistApp.VIEW_TYPE_WATCHED);
} else if (position == 5) {
args.putInt(WatchlistApp.VIEW_TYPE, WatchlistApp.VIEW_TYPE_TO_SEE);
}
// Initialize fragment type
if (position <= 3) {
fragment = new MovieListFragment();
} else {
fragment = new MovieSavedFragment();
}
fragment.setArguments(args);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, fragment, WatchlistApp.TAG_GRID_FRAGMENT);
transaction.commit();
// Save selected position to preference
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(WatchlistApp.LAST_SELECTED, position);
editor.apply();
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/MovieDetailFragment.java | app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/MovieDetailFragment.java | package com.ronakmanglani.watchlist.ui.fragment;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.Toolbar.OnMenuItemClickListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.activity.CreditActivity;
import com.ronakmanglani.watchlist.ui.activity.PhotoActivity;
import com.ronakmanglani.watchlist.ui.activity.ReviewActivity;
import com.ronakmanglani.watchlist.ui.activity.VideoActivity;
import com.ronakmanglani.watchlist.data.MovieColumns;
import com.ronakmanglani.watchlist.data.MovieProvider;
import com.ronakmanglani.watchlist.model.Credit;
import com.ronakmanglani.watchlist.model.MovieDetail;
import com.ronakmanglani.watchlist.api.ApiHelper;
import com.ronakmanglani.watchlist.util.TextUtil;
import com.ronakmanglani.watchlist.api.VolleySingleton;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.BindBool;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class MovieDetailFragment extends Fragment implements OnMenuItemClickListener {
private Unbinder unbinder;
private String id;
private MovieDetail movie;
private boolean isMovieWatched;
private boolean isMovieToWatch;
private boolean isVideoAvailable = false;
@BindBool(R.bool.is_tablet) boolean isTablet;
// Toolbar
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.toolbar_text_holder) View toolbarTextHolder;
@BindView(R.id.toolbar_title) TextView toolbarTitle;
@BindView(R.id.toolbar_subtitle) TextView toolbarSubtitle;
// Main views
@BindView(R.id.progress_circle) View progressCircle;
@BindView(R.id.error_message) View errorMessage;
@BindView(R.id.movie_detail_holder) NestedScrollView movieHolder;
@BindView(R.id.fab_menu) FloatingActionMenu floatingActionsMenu;
@BindView(R.id.fab_watched) FloatingActionButton watchedButton;
@BindView(R.id.fab_to_see) FloatingActionButton toWatchButton;
// Image views
@BindView(R.id.backdrop_image) NetworkImageView backdropImage;
@BindView(R.id.backdrop_image_default) ImageView backdropImageDefault;
@BindView(R.id.backdrop_play_button) View backdropPlayButton;
@BindView(R.id.poster_image) NetworkImageView posterImage;
@BindView(R.id.poster_image_default) ImageView posterImageDefault;
// Basic info
@BindView(R.id.movie_title) TextView movieTitle;
@BindView(R.id.movie_subtitle) TextView movieSubtitle;
@BindView(R.id.movie_rating_holder) View movieRatingHolder;
@BindView(R.id.movie_rating) TextView movieRating;
@BindView(R.id.movie_vote_count) TextView movieVoteCount;
// Overview
@BindView(R.id.movie_overview_holder) View movieOverviewHolder;
@BindView(R.id.movie_overview_value) TextView movieOverviewValue;
// Crew
@BindView(R.id.movie_crew_holder) View movieCrewHolder;
@BindView(R.id.movie_crew_see_all) View movieCrewSeeAllButton;
@BindViews({R.id.movie_crew_value1, R.id.movie_crew_value2}) List<TextView> movieCrewValues;
// Cast
@BindView(R.id.movie_cast_holder) View movieCastHolder;
@BindView(R.id.movie_cast_see_all) View movieCastSeeAllButton;
@BindViews({R.id.movie_cast_item1, R.id.movie_cast_item2, R.id.movie_cast_item3}) List<View> movieCastItems;
@BindViews({R.id.movie_cast_image1, R.id.movie_cast_image2, R.id.movie_cast_image3}) List<NetworkImageView> movieCastImages;
@BindViews({R.id.movie_cast_name1, R.id.movie_cast_name2, R.id.movie_cast_name3}) List<TextView> movieCastNames;
@BindViews({R.id.movie_cast_role1, R.id.movie_cast_role2, R.id.movie_cast_role3}) List<TextView> movieCastRoles;
// Fragment lifecycle
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_movie_detail, container, false);
unbinder = ButterKnife.bind(this, v);
// Setup toolbar
toolbar.setTitle(R.string.loading);
toolbar.setOnMenuItemClickListener(this);
if (!isTablet) {
toolbar.setNavigationIcon(ContextCompat.getDrawable(getActivity(), R.drawable.action_home));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().finish();
}
});
}
// Download movie details if new instance, else restore from saved instance
if (savedInstanceState == null || !(savedInstanceState.containsKey(WatchlistApp.MOVIE_ID)
&& savedInstanceState.containsKey(WatchlistApp.MOVIE_OBJECT))) {
id = getArguments().getString(WatchlistApp.MOVIE_ID);
if (TextUtil.isNullOrEmpty(id)) {
progressCircle.setVisibility(View.GONE);
toolbarTextHolder.setVisibility(View.GONE);
toolbar.setTitle("");
} else {
downloadMovieDetails(id);
}
} else {
id = savedInstanceState.getString(WatchlistApp.MOVIE_ID);
movie = savedInstanceState.getParcelable(WatchlistApp.MOVIE_OBJECT);
onDownloadSuccessful();
}
// Setup FAB
updateFABs();
movieHolder.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (oldScrollY < scrollY) {
floatingActionsMenu.hideMenuButton(true);
} else {
floatingActionsMenu.showMenuButton(true);
}
}
});
return v;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (movie != null && id != null) {
outState.putString(WatchlistApp.MOVIE_ID, id);
outState.putParcelable(WatchlistApp.MOVIE_OBJECT, movie);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
VolleySingleton.getInstance().requestQueue.cancelAll(this.getClass().getName());
unbinder.unbind();
}
// Toolbar menu click
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.action_share) {
if (movie != null) {
// Share the movie
String shareText = getString(R.string.action_share_text, movie.title, ApiHelper.getMovieShareURL(movie.id));
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, movie.title);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareText);
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.action_share_using)));
}
return true;
} else {
return false;
}
}
// JSON parsing and display
private void downloadMovieDetails(String id) {
String urlToDownload = ApiHelper.getMovieDetailLink(getActivity(), id);
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET, urlToDownload, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
try {
String backdropImage = jsonObject.getString("backdrop_path");
String id = jsonObject.getString("id");
String imdbId = jsonObject.getString("imdb_id");
String overview = jsonObject.getString("overview");
String posterImage = jsonObject.getString("poster_path");
String releaseDate = jsonObject.getString("release_date");
String runtime = jsonObject.getString("runtime");
String tagline = jsonObject.getString("tagline");
String title = jsonObject.getString("title");
String voteAverage = jsonObject.getString("vote_average");
String voteCount = jsonObject.getString("vote_count");
ArrayList<Credit> cast = new ArrayList<>();
JSONArray castArray = jsonObject.getJSONObject("credits").getJSONArray("cast");
for (int i = 0; i < castArray.length(); i++) {
JSONObject object = (JSONObject) castArray.get(i);
String role = object.getString("character");
String person_id = object.getString("id");
String name = object.getString("name");
String profileImage = object.getString("profile_path");
cast.add(new Credit(person_id, name, role, profileImage));
}
ArrayList<Credit> crew = new ArrayList<>();
JSONArray crewArray = jsonObject.getJSONObject("credits").getJSONArray("crew");
for (int i = 0; i < crewArray.length(); i++) {
JSONObject object = (JSONObject) crewArray.get(i);
String person_id = object.getString("id");
String role = object.getString("job");
String name = object.getString("name");
String profileImage = object.getString("profile_path");
crew.add(new Credit(person_id, name, role, profileImage));
}
String video = "";
JSONArray videoArray = jsonObject.getJSONObject("trailers").getJSONArray("youtube");
if (videoArray.length() > 0) {
video = videoArray.getJSONObject(0).getString("source");
}
movie = new MovieDetail(id, imdbId, title, tagline, releaseDate, runtime, overview, voteAverage,
voteCount, backdropImage, posterImage, video, cast, crew);
onDownloadSuccessful();
} catch (Exception ex) {
// Parsing error
onDownloadFailed();
Log.d("Parse Error", ex.getMessage(), ex);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
// Network error
onDownloadFailed();
}
});
request.setTag(this.getClass().getName());
VolleySingleton.getInstance().requestQueue.add(request);
}
private void onDownloadSuccessful() {
// Toggle visibility
progressCircle.setVisibility(View.GONE);
errorMessage.setVisibility(View.GONE);
movieHolder.setVisibility(View.VISIBLE);
floatingActionsMenu.setVisibility(View.VISIBLE);
// Set title and tagline
if (TextUtil.isNullOrEmpty(movie.tagline)) {
toolbar.setTitle(movie.title);
toolbarTextHolder.setVisibility(View.GONE);
} else {
toolbar.setTitle("");
toolbarTextHolder.setVisibility(View.VISIBLE);
toolbarTitle.setText(movie.title);
toolbarSubtitle.setText(movie.tagline);
}
// Add share button to toolbar
toolbar.inflateMenu(R.menu.menu_share);
// Backdrop image
if (!TextUtil.isNullOrEmpty(movie.backdropImage)) {
int headerImageWidth = (int) getResources().getDimension(R.dimen.detail_backdrop_width);
backdropImage.setImageUrl(ApiHelper.getImageURL(movie.backdropImage, headerImageWidth),
VolleySingleton.getInstance().imageLoader);
if (movie.video.length() == 0) {
isVideoAvailable = false;
} else {
backdropPlayButton.setVisibility(View.VISIBLE);
isVideoAvailable = true;
}
} else {
if (movie.video.length() == 0) {
backdropImage.setVisibility(View.GONE);
backdropImageDefault.setVisibility(View.VISIBLE);
isVideoAvailable = false;
} else {
backdropImage.setImageUrl(ApiHelper.getVideoThumbnailURL(movie.video),
VolleySingleton.getInstance().imageLoader);
backdropPlayButton.setVisibility(View.VISIBLE);
isVideoAvailable = true;
}
}
// Basic info
if (!TextUtil.isNullOrEmpty(movie.posterImage)) {
int posterImageWidth = (int) getResources().getDimension(R.dimen.movie_list_poster_width);
posterImage.setImageUrl(ApiHelper.getImageURL(movie.posterImage, posterImageWidth),
VolleySingleton.getInstance().imageLoader);
} else {
posterImageDefault.setVisibility(View.VISIBLE);
posterImage.setVisibility(View.GONE);
}
movieTitle.setText(movie.title);
movieSubtitle.setText(movie.getSubtitle());
if (TextUtil.isNullOrEmpty(movie.voteAverage) || movie.voteAverage.equals("0.0")) {
movieRatingHolder.setVisibility(View.GONE);
} else {
movieRating.setText(movie.voteAverage);
movieVoteCount.setText(getString(R.string.detail_vote_count, movie.voteCount));
}
// Overview
if (TextUtil.isNullOrEmpty(movie.overview)) {
movieOverviewHolder.setVisibility(View.GONE);
} else {
movieOverviewValue.setText(movie.overview);
}
// Crew
if (movie.crew.size() == 0) {
movieCrewHolder.setVisibility(View.GONE);
} else if (movie.crew.size() == 1) {
// Set value
movieCrewValues.get(0).setText(getString(R.string.detail_crew_format, movie.crew.get(0).role, movie.crew.get(0).name));
// Hide views
movieCrewValues.get(1).setVisibility(View.GONE);
movieCrewSeeAllButton.setVisibility(View.GONE);
// Fix padding
int padding = getResources().getDimensionPixelSize(R.dimen.dist_large);
movieCrewHolder.setPadding(padding, padding, padding, padding);
} else if (movie.crew.size() >= 2) {
// Set values
movieCrewValues.get(0).setText(getString(R.string.detail_crew_format, movie.crew.get(0).role, movie.crew.get(0).name));
movieCrewValues.get(1).setText(getString(R.string.detail_crew_format, movie.crew.get(1).role, movie.crew.get(1).name));
// Hide views
if (movie.crew.size() == 2) {
int padding = getResources().getDimensionPixelSize(R.dimen.dist_large);
movieCrewHolder.setPadding(padding, padding, padding, padding);
movieCrewSeeAllButton.setVisibility(View.GONE);
}
}
// Cast
if (movie.cast.size() == 0) {
movieCastHolder.setVisibility(View.GONE);
} else if (movie.cast.size() == 1) {
int castImageWidth = (int) getResources().getDimension(R.dimen.detail_cast_image_width);
// 0
movieCastImages.get(0).setDefaultImageResId(R.drawable.default_cast);
movieCastImages.get(0).setImageUrl(ApiHelper.getImageURL(movie.cast.get(0).imagePath, castImageWidth),
VolleySingleton.getInstance().imageLoader);
movieCastNames.get(0).setText(movie.cast.get(0).name);
movieCastRoles.get(0).setText(movie.cast.get(0).role);
// Hide views
movieCastSeeAllButton.setVisibility(View.GONE);
movieCastItems.get(2).setVisibility(View.GONE);
movieCastItems.get(1).setVisibility(View.GONE);
// Fix padding
int padding = getResources().getDimensionPixelSize(R.dimen.dist_large);
movieCastHolder.setPadding(padding, padding, padding, padding);
} else if (movie.cast.size() == 2) {
int castImageWidth = (int) getResources().getDimension(R.dimen.detail_cast_image_width);
// 1
movieCastImages.get(1).setDefaultImageResId(R.drawable.default_cast);
movieCastImages.get(1).setImageUrl(ApiHelper.getImageURL(movie.cast.get(1).imagePath, castImageWidth),
VolleySingleton.getInstance().imageLoader);
movieCastNames.get(1).setText(movie.cast.get(1).name);
movieCastRoles.get(1).setText(movie.cast.get(1).role);
// 0
movieCastImages.get(0).setDefaultImageResId(R.drawable.default_cast);
movieCastImages.get(0).setImageUrl(ApiHelper.getImageURL(movie.cast.get(0).imagePath, castImageWidth),
VolleySingleton.getInstance().imageLoader);
movieCastNames.get(0).setText(movie.cast.get(0).name);
movieCastRoles.get(0).setText(movie.cast.get(0).role);
// Hide views
movieCastSeeAllButton.setVisibility(View.GONE);
movieCastItems.get(2).setVisibility(View.GONE);
// Fix padding
int padding = getResources().getDimensionPixelSize(R.dimen.dist_large);
movieCastHolder.setPadding(padding, padding, padding, padding);
} else if (movie.cast.size() >= 3) {
int castImageWidth = (int) getResources().getDimension(R.dimen.detail_cast_image_width);
// 2
movieCastImages.get(2).setDefaultImageResId(R.drawable.default_cast);
movieCastImages.get(2).setImageUrl(ApiHelper.getImageURL(movie.cast.get(2).imagePath, castImageWidth),
VolleySingleton.getInstance().imageLoader);
movieCastNames.get(2).setText(movie.cast.get(2).name);
movieCastRoles.get(2).setText(movie.cast.get(2).role);
// 1
movieCastImages.get(1).setDefaultImageResId(R.drawable.default_cast);
movieCastImages.get(1).setImageUrl(ApiHelper.getImageURL(movie.cast.get(1).imagePath, castImageWidth),
VolleySingleton.getInstance().imageLoader);
movieCastNames.get(1).setText(movie.cast.get(1).name);
movieCastRoles.get(1).setText(movie.cast.get(1).role);
// 0
movieCastImages.get(0).setDefaultImageResId(R.drawable.default_cast);
movieCastImages.get(0).setImageUrl(ApiHelper.getImageURL(movie.cast.get(0).imagePath, castImageWidth),
VolleySingleton.getInstance().imageLoader);
movieCastNames.get(0).setText(movie.cast.get(0).name);
movieCastRoles.get(0).setText(movie.cast.get(0).role);
// Hide show all button
if (movie.cast.size() == 3) {
int padding = getResources().getDimensionPixelSize(R.dimen.dist_large);
movieCastHolder.setPadding(padding, padding, padding, padding);
movieCastSeeAllButton.setVisibility(View.GONE);
}
}
}
private void onDownloadFailed() {
errorMessage.setVisibility(View.VISIBLE);
progressCircle.setVisibility(View.GONE);
movieHolder.setVisibility(View.GONE);
toolbarTextHolder.setVisibility(View.GONE);
toolbar.setTitle("");
}
// Click events
@OnClick(R.id.button_photos)
public void onPhotosButtonClicked() {
Intent intent = new Intent(getContext(), PhotoActivity.class);
intent.putExtra(WatchlistApp.MOVIE_ID, movie.id);
intent.putExtra(WatchlistApp.MOVIE_NAME, movie.title);
startActivity(intent);
}
@OnClick(R.id.button_reviews)
public void onReviewsButtonClicked() {
Intent intent = new Intent(getContext(), ReviewActivity.class);
intent.putExtra(WatchlistApp.MOVIE_ID, movie.imdbId);
intent.putExtra(WatchlistApp.MOVIE_NAME, movie.title);
startActivity(intent);
}
@OnClick(R.id.button_videos)
public void onVideosButtonClicked() {
Intent intent = new Intent(getContext(), VideoActivity.class);
intent.putExtra(WatchlistApp.MOVIE_ID, movie.id);
intent.putExtra(WatchlistApp.MOVIE_NAME, movie.title);
startActivity(intent);
}
@OnClick(R.id.try_again)
public void onTryAgainClicked() {
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.VISIBLE);
downloadMovieDetails(id);
}
@OnClick(R.id.backdrop_play_button)
public void onTrailedPlayClicked() {
if (isVideoAvailable) {
try{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + movie.video));
startActivity(intent);
} catch (ActivityNotFoundException ex) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + movie.video));
startActivity(intent);
}
}
}
@OnClick(R.id.movie_crew_see_all)
public void onSeeAllCrewClicked() {
Intent intent = new Intent(getContext(), CreditActivity.class);
intent.putExtra(WatchlistApp.CREDIT_TYPE, WatchlistApp.CREDIT_TYPE_CREW);
intent.putExtra(WatchlistApp.MOVIE_NAME, movie.title);
intent.putExtra(WatchlistApp.CREDIT_LIST, movie.crew);
startActivity(intent);
}
@OnClick(R.id.movie_cast_see_all)
public void onSeeAllCastClicked() {
Intent intent = new Intent(getContext(), CreditActivity.class);
intent.putExtra(WatchlistApp.CREDIT_TYPE, WatchlistApp.CREDIT_TYPE_CAST);
intent.putExtra(WatchlistApp.MOVIE_NAME, movie.title);
intent.putExtra(WatchlistApp.CREDIT_LIST, movie.cast);
startActivity(intent);
}
@OnClick(R.id.movie_cast_item1)
public void onFirstCastItemClicked() {
// TODO
}
@OnClick(R.id.movie_cast_item2)
public void onSecondCastItemClicked() {
// TODO
}
@OnClick(R.id.movie_cast_item3)
public void onThirdCastItemClicked() {
// TODO
}
// FAB related functions
private void updateFABs() {
final String movieId = id;
// Look in WATCHED table
getLoaderManager().initLoader(42, null, new LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getContext(),
MovieProvider.Watched.CONTENT_URI,
new String[]{ },
MovieColumns.TMDB_ID + " = '" + movieId + "'",
null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data.getCount() > 0) {
isMovieWatched = true;
watchedButton.setLabelText(getString(R.string.detail_fab_watched_remove));
toWatchButton.setVisibility(View.GONE);
} else {
isMovieWatched = false;
watchedButton.setLabelText(getString(R.string.detail_fab_watched_add));
toWatchButton.setVisibility(View.VISIBLE);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
});
// Look in TO_SEE table
getLoaderManager().initLoader(43, null, new LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getContext(),
MovieProvider.ToSee.CONTENT_URI,
new String[]{ },
MovieColumns.TMDB_ID + " = '" + movieId + "'",
null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data.getCount() > 0) {
isMovieToWatch = true;
toWatchButton.setLabelText(getString(R.string.detail_fab_to_watch_remove));
} else {
isMovieToWatch = false;
toWatchButton.setLabelText(getString(R.string.detail_fab_to_watch_add));
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
});
}
@OnClick(R.id.fab_watched)
public void onWatchedButtonClicked() {
if (!isMovieWatched) {
// Add movie to WATCHED table
ContentValues values = new ContentValues();
values.put(MovieColumns.TMDB_ID, movie.id);
values.put(MovieColumns.TITLE, movie.title);
values.put(MovieColumns.YEAR, movie.getYear());
values.put(MovieColumns.OVERVIEW, movie.overview);
values.put(MovieColumns.RATING, movie.voteAverage);
values.put(MovieColumns.POSTER, movie.posterImage);
values.put(MovieColumns.BACKDROP, movie.backdropImage);
getContext().getContentResolver().insert(MovieProvider.Watched.CONTENT_URI, values);
Toast.makeText(getContext(), R.string.detail_watched_added, Toast.LENGTH_SHORT).show();
// Remove from "TO_SEE" table
if (isMovieToWatch) {
getContext().getContentResolver().
delete(MovieProvider.ToSee.CONTENT_URI,
MovieColumns.TMDB_ID + " = '" + id + "'",
null);
}
} else {
// Remove from WATCHED table
getContext().getContentResolver().
delete(MovieProvider.Watched.CONTENT_URI,
MovieColumns.TMDB_ID + " = '" + id + "'",
null);
Toast.makeText(getContext(), R.string.detail_watched_removed, Toast.LENGTH_SHORT).show();
}
// Update FABs
updateFABs();
}
@OnClick(R.id.fab_to_see)
public void onToWatchButtonClicked() {
if (!isMovieToWatch) {
// Add movie to "TO SEE" table
ContentValues values = new ContentValues();
values.put(MovieColumns.TMDB_ID, movie.id);
values.put(MovieColumns.TITLE, movie.title);
values.put(MovieColumns.YEAR, movie.getYear());
values.put(MovieColumns.OVERVIEW, movie.overview);
values.put(MovieColumns.RATING, movie.voteAverage);
values.put(MovieColumns.POSTER, movie.posterImage);
values.put(MovieColumns.BACKDROP, movie.backdropImage);
getContext().getContentResolver().insert(MovieProvider.ToSee.CONTENT_URI, values);
Toast.makeText(getContext(), R.string.detail_to_watch_added, Toast.LENGTH_SHORT).show();
} else {
// Remove from "TO SEE" table
getContext().getContentResolver().
delete(MovieProvider.ToSee.CONTENT_URI,
MovieColumns.TMDB_ID + " = '" + id + "'",
null);
Toast.makeText(getContext(), R.string.detail_to_watch_removed, Toast.LENGTH_SHORT).show();
}
// Update FABs
updateFABs();
}
} | java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/SearchFragment.java | app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/SearchFragment.java | package com.ronakmanglani.watchlist.ui.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.activity.MovieDetailActivity;
import com.ronakmanglani.watchlist.ui.activity.SearchActivity;
import com.ronakmanglani.watchlist.ui.adapter.SearchAdapter;
import com.ronakmanglani.watchlist.model.Movie;
import com.ronakmanglani.watchlist.api.ApiHelper;
import com.ronakmanglani.watchlist.util.TextUtil;
import com.ronakmanglani.watchlist.api.VolleySingleton;
import com.ronakmanglani.watchlist.ui.view.PaddingDecorationView;
import org.json.JSONArray;
import org.json.JSONObject;
import butterknife.BindView;
import butterknife.BindBool;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import static com.ronakmanglani.watchlist.ui.adapter.SearchAdapter.*;
public class SearchFragment extends Fragment implements OnMovieClickListener {
private Context context;
private Unbinder unbinder;
private String searchQuery;
private SearchAdapter adapter;
private LinearLayoutManager layoutManager;
private int pageToDownload;
private int totalPages;
private boolean isLoading;
private boolean isLoadingLocked;
@BindBool(R.bool.is_tablet) boolean isTablet;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.search_bar) EditText searchBar;
@BindView(R.id.error_message) View errorMessage;
@BindView(R.id.progress_circle) View progressCircle;
@BindView(R.id.loading_more) View loadingMore;
@BindView(R.id.no_results) View noResults;
@BindView(R.id.search_list) RecyclerView recyclerView;
// Fragment lifecycle
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_search_list, container, false);
context = getContext();
unbinder = ButterKnife.bind(this, v);
// Setup toolbar
toolbar.setNavigationIcon(ContextCompat.getDrawable(getActivity(), R.drawable.action_home));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
searchBar.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
String query = searchBar.getText().toString().trim();
if (query.length() > 0) {
// Set query string
searchQuery = query;
// Toggle visibility
recyclerView.setVisibility(View.GONE);
errorMessage.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
noResults.setVisibility(View.GONE);
progressCircle.setVisibility(View.VISIBLE);
// Set counters
pageToDownload = 1;
totalPages = 1;
// Download list
adapter = null;
searchMoviesList();
return true;
}
}
return false;
}
});
// Setup RecyclerView
layoutManager = new GridLayoutManager(context, getNumberOfColumns());
recyclerView.addItemDecoration(new PaddingDecorationView(context, R.dimen.recycler_item_padding));
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// Load more if RecyclerView has reached the end and isn't already loading
if (layoutManager.findLastVisibleItemPosition() == adapter.movieList.size() - 1 && !isLoadingLocked && !isLoading) {
if (pageToDownload < totalPages) {
loadingMore.setVisibility(View.VISIBLE);
searchMoviesList();
}
}
}
});
// Get the movies list
if (savedInstanceState != null && savedInstanceState.containsKey(WatchlistApp.MOVIE_LIST)) {
adapter = new SearchAdapter(context, this);
adapter.movieList = savedInstanceState.getParcelableArrayList(WatchlistApp.MOVIE_LIST);
recyclerView.setAdapter(adapter);
searchQuery = savedInstanceState.getString(WatchlistApp.SEARCH_QUERY);
pageToDownload = savedInstanceState.getInt(WatchlistApp.PAGE_TO_DOWNLOAD);
totalPages = savedInstanceState.getInt(WatchlistApp.TOTAL_PAGES);
isLoadingLocked = savedInstanceState.getBoolean(WatchlistApp.IS_LOCKED);
isLoading = savedInstanceState.getBoolean(WatchlistApp.IS_LOADING);
// Download again if stopped, else show list
if (isLoading) {
if (pageToDownload == 1) {
progressCircle.setVisibility(View.VISIBLE);
loadingMore.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
} else {
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.VISIBLE);
}
searchMoviesList();
} else {
onDownloadSuccessful();
}
}
return v;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (layoutManager != null && adapter != null) {
outState.putBoolean(WatchlistApp.IS_LOADING, isLoading);
outState.putBoolean(WatchlistApp.IS_LOCKED, isLoadingLocked);
outState.putInt(WatchlistApp.PAGE_TO_DOWNLOAD, pageToDownload);
outState.putInt(WatchlistApp.TOTAL_PAGES, totalPages);
outState.putString(WatchlistApp.SEARCH_QUERY, searchQuery);
outState.putParcelableArrayList(WatchlistApp.MOVIE_LIST, adapter.movieList);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
VolleySingleton.getInstance().requestQueue.cancelAll(getClass().getName());
unbinder.unbind();
}
// Helper methods
public int getNumberOfColumns() {
// Get screen width
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float widthPx = displayMetrics.widthPixels;
if (isTablet) {
widthPx = widthPx / 3;
}
float desiredPx = getResources().getDimensionPixelSize(R.dimen.movie_list_card_width);
int columns = Math.round(widthPx / desiredPx);
return columns > 1 ? columns : 1;
}
// JSON parsing and display
private void searchMoviesList() {
if (adapter == null) {
adapter = new SearchAdapter(context, this);
recyclerView.swapAdapter(adapter, true);
}
String urlToDownload = ApiHelper.getSearchMoviesLink(context, searchQuery, pageToDownload);
final JsonObjectRequest request = new JsonObjectRequest (
Request.Method.GET, urlToDownload, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
try {
JSONArray result = jsonObject.getJSONArray("results");
for (int i = 0; i < result.length(); i++) {
JSONObject movie = (JSONObject) result.get(i);
String poster = movie.getString("poster_path");
String overview = movie.getString("overview");
String year = movie.getString("release_date");
if (!TextUtil.isNullOrEmpty(year)) {
year = year.substring(0, 4);
}
String id = movie.getString("id");
String title = movie.getString("title");
String backdrop = movie.getString("backdrop_path");
String rating = movie.getString("vote_average");
Movie thumb = new Movie(id, title, year, overview, rating, poster, backdrop);
adapter.movieList.add(thumb);
}
// Load detail fragment if in tablet mode
if (isTablet && pageToDownload == 1 && adapter.movieList.size() > 0) {
((SearchActivity)getActivity()).loadDetailFragmentWith(adapter.movieList.get(0).id);
}
// Update counters
pageToDownload = jsonObject.getInt("page") + 1;
totalPages = jsonObject.getInt("total_pages");
// Display search results
onDownloadSuccessful();
} catch (Exception ex) {
// JSON parsing error
onDownloadFailed();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
// Network error
onDownloadFailed();
}
});
isLoading = true;
request.setTag(this.getClass().getName());
VolleySingleton.getInstance().requestQueue.add(request);
}
private void onDownloadSuccessful() {
isLoading = false;
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
if (adapter.movieList.size() == 0) {
noResults.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
} else {
noResults.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
adapter.notifyDataSetChanged();
}
private void onDownloadFailed() {
isLoading = false;
if (pageToDownload == 1) {
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
noResults.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
errorMessage.setVisibility(View.VISIBLE);
} else {
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
errorMessage.setVisibility(View.GONE);
noResults.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
isLoadingLocked = true;
}
}
// Click events
@OnClick(R.id.try_again)
public void onTryAgainClicked() {
// Hide all views
errorMessage.setVisibility(View.GONE);
noResults.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
// Show progress circle
progressCircle.setVisibility(View.VISIBLE);
// Try to download the data again
pageToDownload = 1;
totalPages = 1;
adapter = null;
searchMoviesList();
}
@Override
public void onMovieClicked(int position) {
if (isTablet) {
((SearchActivity)getActivity()).loadDetailFragmentWith(adapter.movieList.get(position).id);
} else {
Intent intent = new Intent(context, MovieDetailActivity.class);
intent.putExtra(WatchlistApp.MOVIE_ID, adapter.movieList.get(position).id);
startActivity(intent);
}
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/MovieSavedFragment.java | app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/MovieSavedFragment.java | package com.ronakmanglani.watchlist.ui.fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.activity.MovieActivity;
import com.ronakmanglani.watchlist.ui.activity.MovieDetailActivity;
import com.ronakmanglani.watchlist.ui.adapter.MovieCursorAdapter;
import com.ronakmanglani.watchlist.ui.adapter.MovieCursorAdapter.OnMovieClickListener;
import com.ronakmanglani.watchlist.data.MovieColumns;
import com.ronakmanglani.watchlist.data.MovieProvider;
import com.ronakmanglani.watchlist.ui.view.PaddingDecorationView;
import butterknife.BindView;
import butterknife.BindBool;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class MovieSavedFragment extends Fragment implements OnMovieClickListener, LoaderCallbacks<Cursor> {
private static final int CURSOR_LOADER_ID = 42;
private Context context;
private Unbinder unbinder;
private MovieCursorAdapter adapter;
private GridLayoutManager layoutManager;
private int viewType;
@BindBool(R.bool.is_tablet) boolean isTablet;
@BindView(R.id.no_results) View noResults;
@BindView(R.id.no_results_message) TextView noResultsMessage;
@BindView(R.id.progress_circle) View progressCircle;
@BindView(R.id.movie_grid) RecyclerView recyclerView;
// Fragment life cycle
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_movie_saved, container, false);
unbinder = ButterKnife.bind(this, v);
setRetainInstance(true);
// Initialize variable
context = getContext();
viewType = getArguments().getInt(WatchlistApp.VIEW_TYPE);
// Setup RecyclerView
adapter = new MovieCursorAdapter(context, this, null);
layoutManager = new GridLayoutManager(context, getNumberOfColumns());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new PaddingDecorationView(context, R.dimen.recycler_item_padding));
recyclerView.setAdapter(adapter);
// Load movies from database
getLoaderManager().initLoader(CURSOR_LOADER_ID, null, this);
return v;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
// Cursor Loader
@Override
public Loader<Cursor> onCreateLoader(int loaderID, Bundle args) {
switch (loaderID) {
case CURSOR_LOADER_ID:
// Returns a new CursorLoader
Uri contentUri;
if (viewType == WatchlistApp.VIEW_TYPE_WATCHED) {
contentUri = MovieProvider.Watched.CONTENT_URI;
} else {
contentUri = MovieProvider.ToSee.CONTENT_URI;
}
return new CursorLoader(context, contentUri,
new String[]{ MovieColumns._ID, MovieColumns.TMDB_ID, MovieColumns.TITLE, MovieColumns.YEAR,
MovieColumns.OVERVIEW, MovieColumns.RATING, MovieColumns.POSTER, MovieColumns.BACKDROP},
null, null, null);
default:
// An invalid id was passed in
return null;
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data.getCount() == 0) {
progressCircle.setVisibility(View.GONE);
noResults.setVisibility(View.VISIBLE);
noResultsMessage.setText(R.string.saved_empty);
} else {
progressCircle.setVisibility(View.GONE);
noResults.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
adapter.swapCursor(data);
}
// Load detail fragment if in tablet mode
if (isTablet) {
if (data.getCount() > 0) {
data.moveToFirst();
loadDetailFragmentWith(data.getString(data.getColumnIndex(MovieColumns.TMDB_ID)));
} else {
loadDetailFragmentWith("null");
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
// Helper methods
public int getNumberOfColumns() {
// Get screen width
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float widthPx = displayMetrics.widthPixels;
if (isTablet) {
widthPx = widthPx / 3;
}
// Calculate desired width
SharedPreferences preferences = context.getSharedPreferences(WatchlistApp.TABLE_USER, Context.MODE_PRIVATE);
if (preferences.getInt(WatchlistApp.VIEW_MODE, WatchlistApp.VIEW_MODE_GRID) == WatchlistApp.VIEW_MODE_GRID) {
float desiredPx = getResources().getDimensionPixelSize(R.dimen.movie_card_width);
int columns = Math.round(widthPx / desiredPx);
return columns > 2 ? columns : 2;
} else {
float desiredPx = getResources().getDimensionPixelSize(R.dimen.movie_list_card_width);
int columns = Math.round(widthPx / desiredPx);
return columns > 1 ? columns : 1;
}
}
public void refreshLayout() {
Parcelable state = layoutManager.onSaveInstanceState();
layoutManager = new GridLayoutManager(getContext(), getNumberOfColumns());
recyclerView.setLayoutManager(layoutManager);
layoutManager.onRestoreInstanceState(state);
}
public void loadDetailFragmentWith(final String id) {
new Handler().post(new Runnable() {
@Override
public void run() {
((MovieActivity)getActivity()).loadDetailFragmentWith(id);
}
});
}
// Click events
@Override
public void onMovieClicked(int position) {
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(position);
if (isTablet) {
loadDetailFragmentWith(cursor.getString(cursor.getColumnIndex(MovieColumns.TMDB_ID)));
} else {
Intent intent = new Intent(context, MovieDetailActivity.class);
intent.putExtra(WatchlistApp.MOVIE_ID, cursor.getString(cursor.getColumnIndex(MovieColumns.TMDB_ID)));
startActivity(intent);
}
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/ReviewFragment.java | app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/ReviewFragment.java | package com.ronakmanglani.watchlist.ui.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.activity.ReviewActivity;
import com.ronakmanglani.watchlist.ui.activity.ReviewDetailActivity;
import com.ronakmanglani.watchlist.ui.adapter.ReviewAdapter;
import com.ronakmanglani.watchlist.model.Review;
import com.ronakmanglani.watchlist.api.ApiHelper;
import com.ronakmanglani.watchlist.util.TextUtil;
import com.ronakmanglani.watchlist.api.VolleySingleton;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.BindBool;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class ReviewFragment extends Fragment implements ReviewAdapter.OnReviewClickListener {
private Unbinder unbinder;
private String movieId;
private String movieName;
private ReviewAdapter adapter;
private LinearLayoutManager layoutManager;
private int pageToDownload = 1;
private int totalPages = 1;
private boolean isLoading = false;
private boolean isLoadingLocked = false;
@BindBool(R.bool.is_tablet) boolean isTablet;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.toolbar_title) TextView toolbarTitle;
@BindView(R.id.toolbar_subtitle) TextView toolbarSubtitle;
@BindView(R.id.review_list) RecyclerView reviewList;
@BindView(R.id.error_message) View errorMessage;
@BindView(R.id.no_results) View noResults;
@BindView(R.id.no_results_message) TextView noResultsMessage;
@BindView(R.id.progress_circle) View progressCircle;
@BindView(R.id.loading_more) View loadingMore;
// Fragment lifecycle
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_review,container,false);
unbinder = ButterKnife.bind(this, v);
// Initialize variables
movieId = getArguments().getString(WatchlistApp.MOVIE_ID);
movieName = getArguments().getString(WatchlistApp.MOVIE_NAME);
// Setup toolbar
toolbar.setTitle("");
toolbarTitle.setText(R.string.reviews_title);
toolbarSubtitle.setText(movieName);
toolbar.setNavigationIcon(ContextCompat.getDrawable(getActivity(), R.drawable.action_home));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().finish();
}
});
// Setup RecyclerView
adapter = new ReviewAdapter(new ArrayList<Review>(), this);
layoutManager = new LinearLayoutManager(getContext());
reviewList.setHasFixedSize(true);
reviewList.setLayoutManager(layoutManager);
reviewList.setAdapter(adapter);
reviewList.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// Load more data if reached the end of the list
if (layoutManager.findLastVisibleItemPosition() == adapter.reviewList.size() - 1 && !isLoadingLocked && !isLoading) {
if (pageToDownload < totalPages) {
loadingMore.setVisibility(View.VISIBLE);
downloadMovieReviews();
}
}
}
});
// Download reviews
if (savedInstanceState == null || !savedInstanceState.containsKey(WatchlistApp.REVIEW_LIST)) {
downloadMovieReviews();
} else {
adapter.reviewList = savedInstanceState.getParcelableArrayList(WatchlistApp.REVIEW_LIST);
totalPages = savedInstanceState.getInt(WatchlistApp.TOTAL_PAGES);
pageToDownload = savedInstanceState.getInt(WatchlistApp.PAGE_TO_DOWNLOAD);
isLoadingLocked = savedInstanceState.getBoolean(WatchlistApp.IS_LOCKED);
isLoading = savedInstanceState.getBoolean(WatchlistApp.IS_LOADING);
// If download stopped, download again, else display list
if (isLoading) {
if (pageToDownload > 1) {
progressCircle.setVisibility(View.GONE);
reviewList.setVisibility(View.VISIBLE);
loadingMore.setVisibility(View.VISIBLE);
}
downloadMovieReviews();
} else {
onDownloadSuccessful();
}
}
return v;
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (layoutManager != null && adapter != null) {
outState.putParcelableArrayList(WatchlistApp.REVIEW_LIST, adapter.reviewList);
outState.putBoolean(WatchlistApp.IS_LOADING, isLoading);
outState.putBoolean(WatchlistApp.IS_LOCKED, isLoadingLocked);
outState.putInt(WatchlistApp.PAGE_TO_DOWNLOAD, pageToDownload);
outState.putInt(WatchlistApp.TOTAL_PAGES, totalPages);
}
super.onSaveInstanceState(outState);
}
@Override
public void onDestroyView() {
super.onDestroyView();
VolleySingleton.getInstance().requestQueue.cancelAll(this.getClass().getName());
unbinder.unbind();
}
// JSON parsing and display
private void downloadMovieReviews() {
if (adapter == null) {
adapter = new ReviewAdapter(new ArrayList<Review>(), this);
reviewList.setAdapter(adapter);
}
JsonArrayRequest request = new JsonArrayRequest(
Request.Method.GET, ApiHelper.getMovieReviewsLink(movieId, pageToDownload), null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray array) {
try {
for (int i = 0; i < array.length(); i++) {
JSONObject review = array.getJSONObject(i);
String id = review.getString("id");
String comment = review.getString("comment");
boolean hasSpoiler = review.getBoolean("spoiler");
// Get date and format it
String inputTime = review.getString("created_at").substring(0, 10);
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = inputFormat.parse(inputTime);
DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
String createdAt = outputFormat.format(date);
// Get user name
JSONObject user = review.getJSONObject("user");
String userName = user.getString("username");
if (!user.getBoolean("private")) {
String name = user.getString("name");
if (!TextUtil.isNullOrEmpty(name)) {
userName = name;
}
}
adapter.reviewList.add(new Review(id, userName, comment, createdAt, hasSpoiler));
}
onDownloadSuccessful();
} catch (Exception ex) {
// Parsing error
onDownloadFailed();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError.networkResponse.statusCode == 404 || volleyError.networkResponse.statusCode == 405) {
// No such movie exists
onDownloadSuccessful();
} else {
// Network error, failed to load
onDownloadFailed();
}
}
}) {
// Add Request Headers
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-type", "application/json");
params.put("trakt-api-key", ApiHelper.getTraktKey(getContext()));
params.put("trakt-api-version", "2");
return params;
}
// Get Response Headers
@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
pageToDownload = Integer.parseInt(response.headers.get("X-Pagination-Page")) + 1;
totalPages = Integer.parseInt(response.headers.get("X-Pagination-Page-Count"));
return super.parseNetworkResponse(response);
}
};
isLoading = true;
request.setTag(getClass().getName());
VolleySingleton.getInstance().requestQueue.add(request);
}
private void onDownloadSuccessful() {
isLoading = false;
if (adapter.reviewList.size() == 0) {
noResultsMessage.setText(R.string.reviews_no_results);
noResults.setVisibility(View.VISIBLE);
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
reviewList.setVisibility(View.GONE);
if (isTablet) {
((ReviewActivity) getActivity()).loadDetailFragmentWith("null", null);
}
} else {
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
reviewList.setVisibility(View.VISIBLE);
adapter.notifyDataSetChanged();
if (isTablet) {
((ReviewActivity) getActivity()).loadDetailFragmentWith(movieName, adapter.reviewList.get(0));
}
}
}
private void onDownloadFailed() {
isLoading = false;
if (pageToDownload == 1) {
errorMessage.setVisibility(View.VISIBLE);
reviewList.setVisibility(View.GONE);
} else {
errorMessage.setVisibility(View.GONE);
reviewList.setVisibility(View.VISIBLE);
isLoadingLocked = true;
}
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
}
// Click events
@OnClick(R.id.try_again)
public void onTryAgainClicked() {
// Toggle visibility
reviewList.setVisibility(View.GONE);
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.VISIBLE);
// Reset counters
pageToDownload = 1;
totalPages = 1;
// Download reviews again
adapter = null;
downloadMovieReviews();
}
@Override
public void onReviewClicked(int position) {
Review review = adapter.reviewList.get(position);
if (isTablet) {
((ReviewActivity) getActivity()).loadDetailFragmentWith(movieName, review);
} else {
Intent intent = new Intent(getContext(), ReviewDetailActivity.class);
intent.putExtra(WatchlistApp.MOVIE_NAME, movieName);
intent.putExtra(WatchlistApp.REVIEW_OBJECT, review);
startActivity(intent);
}
}
} | java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/ReviewDetailFragment.java | app/src/main/java/com/ronakmanglani/watchlist/ui/fragment/ReviewDetailFragment.java | package com.ronakmanglani.watchlist.ui.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.Toolbar.OnMenuItemClickListener;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.model.Review;
import butterknife.BindBool;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class ReviewDetailFragment extends Fragment implements OnMenuItemClickListener {
private Unbinder unbinder;
private String movieName;
private Review review;
@BindBool(R.bool.is_tablet) boolean isTablet;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.review_body) TextView reviewBody;
@BindView(R.id.review_body_holder) View reviewBodyHolder;
// Fragment lifecycle
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.fragment_review_detail,container,false);
unbinder = ButterKnife.bind(this, v);
// Get arguments
movieName = getArguments().getString(WatchlistApp.MOVIE_NAME);
review = getArguments().getParcelable(WatchlistApp.REVIEW_OBJECT);
if (review == null) {
if (movieName.equals("null")) {
toolbar.setTitle("");
} else {
toolbar.setTitle(R.string.loading);
}
reviewBodyHolder.setVisibility(View.GONE);
} else {
// Setup toolbar
toolbar.setTitle("Review by " + review.userName);
toolbar.inflateMenu(R.menu.menu_share);
toolbar.setOnMenuItemClickListener(this);
if (!isTablet) {
toolbar.setNavigationIcon(ContextCompat.getDrawable(getActivity(), R.drawable.action_home));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().finish();
}
});
}
// Set review body
reviewBody.setText(review.comment);
}
return v;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
// Toolbar options menu
@Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_share) {
// Share the review
String url = "https://trakt.tv/comments/" + review.id;
String shareText = "A review of " + movieName + " by " + review.userName + " - " + url;
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, movieName + " - Review");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareText);
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.action_share_using)));
return true;
} else {
return false;
}
}
} | java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/activity/PhotoActivity.java | app/src/main/java/com/ronakmanglani/watchlist/ui/activity/PhotoActivity.java | package com.ronakmanglani.watchlist.ui.activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.adapter.PhotoAdapter;
import com.ronakmanglani.watchlist.ui.adapter.PhotoAdapter.OnPhotoClickListener;
import com.ronakmanglani.watchlist.api.ApiHelper;
import com.ronakmanglani.watchlist.api.VolleySingleton;
import com.ronakmanglani.watchlist.ui.view.PaddingDecorationView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.BindBool;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class PhotoActivity extends AppCompatActivity implements OnPhotoClickListener {
private String movieId;
private PhotoAdapter adapter;
private boolean isLoading = false;
@BindBool(R.bool.is_tablet) boolean isTablet;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.toolbar_title) TextView toolbarTitle;
@BindView(R.id.toolbar_subtitle) TextView toolbarSubtitle;
@BindView(R.id.photo_list) RecyclerView photoList;
@BindView(R.id.error_message) View errorMessage;
@BindView(R.id.progress_circle) View progressCircle;
@BindView(R.id.no_results) View noResults;
@BindView(R.id.no_results_message) TextView noResultsMessage;
// Activity lifecycle
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
ButterKnife.bind(this);
movieId = getIntent().getStringExtra(WatchlistApp.MOVIE_ID);
String movieName = getIntent().getStringExtra(WatchlistApp.MOVIE_NAME);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
toolbarTitle.setText(R.string.photos_title);
toolbarSubtitle.setText(movieName);
GridLayoutManager layoutManager = new GridLayoutManager(this,getNumberOfColumns());
adapter = new PhotoAdapter(this, new ArrayList<String>(), this);
photoList.setHasFixedSize(true);
photoList.setLayoutManager(layoutManager);
photoList.addItemDecoration(new PaddingDecorationView(this, R.dimen.dist_xxsmall));
photoList.setAdapter(adapter);
if (savedInstanceState == null) {
downloadPhotosList();
}
// Lock orientation for tablets
if (isTablet) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
@Override
protected void onStop() {
super.onStop();
VolleySingleton.getInstance().requestQueue.cancelAll(this.getClass().getName());
}
// Save/restore state
@Override
public void onSaveInstanceState(Bundle outState) {
if (adapter != null) {
outState.putStringArrayList(WatchlistApp.PHOTO_LIST, adapter.photoList);
outState.putBoolean(WatchlistApp.IS_LOADING, isLoading);
}
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
adapter.photoList = savedInstanceState.getStringArrayList(WatchlistApp.PHOTO_LIST);
isLoading = savedInstanceState.getBoolean(WatchlistApp.IS_LOADING);
// If activity was previously downloading and it stopped, download again
if (isLoading) {
downloadPhotosList();
} else {
onDownloadSuccessful();
}
}
// Toolbar actions
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
} else {
return false;
}
}
// Helper method
public int getNumberOfColumns() {
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float widthPx = displayMetrics.widthPixels;
float desiredPx = getResources().getDimensionPixelSize(R.dimen.photo_item_width);
int columns = Math.round(widthPx / desiredPx);
if (columns <= 1) {
return 1;
} else {
return columns;
}
}
// JSON parsing and display
private void downloadPhotosList() {
isLoading = true;
if (adapter == null) {
adapter = new PhotoAdapter(this, new ArrayList<String>(), this);
photoList.setAdapter(adapter);
}
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET, ApiHelper.getPhotosLink(this, movieId), null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject object) {
try {
JSONArray backdrops = object.getJSONArray("backdrops");
for (int i = 0; i < backdrops.length(); i++) {
adapter.photoList.add(backdrops.getJSONObject(i).getString("file_path"));
}
onDownloadSuccessful();
} catch (Exception ex) {
onDownloadFailed();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
onDownloadFailed();
}
});
request.setTag(getClass().getName());
VolleySingleton.getInstance().requestQueue.add(request);
}
private void onDownloadSuccessful() {
isLoading = false;
if (adapter.photoList.size() == 0) {
noResultsMessage.setText(R.string.photos_no_results);
noResults.setVisibility(View.VISIBLE);
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.GONE);
photoList.setVisibility(View.GONE);
} else {
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.GONE);
photoList.setVisibility(View.VISIBLE);
adapter.notifyDataSetChanged();
}
}
private void onDownloadFailed() {
isLoading = false;
errorMessage.setVisibility(View.VISIBLE);
progressCircle.setVisibility(View.GONE);
photoList.setVisibility(View.GONE);
}
// Click events
@OnClick(R.id.try_again)
public void onTryAgainClicked() {
photoList.setVisibility(View.GONE);
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.VISIBLE);
adapter = null;
downloadPhotosList();
}
@Override
public void onPhotoClicked(int position) {
String url = ApiHelper.getOriginalImageURL(adapter.photoList.get(position));
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/activity/ReviewActivity.java | app/src/main/java/com/ronakmanglani/watchlist/ui/activity/ReviewActivity.java | package com.ronakmanglani.watchlist.ui.activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.fragment.ReviewDetailFragment;
import com.ronakmanglani.watchlist.ui.fragment.ReviewFragment;
import com.ronakmanglani.watchlist.model.Review;
import butterknife.BindBool;
import butterknife.ButterKnife;
public class ReviewActivity extends AppCompatActivity {
@BindBool(R.bool.is_tablet) boolean isTablet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review);
ButterKnife.bind(this);
if (savedInstanceState == null) {
ReviewFragment fragment = new ReviewFragment();
Bundle args = new Bundle();
args.putString(WatchlistApp.MOVIE_ID, getIntent().getStringExtra(WatchlistApp.MOVIE_ID));
args.putString(WatchlistApp.MOVIE_NAME, getIntent().getStringExtra(WatchlistApp.MOVIE_NAME));
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.review_container, fragment).commit();
if (isTablet) {
loadDetailFragmentWith("", null);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
}
public void loadDetailFragmentWith(String movieName, Review review) {
ReviewDetailFragment fragment = new ReviewDetailFragment();
Bundle args = new Bundle();
args.putString(WatchlistApp.MOVIE_NAME, movieName);
args.putParcelable(WatchlistApp.REVIEW_OBJECT, review);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.review_detail_container, fragment).commit();
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/activity/BackupActivity.java | app/src/main/java/com/ronakmanglani/watchlist/ui/activity/BackupActivity.java | package com.ronakmanglani.watchlist.ui.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.ui.fragment.BackupFragment;
public class BackupActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_backup);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getFragmentManager().beginTransaction().replace(R.id.settings_layout, new BackupFragment()).commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
} else {
return false;
}
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/activity/MovieActivity.java | app/src/main/java/com/ronakmanglani/watchlist/ui/activity/MovieActivity.java | package com.ronakmanglani.watchlist.ui.activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.fragment.MovieDetailFragment;
import butterknife.BindBool;
import butterknife.ButterKnife;
public class MovieActivity extends AppCompatActivity {
@BindBool(R.bool.is_tablet) boolean isTablet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie);
ButterKnife.bind(this);
if (isTablet && savedInstanceState == null) {
loadDetailFragmentWith("null");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
public void loadDetailFragmentWith(String movieId) {
MovieDetailFragment fragment = new MovieDetailFragment();
Bundle args = new Bundle();
args.putString(WatchlistApp.MOVIE_ID, movieId);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.detail_fragment, fragment).commit();
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/activity/CreditActivity.java | app/src/main/java/com/ronakmanglani/watchlist/ui/activity/CreditActivity.java | package com.ronakmanglani.watchlist.ui.activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.fragment.CreditFragment;
import butterknife.BindBool;
import butterknife.ButterKnife;
public class CreditActivity extends AppCompatActivity {
@BindBool(R.bool.is_tablet) boolean isTablet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_credit);
ButterKnife.bind(this);
if (savedInstanceState == null) {
CreditFragment fragment = new CreditFragment();
Bundle args = new Bundle();
args.putInt(WatchlistApp.CREDIT_TYPE, getIntent().getIntExtra(WatchlistApp.CREDIT_TYPE, 0));
args.putString(WatchlistApp.MOVIE_NAME, getIntent().getStringExtra(WatchlistApp.MOVIE_NAME));
args.putParcelableArrayList(WatchlistApp.CREDIT_LIST, getIntent().getParcelableArrayListExtra(WatchlistApp.CREDIT_LIST));
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.credit_container, fragment).commit();
if (isTablet) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/activity/SearchActivity.java | app/src/main/java/com/ronakmanglani/watchlist/ui/activity/SearchActivity.java | package com.ronakmanglani.watchlist.ui.activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.fragment.MovieDetailFragment;
import butterknife.BindBool;
import butterknife.ButterKnife;
public class SearchActivity extends AppCompatActivity {
@BindBool(R.bool.is_tablet) boolean isTablet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
ButterKnife.bind(this);
if (isTablet && savedInstanceState == null) {
loadDetailFragmentWith("null");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
public void loadDetailFragmentWith(String movieId) {
MovieDetailFragment fragment = new MovieDetailFragment();
Bundle args = new Bundle();
args.putString(WatchlistApp.MOVIE_ID, movieId);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.detail_fragment, fragment).commit();
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/activity/MovieDetailActivity.java | app/src/main/java/com/ronakmanglani/watchlist/ui/activity/MovieDetailActivity.java | package com.ronakmanglani.watchlist.ui.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.fragment.MovieDetailFragment;
public class MovieDetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
if (savedInstanceState == null) {
String movieId;
Intent intent = getIntent();
Uri data = intent.getData();
if (data == null) {
// Not loading from deep link
movieId = getIntent().getStringExtra(WatchlistApp.MOVIE_ID);
loadMovieDetailsOf(movieId);
} else {
// Loading from deep link
String[] parts = data.toString().split("/");
movieId = parts[parts.length - 1];
switch (movieId) {
// Load Movie Lists
case "movie":
loadMoviesOfType(0);
break;
case "top-rated":
loadMoviesOfType(1);
break;
case "upcoming":
loadMoviesOfType(2);
break;
case "now-playing":
loadMoviesOfType(3);
break;
// Load details of a particular movie
default:
int dashPosition = movieId.indexOf("-");
if (dashPosition != -1) {
movieId = movieId.substring(0, dashPosition);
}
loadMovieDetailsOf(movieId);
break;
}
}
}
}
private void loadMovieDetailsOf(String movieId) {
MovieDetailFragment fragment = new MovieDetailFragment();
Bundle args = new Bundle();
args.putString(WatchlistApp.MOVIE_ID, movieId);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.movie_detail_container, fragment).commit();
}
@SuppressLint("CommitPrefEdits")
private void loadMoviesOfType(int viewType) {
SharedPreferences.Editor editor = getSharedPreferences(WatchlistApp.TABLE_USER, MODE_PRIVATE).edit();
editor.putInt(WatchlistApp.LAST_SELECTED, viewType);
editor.commit();
startActivity(new Intent(this, MovieActivity.class));
finish();
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/activity/VideoActivity.java | app/src/main/java/com/ronakmanglani/watchlist/ui/activity/VideoActivity.java | package com.ronakmanglani.watchlist.ui.activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.adapter.VideoAdapter;
import com.ronakmanglani.watchlist.ui.adapter.VideoAdapter.OnVideoClickListener;
import com.ronakmanglani.watchlist.model.Video;
import com.ronakmanglani.watchlist.api.ApiHelper;
import com.ronakmanglani.watchlist.api.VolleySingleton;
import com.ronakmanglani.watchlist.ui.view.PaddingDecorationView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.BindBool;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class VideoActivity extends AppCompatActivity implements OnVideoClickListener {
private String movieId;
private VideoAdapter adapter;
private boolean isLoading = false;
@BindBool(R.bool.is_tablet) boolean isTablet;
@BindView(R.id.toolbar) Toolbar toolbar;
@BindView(R.id.toolbar_title) TextView toolbarTitle;
@BindView(R.id.toolbar_subtitle) TextView toolbarSubtitle;
@BindView(R.id.video_list) RecyclerView videoList;
@BindView(R.id.error_message) View errorMessage;
@BindView(R.id.progress_circle) View progressCircle;
@BindView(R.id.no_results) View noResults;
@BindView(R.id.no_results_message) TextView noResultsMessage;
// Activity lifecycle
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
ButterKnife.bind(this);
movieId = getIntent().getStringExtra(WatchlistApp.MOVIE_ID);
String movieName = getIntent().getStringExtra(WatchlistApp.MOVIE_NAME);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
toolbarTitle.setText(R.string.videos_title);
toolbarSubtitle.setText(movieName);
final int numOfColumns = getNumberOfColumns();
GridLayoutManager layoutManager = new GridLayoutManager(this, numOfColumns);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (position == adapter.videoList.size()) {
return numOfColumns;
} else {
return 1;
}
}
});
adapter = new VideoAdapter(this, new ArrayList<Video>(), this);
videoList.setHasFixedSize(true);
videoList.setLayoutManager(layoutManager);
videoList.addItemDecoration(new PaddingDecorationView(this, R.dimen.dist_small));
videoList.setAdapter(adapter);
if (savedInstanceState == null) {
downloadVideosList();
}
// Lock orientation for tablets
if (isTablet) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
@Override
protected void onStop() {
super.onStop();
VolleySingleton.getInstance().requestQueue.cancelAll(this.getClass().getName());
}
// Save/restore state
@Override
public void onSaveInstanceState(Bundle outState) {
if (adapter != null) {
outState.putParcelableArrayList(WatchlistApp.VIDEO_LIST, adapter.videoList);
outState.putBoolean(WatchlistApp.IS_LOADING, isLoading);
}
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
adapter.videoList = savedInstanceState.getParcelableArrayList(WatchlistApp.VIDEO_LIST);
isLoading = savedInstanceState.getBoolean(WatchlistApp.IS_LOADING);
// If activity was previously downloading and it stopped, download again
if (isLoading) {
downloadVideosList();
} else {
onDownloadSuccessful();
}
}
// Helper method
public int getNumberOfColumns() {
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float widthPx = displayMetrics.widthPixels;
float desiredPx = getResources().getDimensionPixelSize(R.dimen.video_item_width);
int columns = Math.round(widthPx / desiredPx);
if (columns <= 1) {
return 1;
} else {
return columns;
}
}
// Toolbar actions
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
} else {
return false;
}
}
// JSON parsing and display
private void downloadVideosList() {
isLoading = true;
if (adapter == null) {
adapter = new VideoAdapter(this, new ArrayList<Video>(), this);
videoList.setAdapter(adapter);
}
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET, ApiHelper.getVideosLink(this, movieId), null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject object) {
try {
JSONArray results = object.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject vid = results.getJSONObject(i);
if (vid.getString("site").equals("YouTube")) {
String title = vid.getString("name");
String key = vid.getString("key");
String subtitle = vid.getString("size") + "p";
Video video = new Video(title, subtitle, key, ApiHelper.getVideoThumbnailURL(key), ApiHelper.getVideoURL(key));
adapter.videoList.add(video);
}
}
onDownloadSuccessful();
} catch (Exception ex) {
onDownloadFailed();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
onDownloadFailed();
}
});
request.setTag(getClass().getName());
VolleySingleton.getInstance().requestQueue.add(request);
}
private void onDownloadSuccessful() {
isLoading = false;
if (adapter.videoList.size() == 0) {
noResultsMessage.setText(R.string.videos_no_results);
noResults.setVisibility(View.VISIBLE);
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.GONE);
videoList.setVisibility(View.GONE);
} else {
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.GONE);
videoList.setVisibility(View.VISIBLE);
adapter.notifyDataSetChanged();
}
}
private void onDownloadFailed() {
isLoading = false;
errorMessage.setVisibility(View.VISIBLE);
progressCircle.setVisibility(View.GONE);
videoList.setVisibility(View.GONE);
}
// Click events
@OnClick(R.id.try_again)
public void onTryAgainClicked() {
videoList.setVisibility(View.GONE);
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.VISIBLE);
adapter = null;
downloadVideosList();
}
@Override
public void onVideoClicked(int position) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + adapter.videoList.get(position).youtubeID));
startActivity(intent);
} catch (ActivityNotFoundException ex) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + adapter.videoList.get(position).youtubeID));
startActivity(intent);
}
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/activity/ReviewDetailActivity.java | app/src/main/java/com/ronakmanglani/watchlist/ui/activity/ReviewDetailActivity.java | package com.ronakmanglani.watchlist.ui.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.fragment.ReviewDetailFragment;
public class ReviewDetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review_detail);
if (savedInstanceState == null) {
ReviewDetailFragment fragment = new ReviewDetailFragment();
Bundle args = new Bundle();
args.putString(WatchlistApp.MOVIE_NAME, getIntent().getStringExtra(WatchlistApp.MOVIE_NAME));
args.putParcelable(WatchlistApp.REVIEW_OBJECT, getIntent().getParcelableExtra(WatchlistApp.REVIEW_OBJECT));
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.review_detail_container, fragment).commit();
}
}
}
| java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/view/AutoResizeTextView.java | app/src/main/java/com/ronakmanglani/watchlist/ui/view/AutoResizeTextView.java | /*
Source: http://adilatwork.blogspot.in/2014/08/android-textview-which-resizes-its-text.html
*/
package com.ronakmanglani.watchlist.ui.view;
import android.content.Context;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
public class AutoResizeTextView extends RobotoLightTextView {
/** Our ellipsis string. */
private static final String mEllipsis = "\u2026";
/**
* Upper bounds for text size.
* This acts as a starting point for resizing.
*/
private float mMaxTextSizePixels;
/** Lower bounds for text size. */
private float mMinTextSizePixels;
/** TextView line spacing multiplier. */
private float mLineSpacingMultiplier = 1.0f;
/** TextView additional line spacing. */
private float mLineSpacingExtra = 0.0f;
/**
* Default constructor override.
*
* @param context
*/
public AutoResizeTextView(Context context) {
this(context, null);
initialise();
setMinTextSize(14);
}
/**
* Default constructor when inflating from XML file.
*
* @param context
* @param attrs
*/
public AutoResizeTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
initialise();
setMinTextSize(14);
}
/**
* Default constructor override.
*
* @param context
* @param attrs
* @param defStyle
*/
public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialise();
setMinTextSize(14);
}
@Override
protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
resizeText();
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
requestLayout();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w != oldw || h != oldh) {
requestLayout();
}
}
@Override
public void setTextSize(float size) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
@Override
public void setTextSize(int unit, float size) {
super.setTextSize(unit, size);
mMaxTextSizePixels = getTextSize();
requestLayout();
}
@Override
public void setLineSpacing(float add, float mult) {
super.setLineSpacing(add, mult);
mLineSpacingMultiplier = mult;
mLineSpacingExtra = add;
requestLayout();
}
@Override
public void setEllipsize(TextUtils.TruncateAt where) {
super.setEllipsize(where);
requestLayout();
}
/**
* Sets the lower text size limit and invalidates the view.
*
* @param minTextSizeScaledPixels the minimum size to use for text in this view,
* in scaled pixels.
*/
public void setMinTextSize(float minTextSizeScaledPixels) {
mMinTextSizePixels = convertSpToPx(minTextSizeScaledPixels);
requestLayout();
}
/**
* @return lower text size limit, in pixels.
*/
public float getMinTextSizePixels() {
return mMinTextSizePixels;
}
private void initialise() {
mMaxTextSizePixels = getTextSize();
}
/**
* Resizes this view's text size with respect to its width and height
* (minus padding).
*/
private void resizeText() {
final int availableHeightPixels = getHeight() - getCompoundPaddingBottom() - getCompoundPaddingTop();
final int availableWidthPixels = getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
final CharSequence text = getText();
// Safety check
// (Do not resize if the view does not have dimensions or if there is no text)
if (text == null
|| text.length() <= 0
|| availableHeightPixels <= 0
|| availableWidthPixels <= 0
|| mMaxTextSizePixels <= 0) {
return;
}
float targetTextSizePixels = mMaxTextSizePixels;
int targetTextHeightPixels = getTextHeightPixels(text, availableWidthPixels, targetTextSizePixels);
// Until we either fit within our TextView
// or we have reached our minimum text size,
// incrementally try smaller sizes
while (targetTextHeightPixels > availableHeightPixels
&& targetTextSizePixels > mMinTextSizePixels) {
targetTextSizePixels = Math.max(
targetTextSizePixels - 2,
mMinTextSizePixels);
targetTextHeightPixels = getTextHeightPixels(
text,
availableWidthPixels,
targetTextSizePixels);
}
// If we have reached our minimum text size and the text still doesn't fit,
// append an ellipsis
// (NOTE: Auto-ellipsize doesn't work hence why we have to do it here)
// depending on the value of getEllipsize())
if (getEllipsize() != null
&& targetTextSizePixels == mMinTextSizePixels
&& targetTextHeightPixels > availableHeightPixels) {
// Make a copy of the original TextPaint object for measuring
TextPaint textPaintCopy = new TextPaint(getPaint());
textPaintCopy.setTextSize(targetTextSizePixels);
// Measure using a StaticLayout instance
StaticLayout staticLayout = new StaticLayout(
text,
textPaintCopy,
availableWidthPixels,
Layout.Alignment.ALIGN_NORMAL,
mLineSpacingMultiplier,
mLineSpacingExtra,
false);
// Check that we have a least one line of rendered text
if (staticLayout.getLineCount() > 0) {
// Since the line at the specific vertical position would be cut off,
// we must trim up to the previous line and add an ellipsis
int lastLine = staticLayout.getLineForVertical(availableHeightPixels) - 1;
if (lastLine >= 0) {
int startOffset = staticLayout.getLineStart(lastLine);
int endOffset = staticLayout.getLineEnd(lastLine);
float lineWidthPixels = staticLayout.getLineWidth(lastLine);
float ellipseWidth = textPaintCopy.measureText(mEllipsis);
// Trim characters off until we have enough room to draw the ellipsis
while (availableWidthPixels < lineWidthPixels + ellipseWidth) {
endOffset--;
lineWidthPixels = textPaintCopy.measureText(
text.subSequence(startOffset, endOffset + 1).toString());
}
setText(text.subSequence(0, endOffset) + mEllipsis);
}
}
}
super.setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSizePixels);
// Some devices try to auto adjust line spacing, so force default line spacing
super.setLineSpacing(mLineSpacingExtra, mLineSpacingMultiplier);
}
/**
* Sets the text size of a clone of the view's {@link TextPaint} object
* and uses a {@link StaticLayout} instance to measure the height of the text.
*
* @param source
* @param availableWidthPixels
* @param textSizePixels
* @return the height of the text when placed in a view
* with the specified width
* and when the text has the specified size.
*/
private int getTextHeightPixels(
CharSequence source,
int availableWidthPixels,
float textSizePixels) {
// Make a copy of the original TextPaint object
// since the object gets modified while measuring
// (see also the docs for TextView.getPaint()
// which states to access it read-only)
TextPaint textPaintCopy = new TextPaint(getPaint());
textPaintCopy.setTextSize(textSizePixels);
// Measure using a StaticLayout instance
StaticLayout staticLayout = new StaticLayout(
source,
textPaintCopy,
availableWidthPixels,
Layout.Alignment.ALIGN_NORMAL,
mLineSpacingMultiplier,
mLineSpacingExtra,
true);
return staticLayout.getHeight();
}
/**
* @param scaledPixels
* @return the number of pixels which scaledPixels corresponds to on the device.
*/
private float convertSpToPx(float scaledPixels) {
float pixels = scaledPixels * getContext().getResources().getDisplayMetrics().scaledDensity;
return pixels;
}
} | java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
ronak-lm/android-watchlist | https://github.com/ronak-lm/android-watchlist/blob/fc6f8c312ebe031e4068b093e84de4ee769cd9db/app/src/main/java/com/ronakmanglani/watchlist/ui/view/RobotoBoldTextView.java | app/src/main/java/com/ronakmanglani/watchlist/ui/view/RobotoBoldTextView.java | package com.ronakmanglani.watchlist.ui.view;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
import com.ronakmanglani.watchlist.util.FontUtil;
public class RobotoBoldTextView extends TextView {
public RobotoBoldTextView(Context context) {
super(context);
applyCustomFont();
}
public RobotoBoldTextView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont();
}
public RobotoBoldTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont();
}
private void applyCustomFont() {
Typeface customFont = FontUtil.getTypeface(FontUtil.ROBOTO_BOLD);
setTypeface(customFont);
}
} | java | Apache-2.0 | fc6f8c312ebe031e4068b093e84de4ee769cd9db | 2026-01-05T02:38:35.947030Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.