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 |
|---|---|---|---|---|---|---|---|---|
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/qr-code/src/main/java/com/fnproject/fn/examples/QRGen.java | examples/qr-code/src/main/java/com/fnproject/fn/examples/QRGen.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.fnproject.fn.examples;
import com.fnproject.fn.api.RuntimeContext;
import com.fnproject.fn.api.httpgateway.HTTPGatewayContext;
import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
import java.io.ByteArrayOutputStream;
public class QRGen {
private final String defaultFormat;
public QRGen(RuntimeContext ctx) {
defaultFormat = ctx.getConfigurationByKey("FORMAT").orElse("png");
}
public byte[] create(HTTPGatewayContext hctx) {
ImageType type = getFormat(hctx.getQueryParameters().get("format").orElse(defaultFormat));
System.err.println("Default format: " + type.toString());
String contents = hctx.getQueryParameters().get("contents").orElseThrow(() -> new RuntimeException("Contents must be provided to the QR code"));
ByteArrayOutputStream stream = QRCode.from(contents).to(type).stream();
System.err.println("Generated QR Code for contents: " + contents);
hctx.setResponseHeader("Content-Type", getMimeType(type));
return stream.toByteArray();
}
private ImageType getFormat(String extension) {
switch (extension.toLowerCase()) {
case "png":
return ImageType.PNG;
case "jpg":
case "jpeg":
return ImageType.JPG;
case "gif":
return ImageType.GIF;
case "bmp":
return ImageType.BMP;
default:
throw new RuntimeException(String.format("Cannot use the specified format %s, must be one of png, jpg, gif, bmp", extension));
}
}
private String getMimeType(ImageType type) {
switch (type) {
case JPG:
return "image/jpeg";
case GIF:
return "image/gif";
case PNG:
return "image/png";
case BMP:
return "image/bmp";
default:
throw new RuntimeException("Invalid ImageType: " + type);
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-streaming/src/test/java/com/fnproject/fn/examples/FunctionTest.java | examples/connectorhub-streaming/src/test/java/com/fnproject/fn/examples/FunctionTest.java | package com.fnproject.fn.examples;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.Date;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fnproject.events.input.ConnectorHubBatch;
import com.fnproject.events.input.sch.StreamingData;
import com.fnproject.events.testing.ConnectorHubTestFeature;
import com.fnproject.fn.testing.FnResult;
import com.fnproject.fn.testing.FnTestingRule;
import org.junit.Rule;
import org.junit.Test;
public class FunctionTest {
@Rule
public FnTestingRule fn = FnTestingRule.createDefault();
private final ConnectorHubTestFeature connectorHubTestFeature = ConnectorHubTestFeature.createDefault(fn);
@Test
public void testInvokeFunctionWithStreamingData() throws Exception {
ConnectorHubBatch<StreamingData<Employee>> event = createMinimalRequest();
connectorHubTestFeature.givenEvent(event).enqueue();
fn.thenRun(Function.class, "handler");
FnResult result = fn.getOnlyResult();
assertEquals(200, result.getStatus().getCode());
}
private static ConnectorHubBatch<StreamingData<Employee>> createMinimalRequest() {
Employee employee = new Employee();
employee.setName("foo");
StreamingData<Employee> source = new StreamingData<>(
"stream-name",
"0",
null,
employee,
"3",
new Date(1764860467553L)
);
ConnectorHubBatch<StreamingData<Employee>> event = mock(ConnectorHubBatch.class);
when(event.getBatch()).thenReturn(Collections.singletonList(source));
return event;
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-streaming/src/main/java/com/fnproject/fn/examples/Function.java | examples/connectorhub-streaming/src/main/java/com/fnproject/fn/examples/Function.java | package com.fnproject.fn.examples;
import com.fnproject.events.ConnectorHubFunction;
import com.fnproject.events.input.ConnectorHubBatch;
import com.fnproject.events.input.sch.StreamingData;
public class Function extends ConnectorHubFunction<StreamingData<Employee>> {
public StreamService streamService;
public Function() {
this.streamService = new StreamService();
}
@Override
public void handler(ConnectorHubBatch<StreamingData<Employee>> batch) {
for (StreamingData<Employee> stream : batch.getBatch()) {
streamService.readStream(stream);
}
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-streaming/src/main/java/com/fnproject/fn/examples/Employee.java | examples/connectorhub-streaming/src/main/java/com/fnproject/fn/examples/Employee.java | package com.fnproject.fn.examples;
import java.util.Objects;
public class Employee {
private String name;
public Employee() {}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Employee employee = (Employee) o;
return Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
return Objects.hashCode(name);
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
'}';
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-streaming/src/main/java/com/fnproject/fn/examples/StreamService.java | examples/connectorhub-streaming/src/main/java/com/fnproject/fn/examples/StreamService.java | package com.fnproject.fn.examples;
import com.fnproject.events.input.sch.StreamingData;
public class StreamService {
public void readStream(StreamingData<Employee> streamingData) {
System.out.println(streamingData);
assert streamingData != null;
assert streamingData.getStream() != null;
assert streamingData.getPartition() != null;
assert streamingData.getValue() != null;
assert streamingData.getOffset() != null;
assert streamingData.getTimestamp() != null;
Employee employee = streamingData.getValue();
System.out.println(employee);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/string-reverse/src/test/java/com/example/fn/testing/StringReverseTest.java | examples/string-reverse/src/test/java/com/example/fn/testing/StringReverseTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.example.fn.testing;
import com.example.fn.StringReverse;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class StringReverseTest {
private StringReverse stringReverse = new StringReverse();
@Test
public void reverseEmptyString() {
assertEquals("", reverse(""));
}
@Test
public void reverseOfSingleCharacter() {
assertEquals("a", reverse("a"));
}
@Test
public void reverseHelloIsOlleh() {
assertEquals("olleh", reverse("hello"));
}
private String reverse(String str) {
return stringReverse.reverse(str);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/string-reverse/src/main/java/com/example/fn/StringReverse.java | examples/string-reverse/src/main/java/com/example/fn/StringReverse.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.example.fn;
public class StringReverse {
public String reverse(String str) {
return new StringBuilder(str).reverse().toString();
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-monitoring/src/test/java/com/fnproject/fn/examples/FunctionTest.java | examples/connectorhub-monitoring/src/test/java/com/fnproject/fn/examples/FunctionTest.java | package com.fnproject.fn.examples;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.fnproject.events.input.ConnectorHubBatch;
import com.fnproject.events.input.sch.Datapoint;
import com.fnproject.events.input.sch.MetricData;
import com.fnproject.events.testing.ConnectorHubTestFeature;
import com.fnproject.fn.testing.FnResult;
import com.fnproject.fn.testing.FnTestingRule;
import org.junit.Rule;
import org.junit.Test;
public class FunctionTest {
@Rule
public FnTestingRule fn = FnTestingRule.createDefault();
private final ConnectorHubTestFeature connectorHubTestFeature = ConnectorHubTestFeature.createDefault(fn);
@Test
public void testInvokeFunctionWithMetricData() throws Exception {
ConnectorHubBatch<MetricData> event = createMinimalRequest();
connectorHubTestFeature.givenEvent(event).enqueue();
fn.thenRun(Function.class, "handler");
FnResult result = fn.getOnlyResult();
assertEquals(200, result.getStatus().getCode());
}
private static ConnectorHubBatch<MetricData> createMinimalRequest() {
Map<String, String> dimensions = new HashMap<>();
dimensions.put("resourceID", "ocid1.bucket.oc1.xyz");
dimensions.put("resourceDisplayName", "userName");
Map<String, String> metadata = new HashMap<>();
metadata.put("displayName", "PutObject Request Count");
metadata.put("unit", "count");
MetricData source = new MetricData(
"oci_objectstorage",
"unknown",
"ocid1.tenancy.oc1..xyz",
"PutRequests",
dimensions,
metadata,
Collections.singletonList(new Datapoint(new Date(1764860467553L), Double.parseDouble("12.3"), null))
);
ConnectorHubBatch<MetricData> event = mock(ConnectorHubBatch.class);
when(event.getBatch()).thenReturn(Collections.singletonList(source));
return event;
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-monitoring/src/main/java/com/fnproject/fn/examples/Function.java | examples/connectorhub-monitoring/src/main/java/com/fnproject/fn/examples/Function.java | package com.fnproject.fn.examples;
import com.fnproject.events.ConnectorHubFunction;
import com.fnproject.events.input.ConnectorHubBatch;
import com.fnproject.events.input.sch.MetricData;
public class Function extends ConnectorHubFunction<MetricData> {
public MetricService metricService;
public Function() {
this.metricService = new MetricService();
}
@Override
public void handler(ConnectorHubBatch<MetricData> batch) {
for (MetricData metric : batch.getBatch()) {
metricService.readMetric(metric);
}
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/connectorhub-monitoring/src/main/java/com/fnproject/fn/examples/MetricService.java | examples/connectorhub-monitoring/src/main/java/com/fnproject/fn/examples/MetricService.java | package com.fnproject.fn.examples;
import com.fnproject.events.input.sch.MetricData;
public class MetricService {
public void readMetric(MetricData metric) {
System.out.println(metric);
assert metric != null;
assert metric.getDatapoints() != null && !metric.getDatapoints().isEmpty();
assert metric.getCompartmentId() != null;
assert metric.getDimensions() != null && !metric.getDimensions().isEmpty();
assert metric.getMetadata() != null && !metric.getMetadata().isEmpty();
assert metric.getName() != null && !metric.getName().isEmpty();
assert metric.getNamespace() != null;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/apigateway-event/src/test/java/com/fnproject/fn/examples/FunctionTest.java | examples/apigateway-event/src/test/java/com/fnproject/fn/examples/FunctionTest.java | package com.fnproject.fn.examples;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Collections;
import com.fnproject.events.input.APIGatewayRequestEvent;
import com.fnproject.events.output.APIGatewayResponseEvent;
import com.fnproject.events.testing.APIGatewayTestFeature;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.runtime.httpgateway.QueryParametersImpl;
import com.fnproject.fn.testing.FnResult;
import com.fnproject.fn.testing.FnTestingRule;
import org.junit.Rule;
import org.junit.Test;
public class FunctionTest {
@Rule
public FnTestingRule fn = FnTestingRule.createDefault();
private final APIGatewayTestFeature apiGatewayFeature = APIGatewayTestFeature.createDefault(fn);
@Test
public void testGetResponseBody() throws IOException {
APIGatewayRequestEvent<RequestEmployee> event = createMinimalRequest();
apiGatewayFeature.givenEvent(event)
.enqueue();
fn.thenRun(Function.class, "handler");
APIGatewayResponseEvent<ResponseEmployee> responseEvent = apiGatewayFeature.getResult(ResponseEmployee.class);
ResponseEmployee responseEventBody = responseEvent.getBody();
assertEquals(Integer.valueOf(123), responseEventBody.getId());
assertEquals("John", responseEventBody.getName());
}
@Test
public void testGetResponseHeaders() throws IOException {
APIGatewayRequestEvent<RequestEmployee> event = createMinimalRequest();
when(event.getHeaders()).thenReturn(Headers.emptyHeaders().addHeader("myHeader", "headerValue"));
apiGatewayFeature.givenEvent(event)
.enqueue();
fn.thenRun(Function.class, "handler");
APIGatewayResponseEvent<ResponseEmployee> responseEvent = apiGatewayFeature.getResult(ResponseEmployee.class);
assertEquals("HeaderValue", responseEvent.getHeaders().getAllValues("X-Custom-Header").get(0));
assertEquals("HeaderValue2", responseEvent.getHeaders().get("X-Custom-Header-2").get());
}
@Test
public void testGetResponseStatus() throws IOException {
APIGatewayRequestEvent<RequestEmployee> event = createMinimalRequest();
apiGatewayFeature.givenEvent(event)
.enqueue();
fn.thenRun(Function.class, "handler");
APIGatewayResponseEvent<ResponseEmployee> responseEvent = apiGatewayFeature.getResult(ResponseEmployee.class);
assertEquals(Integer.valueOf(201), responseEvent.getStatus());
}
@Test
public void testErrorResponse() throws IOException {
APIGatewayRequestEvent<RequestEmployee> event = mock(APIGatewayRequestEvent.class);
apiGatewayFeature.givenEvent(event)
.enqueue();
fn.thenRun(Function.class, "handler");
FnResult result = fn.getOnlyResult();
assertEquals(502, result.getStatus().getCode());
assertEquals("An error occurred in function: requestEmployee must not be null\n" +
"Caused by: java.lang.IllegalArgumentException: requestEmployee must not be null\n\n", fn.getStdErrAsString());
assertEquals(1, fn.getLastExitCode());
}
private static APIGatewayRequestEvent<RequestEmployee> createMinimalRequest() {
RequestEmployee requestEmployee = new RequestEmployee();
requestEmployee.setName("John");
APIGatewayRequestEvent<RequestEmployee> event = mock(APIGatewayRequestEvent.class);
when(event.getBody()).thenReturn(requestEmployee);
when(event.getQueryParameters()).thenReturn(new QueryParametersImpl(Collections.singletonMap("id", Collections.singletonList("123"))));
return event;
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/apigateway-event/src/main/java/com/fnproject/fn/examples/Function.java | examples/apigateway-event/src/main/java/com/fnproject/fn/examples/Function.java | package com.fnproject.fn.examples;
import java.util.Optional;
import com.fnproject.events.APIGatewayFunction;
import com.fnproject.events.input.APIGatewayRequestEvent;
import com.fnproject.events.output.APIGatewayResponseEvent;
import com.fnproject.fn.api.Headers;
import org.apache.http.HttpStatus;
public class Function extends APIGatewayFunction<RequestEmployee, ResponseEmployee> {
private final EmployeeService employeeService;
public Function() {
this.employeeService = new EmployeeService();
}
@Override
public APIGatewayResponseEvent<ResponseEmployee> handler(APIGatewayRequestEvent<RequestEmployee> requestEvent) {
Optional<String> id = requestEvent.getQueryParameters().get("id");
RequestEmployee requestEmployee = requestEvent.getBody();
ResponseEmployee responseEmployee = employeeService.createEmployee(requestEmployee, id);
return new APIGatewayResponseEvent.Builder<ResponseEmployee>()
.statusCode(HttpStatus.SC_CREATED)
.headers(Headers.emptyHeaders()
.addHeader("X-Custom-Header", "HeaderValue")
.addHeader("X-Custom-Header-2", "HeaderValue2"))
.body(responseEmployee)
.build();
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/apigateway-event/src/main/java/com/fnproject/fn/examples/RequestEmployee.java | examples/apigateway-event/src/main/java/com/fnproject/fn/examples/RequestEmployee.java | package com.fnproject.fn.examples;
public class RequestEmployee {
private String name;
public RequestEmployee() {}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/apigateway-event/src/main/java/com/fnproject/fn/examples/ResponseEmployee.java | examples/apigateway-event/src/main/java/com/fnproject/fn/examples/ResponseEmployee.java | package com.fnproject.fn.examples;
import java.util.Objects;
public class ResponseEmployee {
private Integer id;
private String name;
public ResponseEmployee() {}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ResponseEmployee employee = (ResponseEmployee) o;
return id.equals(employee.id) &&
Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
} | java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/examples/apigateway-event/src/main/java/com/fnproject/fn/examples/EmployeeService.java | examples/apigateway-event/src/main/java/com/fnproject/fn/examples/EmployeeService.java | package com.fnproject.fn.examples;
import java.util.Optional;
public class EmployeeService {
public ResponseEmployee createEmployee(RequestEmployee requestEmployee, Optional<String> id) {
if (requestEmployee == null) {
throw new IllegalArgumentException("requestEmployee must not be null");
}
if (!id.isPresent()) {
throw new IllegalArgumentException("id must not be null");
}
ResponseEmployee employee = new ResponseEmployee();
employee.setId(Integer.parseInt(id.get()));
employee.setName(requestEmployee.getName());
return employee;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-testing/src/test/java/com/fnproject/fn/testing/flow/IntegrationTest.java | flow-testing/src/test/java/com/fnproject/fn/testing/flow/IntegrationTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.fnproject.fn.testing.flow;
import com.fnproject.fn.testing.FnTestingRule;
import com.fnproject.fn.testing.FunctionError;
import com.fnproject.fn.testing.flowtestfns.ExerciseEverything;
import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
public class IntegrationTest {
@Rule
public FnTestingRule fn = FnTestingRule.createDefault();
public FlowTesting flow = FlowTesting.create(fn);
@Test
public void runIntegrationTests() {
flow.givenFn("testFunctionNonExistant")
.withFunctionError()
.givenFn("testFunction")
.withAction((body) -> {
if (new String(body).equals("PASS")) {
return "okay".getBytes();
} else {
throw new FunctionError("failed as demanded");
}
});
fn
.givenEvent()
.withBody("") // or "1,5,6,32" to select a set of tests individually
.enqueue()
.thenRun(ExerciseEverything.class, "handleRequest");
Assertions.assertThat(fn.getResults().get(0).getBodyAsString())
.endsWith("Everything worked\n");
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-testing/src/test/java/com/fnproject/fn/testing/flow/MultipleEventsTest.java | flow-testing/src/test/java/com/fnproject/fn/testing/flow/MultipleEventsTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.fnproject.fn.testing.flow;
import com.fnproject.fn.api.FnFeature;
import com.fnproject.fn.api.flow.Flow;
import com.fnproject.fn.api.flow.Flows;
import com.fnproject.fn.runtime.flow.FlowFeature;
import com.fnproject.fn.testing.FnTestingRule;
import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.Semaphore;
public class MultipleEventsTest {
@Rule
public FnTestingRule fn = FnTestingRule.createDefault();
public FlowTesting flow = FlowTesting.create(fn);
public static Semaphore oneGo = null;
public static Semaphore twoGo = null;
public static boolean success = false;
@FnFeature(FlowFeature.class)
public static class TestFn {
public void handleRequest(String s) {
switch (s) {
case "1":
Flows.currentFlow().supply(() -> one());
break;
case "2":
try {
MultipleEventsTest.twoGo.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
Flows.currentFlow().supply(() -> two());
break;
}
}
static void one() {
System.err.println("In one, making rt");
Flow fl1 = Flows.currentFlow();
System.err.println("In one, completedValue(1)");
fl1.completedValue(1);
System.err.println("One: Does fl1 == currentFlow? " + (fl1 == Flows.currentFlow()));
System.err.println("In one, letting two proceed");
MultipleEventsTest.twoGo.release();
System.err.println("In one, awaiting go signal");
try {
MultipleEventsTest.oneGo.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("In one, making second rt");
Flow fl3 = Flows.currentFlow();
System.err.println("In one, completedValue(3)");
fl3.completedValue(3);
success = fl1 == fl3;
System.err.println("One: Does fl3 == currentFlow? " + (fl3 == Flows.currentFlow()));
System.err.println("One: Does fl1 == fl3? " + success);
MultipleEventsTest.twoGo.release();
System.err.println("one completes");
}
static void two() {
System.err.println("In two, awaiting signal to proceed");
System.err.println("In two, making rt");
Flow fl2 = Flows.currentFlow();
System.err.println("In two, completedValue(2)");
fl2.completedValue(2);
System.err.println("Two: Does fl2 == currentFlow? " + (fl2 == Flows.currentFlow()));
System.err.println("In two, letting one proceed");
MultipleEventsTest.oneGo.release();
try {
MultipleEventsTest.twoGo.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("two completes");
}
}
@Test
public void OverlappingFlowInvocationsShouldWork() {
fn.addSharedClass(MultipleEventsTest.class);
oneGo = new Semaphore(0);
twoGo = new Semaphore(0);
success = false;
fn.givenEvent()
.withBody("1")
.enqueue()
.givenEvent()
.withBody("2")
.enqueue();
fn.thenRun(TestFn.class, "handleRequest");
Assertions.assertThat(success).isTrue();
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-testing/src/test/java/com/fnproject/fn/testing/flow/WhenCompleteTest.java | flow-testing/src/test/java/com/fnproject/fn/testing/flow/WhenCompleteTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.fnproject.fn.testing.flow;
import com.fnproject.fn.api.FnFeature;
import com.fnproject.fn.api.flow.Flows;
import com.fnproject.fn.runtime.flow.FlowFeature;
import com.fnproject.fn.testing.FnTestingRule;
import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
public class WhenCompleteTest {
@Rule
public FnTestingRule fn = FnTestingRule.createDefault();
private FlowTesting flow = FlowTesting.create(fn);
public static AtomicInteger cas = new AtomicInteger(0);
@FnFeature(FlowFeature.class)
public static class TestFn {
public void handleRequest() {
Flows.currentFlow().completedValue(1)
.whenComplete((v, e) -> WhenCompleteTest.cas.compareAndSet(0, 1))
.thenRun(() -> WhenCompleteTest.cas.compareAndSet(1, 2));
}
}
@Test
public void OverlappingFlowInvocationsShouldWork() {
fn.addSharedClass(WhenCompleteTest.class);
cas.set(0);
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "handleRequest");
Assertions.assertThat(cas.get()).isEqualTo(2);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-testing/src/test/java/com/fnproject/fn/testing/flow/FnTestingRuleFlowsTest.java | flow-testing/src/test/java/com/fnproject/fn/testing/flow/FnTestingRuleFlowsTest.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.fnproject.fn.testing.flow;
import com.fnproject.fn.api.*;
import com.fnproject.fn.api.flow.*;
import com.fnproject.fn.runtime.flow.FlowFeature;
import com.fnproject.fn.testing.FnTestingRule;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
public class FnTestingRuleFlowsTest {
@Rule
public FnTestingRule fn = FnTestingRule.createDefault();
private FlowTesting flow = FlowTesting.create(fn);
@FnFeature(FlowFeature.class)
public static class Loop {
public static int COUNT = 5;
public String repeat(String s) {
Flow fl = Flows.currentFlow();
return fl
.completedValue(new Triple<>(COUNT, s, ""))
.thenCompose(Loop::loop)
.get();
}
public static FlowFuture<String> loop(Triple<Integer, String, String> triple) {
int i = triple.first;
String s = triple.second;
String acc = triple.third;
Flow fl = Flows.currentFlow();
if (i == 0) {
return fl.completedValue(acc);
} else {
return fl.completedValue(triple(i - 1, s, acc + s))
.thenCompose(Loop::loop);
}
}
public static Triple<Integer, String, String> triple(int i, String s1, String s2) {
return new Triple<>(i, s1, s2);
}
public static class Triple<U, V, W> implements Serializable {
public final U first;
public final V second;
public final W third;
public Triple(U first, V second, W third) {
this.first = first;
this.second = second;
this.third = third;
}
}
}
@Before
public void setup() {
fn.addSharedClass(FnTestingRuleFlowsTest.class);
fn.addSharedClass(Result.class);
reset();
}
@Test
public void completedValue() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "completedValue");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.CompletedValue);
}
@Test
public void supply() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "supply");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.Supply);
}
@Test
public void allOf() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "allOf");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.AllOf);
}
@Test
public void anyOf() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "anyOf");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.AnyOf);
}
@Test()
public void nestedThenCompose() {
fn.givenEvent()
.withBody("hello world")
.enqueue();
fn.thenRun(Loop.class, "repeat");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(fn.getOnlyResult().getBodyAsString())
.isEqualTo(String.join("", Collections.nCopies(Loop.COUNT, "hello world")));
}
@Test
public void invokeFunctionWithResult() {
fn.givenEvent().enqueue();
flow.givenFn("user/echo")
.withResult(Result.InvokeFunctionFixed.name().getBytes());
fn.thenRun(TestFn.class, "invokeFunctionEcho");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.InvokeFunctionFixed);
}
@Test
public void invokeJsonFunction() {
fn.givenEvent().enqueue();
flow.givenFn("user/json")
.withAction((ign) -> {
if (new String(ign).equals("{\"foo\":\"bar\"}")) {
return "{\"foo\":\"baz\"}".getBytes();
} else {
return new byte[0];
}
});
fn.thenRun(TestFn.class, "invokeJsonFunction");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(count).isEqualTo(1);
}
@Test
public void invokeFunctionWithFunctionError() {
fn.givenEvent().enqueue();
flow.givenFn("user/error")
.withFunctionError();
fn.thenRun(TestFn.class, "invokeFunctionError");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.Exceptionally);
isInstanceOfAny(exception, FunctionInvocationException.class);
}
@Test
public void invokeFunctionWithFailedFuture() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "failedFuture");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.Exceptionally);
Assertions.assertThat(exception).isInstanceOf(RuntimeException.class);
Assertions.assertThat(exception).hasMessage("failedFuture");
}
@Test
public void invokeFunctionWithPlatformError() {
fn.givenEvent().enqueue();
flow.givenFn("user/error")
.withPlatformError();
fn.thenRun(TestFn.class, "invokeFunctionError");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.Exceptionally);
isInstanceOfAny(exception, PlatformException.class);
}
@Test
public void invokeFunctionWithAction() {
fn.givenEvent().enqueue();
flow.givenFn("user/echo")
.withAction((p) -> p);
fn.thenRun(TestFn.class, "invokeFunctionEcho");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.InvokeFunctionEcho);
}
@Test
public void completingExceptionally() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "completeExceptionally");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.Exceptionally);
}
@Test
public void completingExceptionallyWhenErrorIsThrownEarlyInGraph() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "completeExceptionallyEarly");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.Exceptionally);
}
@Test
public void cancelledFutureCompletesExceptionally() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "cancelFuture");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.Exceptionally);
Assertions.assertThat(exception).isInstanceOf(CancellationException.class);
}
@Test
public void completeFutureExceptionallyWithCustomException() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "completeFutureExceptionally");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.Exceptionally);
Assertions.assertThat(exception).isInstanceOf(RuntimeException.class);
Assertions.assertThat(exception.getMessage()).isEqualTo("Custom exception");
}
@Test
public void completedFutureCompletesNormally() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "completeFuture");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.CompletedValue);
}
@Test
public void uncompletedFutureCanBeCompleted() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "createFlowFuture");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.CompletedValue);
}
@Test
public void shouldLogMessagesToStdErrToPlatformStdErr() {
// Questionable: for testing, do we point all stderr stuff to the same log stream?
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "logToStdErrInContinuation");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(fn.getStdErrAsString()).contains("TestFn logging: 1");
}
@Test
public void shouldLogMessagesToStdOutToPlatformStdErr() {
// Questionable: for testing, do we point all stderr stuff to the same log stream?
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "logToStdOutInContinuation");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(fn.getStdErrAsString()).contains("TestFn logging: 1");
}
@Test
public void shouldHandleMultipleEventsForFunctionWithoutInput() {
fn.givenEvent().enqueue(2);
fn.thenRun(TestFn.class, "anyOf");
Assertions.assertThat(fn.getResults().get(0).getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(fn.getResults().get(1).getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.AnyOf);
}
@Test
public void exceptionallyComposeHandle() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "exceptionallyComposeHandle");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(count).isEqualTo(2);
}
@Test
public void exceptionallyComposePassThru() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "exceptionallyComposePassThru");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(count).isEqualTo(1);
}
@Test
public void exceptionallyComposeThrowsError() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "exceptionallyComposeThrowsError");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(count).isEqualTo(1);
}
@Test()
public void shouldHandleMultipleEventsForFunctionWithInput() {
String[] bodies = {"hello", "world", "test"};
for (int i = 0; i < bodies.length; i++) {
fn.givenEvent().withBody(bodies[i]).enqueue();
}
fn.thenRun(Loop.class, "repeat");
for (int i = 0; i < bodies.length; i++) {
Assertions.assertThat(fn.getResults().get(i).getBodyAsString())
.isEqualTo(String.join("", Collections.nCopies(Loop.COUNT, bodies[i])));
}
}
@Test()
public void shouldRunShutdownHooksInTest() {
fn.givenEvent().enqueue();
fn.thenRun(TestFn.class, "terminationHooks");
Assertions.assertThat(fn.getOnlyResult().getStatus()).isEqualTo(OutputEvent.Status.Success);
Assertions.assertThat(result).isEqualTo(Result.TerminationHookRun);
}
// Due to the alien nature of the stored exception, we supply a helper to assert isInstanceOfAny
void isInstanceOfAny(Object o, Class<?>... cs) {
Assertions.assertThat(o).isNotNull();
ClassLoader loader = o.getClass().getClassLoader();
for (Class<?> c : cs) {
try {
if (loader.loadClass(c.getName()).isAssignableFrom(o.getClass())) {
return;
}
} catch (ClassNotFoundException e) {
}
}
Assert.fail("Object " + o + "is not an instance of any of " + Arrays.toString(cs));
}
@FnFeature(FlowFeature.class)
public static class TestFn {
static Integer TO_ADD = null;
public TestFn(RuntimeContext ctx) {
TO_ADD = Integer.parseInt(ctx.getConfigurationByKey("ADD").orElse("-1"));
}
public void completedValue() {
Flows.currentFlow()
.completedValue(Result.CompletedValue).thenAccept((r) -> result = r);
}
public void supply() {
Flows.currentFlow()
.supply(() -> {
return Result.Supply;
}).thenAccept((r) -> result = r);
}
public void allOf() {
Flow fl = Flows.currentFlow();
fl.allOf(
fl.completedValue(1),
fl.completedValue(-1)
).thenAccept((r) -> {
result = Result.AllOf;
});
}
public void anyOf() {
Flow fl = Flows.currentFlow();
fl.anyOf(
fl.completedValue(1),
fl.completedValue(-1)
).thenAccept((r) -> result = Result.AnyOf);
}
public void thenCompose() {
Flow fl = Flows.currentFlow();
fl.completedValue(1)
.thenCompose((x) ->
fl.completedValue(1)
.thenApply((y) -> x + y)
)
.thenAccept((r) -> result = Result.AnyOf);
}
public void exceptionallyComposeHandle() {
Flow fl = Flows.currentFlow();
fl.<Integer>failedFuture(new RuntimeException("error"))
.exceptionallyCompose((e) -> {
if (count == 0 && e.getMessage().equals("error")) {
count = 1;
return fl.completedValue(1);
}
return fl.completedValue(0);
})
.thenAccept((i) -> {
if (count == 1 && i == 1) {
count++;
}
});
}
public void exceptionallyComposePassThru() {
Flow fl = Flows.currentFlow();
fl.completedValue(-1)
.exceptionallyCompose((e) -> {
count--;
return fl.completedValue(1);
})
.thenAccept((i) -> {
if (count == 0 && i == -1) {
count++;
}
});
}
public void exceptionallyComposeThrowsError() {
Flow fl = Flows.currentFlow();
fl.failedFuture(new RuntimeException("error"))
.exceptionallyCompose((e) -> {
if (e.getMessage().equals("error")) {
throw new RuntimeException("foo");
}
count--;
return fl.completedValue(-1);
})
.whenComplete((i, e) -> {
if (e != null && e.getMessage().equals("foo")) {
count++;
}
});
}
public void invokeFunctionEcho() {
Flow fl = Flows.currentFlow();
fl.invokeFunction("user/echo", HttpMethod.GET, Headers.emptyHeaders(), Result.InvokeFunctionEcho.name().getBytes())
.thenAccept((r) -> result = Result.valueOf(new String(r.getBodyAsBytes())));
}
public static class JSONObject implements Serializable{
public String foo = "bar";
}
public void invokeJsonFunction() {
Flows.currentFlow()
.invokeFunction("user/json", new JSONObject(), JSONObject.class)
.thenAccept((json) -> {
if (json.foo.equals("baz")) {
count = 1;
}
});
}
public void invokeFunctionError() {
Flow fl = Flows.currentFlow();
fl.invokeFunction("user/error", HttpMethod.GET, Headers.emptyHeaders(), new byte[]{})
.exceptionally((e) -> {
result = Result.Exceptionally;
exception = e;
return null;
});
}
public void completeExceptionally() {
Flow fl = Flows.currentFlow();
fl.supply(() -> {
throw new RuntimeException("This function should fail");
})
.exceptionally((ex) -> result = Result.Exceptionally);
}
public void failedFuture() {
Flow fl = Flows.currentFlow();
fl.failedFuture(new RuntimeException("failedFuture"))
.exceptionally((ex) -> {
result = Result.Exceptionally;
exception = ex;
return null;
});
}
public void completeExceptionallyEarly() {
Flow fl = Flows.currentFlow();
fl.completedValue(null)
.thenApply((x) -> {
throw new RuntimeException("This function should fail");
})
.thenApply((x) -> 2)
.exceptionally((ex) -> {
result = Result.Exceptionally;
return null;
});
}
public void cancelFuture() {
Flow fl = Flows.currentFlow();
FlowFuture<Result> f = fl.supply(() -> {
new CompletableFuture<>().get();
return Result.Supply;
});
f.exceptionally((ex) -> {
result = Result.Exceptionally;
exception = ex;
return Result.Exceptionally;
});
f.cancel();
}
public void completeFutureExceptionally() {
Flow fl = Flows.currentFlow();
FlowFuture<Result> f = fl.supply(() -> {
new CompletableFuture<>().get();
return Result.Supply;
});
f.exceptionally((ex) -> {
result = Result.Exceptionally;
exception = ex;
return Result.Exceptionally;
});
f.completeExceptionally(new RuntimeException("Custom exception"));
}
public void completeFuture() {
Flow fl = Flows.currentFlow();
FlowFuture<Result> f = fl.supply(() -> {
new CompletableFuture<>().get();
return Result.Supply;
});
f.thenAccept((r) -> result = r);
f.complete(Result.CompletedValue);
}
public void createFlowFuture() {
Flow fl = Flows.currentFlow();
FlowFuture<Result> f = fl.createFlowFuture();
f.thenAccept((r) -> result = r);
f.complete(Result.CompletedValue);
}
public void logToStdErrInContinuation() {
Flow fl = Flows.currentFlow();
fl.completedValue(1)
.thenApply((x) -> {
System.err.println("TestFn logging: " + x);
return x;
})
.thenApply((x) -> x + 1);
}
public void logToStdOutInContinuation() {
Flow fl = Flows.currentFlow();
fl.completedValue(1)
.thenApply((x) -> {
System.err.println("TestFn logging: " + x);
return x;
})
.thenApply((x) -> x + 1);
}
public void cannotReadConfigVarInContinuation() {
Flow fl = Flows.currentFlow();
TO_ADD = 3;
fl.completedValue(1)
.thenAccept((x) -> {
staticConfig = TO_ADD;
});
}
public void terminationHooks() {
Flow fl = Flows.currentFlow();
fl.supply(() -> 1)
.thenAccept((i) -> {
System.err.println("Hello");
});
fl.addTerminationHook((s) -> {
if (staticConfig == 2) {
result = Result.TerminationHookRun;
}
});
fl.addTerminationHook((s) -> {
staticConfig++;
});
fl.addTerminationHook((s) -> {
staticConfig = 1;
});
}
}
public enum Result {
CompletedValue,
Supply,
AllOf,
InvokeFunctionEcho,
InvokeFunctionFixed,
AnyOf, Exceptionally,
ThenCompose,
ThenComplete,
TerminationHookRun
}
static void reset() {
result = null;
exception = null;
staticConfig = null;
count = 0;
}
// These members are external to the class under test so as to be visible from the unit tests.
// They must be public, since the TestFn class will be instantiated under a separate ClassLoader;
// therefore we need broader access than might be anticipated.
public static volatile Result result = null;
public static volatile Throwable exception = null;
public static volatile Integer staticConfig = null;
public static volatile Integer count = 0;
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-testing/src/test/java/com/fnproject/fn/testing/flowtestfns/ExerciseEverything.java | flow-testing/src/test/java/com/fnproject/fn/testing/flowtestfns/ExerciseEverything.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.fnproject.fn.testing.flowtestfns;
import com.fnproject.fn.api.*;
import com.fnproject.fn.api.flow.*;
import com.fnproject.fn.runtime.flow.FlowFeature;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.TeeOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
@FnFeature(FlowFeature.class)
public class ExerciseEverything {
private boolean okay = true;
private ByteArrayOutputStream bos = new ByteArrayOutputStream();
private PrintStream out = new PrintStream(new TeeOutputStream(System.err, bos));
private String testSelector = null;
private InputEvent inputEvent;
private List<Integer> failures = new ArrayList<>();
@Test(1)
@Test.Expect("completed value")
public FlowFuture<String> completedValue(Flow fl) {
return fl.completedValue("completed value");
}
@Test(2)
@Test.Expect("supply")
public FlowFuture<String> supply(Flow fl) {
return fl.supply(() -> "supply");
}
@Test(3)
public FlowFuture<Void> allOfWithCompletedValue(Flow fl) {
return fl.allOf(
fl.completedValue(1),
fl.completedValue(2),
fl.completedValue(3)
);
}
@Test(4)
public FlowFuture<Void> allOfWithSuppliedValue(Flow fl) {
return fl.allOf(
fl.supply(() -> 1),
fl.supply(() -> 2),
fl.supply(() -> 3)
);
}
@Test(5)
@Test.Expect("1")
@Test.Expect("2")
@Test.Expect("3")
public FlowFuture<Object> anyOfWithCompletedValue(Flow fl) {
return fl.anyOf(
fl.completedValue("1"),
fl.completedValue("2"),
fl.completedValue("3")
);
}
@Test(6)
@Test.Expect("1")
@Test.Expect("2")
@Test.Expect("3")
public FlowFuture<Object> anyOfWithSuppliedValue(Flow fl) {
return fl.anyOf(
fl.supply(() -> "1"),
fl.supply(() -> "2"),
fl.supply(() -> "3")
);
}
@Test(7)
@Test.Expect("test exception")
public FlowFuture<Exception> completeWithAnException(Flow fl) {
return fl.completedValue(new Exception("test exception"));
}
@Test(8)
@Test.Catch({FlowCompletionException.class, MyException.class})
public FlowFuture<String> supplyAnException(Flow fl) {
return fl.supply(() -> {
throw new MyException("test exception");
});
}
public static class MyException extends RuntimeException {
MyException(String m) {
super(m);
}
}
@Test(9)
@Test.Expect("4")
public FlowFuture<Integer> chainThenApply(Flow fl) {
FlowFuture<Integer> cf = fl.completedValue(0);
for (int i = 0; i < 4; i++) {
cf = cf.thenApply((x) -> x + 1);
}
return cf;
}
@Test(10)
@Test.Expect("-3")
public FlowFuture<Integer> catchBubbledException(Flow fl) {
return fl.completedValue(0)
.thenApply((x) -> x + 1)
.thenApply((x) -> {
if (x == 1) throw new MyException("boom");
else return x + 1;
})
.thenApply((x) -> x + 1)
.thenApply((x) -> x + 1)
.exceptionally((e) -> -3);
}
@Test(11)
@Test.Catch({FlowCompletionException.class, FunctionInvocationException.class})
public FlowFuture<HttpResponse> nonexistentExternalEvaluation(Flow fl) {
return fl.invokeFunction("testFunctionNonExistant", HttpMethod.POST, Headers.emptyHeaders(), new byte[0]);
}
@Test(12)
@Test.Expect("okay")
public FlowFuture<String> checkPassingInvocation(Flow fl) {
return fl.invokeFunction("testFunction", HttpMethod.POST, Headers.emptyHeaders(), "PASS".getBytes())
.thenApply((resp) -> resp.getStatusCode() != 200 ? "failure" : new String(resp.getBodyAsBytes()));
}
// There is currently no way for a hot function to signal failure in the Fn platform.
// This test will only work in default mode.
@Test(13)
@Test.Catch({FlowCompletionException.class, FunctionInvocationException.class})
public FlowFuture<HttpResponse> checkFailingInvocation(Flow fl) {
return fl.invokeFunction("testFunction", HttpMethod.POST, Headers.emptyHeaders(), "FAIL".getBytes());
}
// This original version captures the RT, which captures the factory, which is not serializable
@Test(14)
@Test.Expect("X")
public FlowFuture<String> simpleThenCompose(Flow fl) {
return fl.completedValue("x").thenCompose((s) -> {
System.err.println("I am in the thenCompose stage, s = " + s);
FlowFuture<String> retVal = fl.completedValue(s.toUpperCase());
System.err.println("my retVal = " + retVal + "; type is " + retVal.getClass());
return retVal;
});
}
@Test(15)
@Test.Expect("hello world")
public FlowFuture<String> thenCompose(Flow fl) {
return fl.completedValue("hello")
.thenCompose((s) ->
fl.supply(() -> s)
.thenApply((s2) -> s2 + " world")
);
}
@Test(16)
@Test.Expect("foo")
public FlowFuture<String> thenComposeThenError(Flow fl) {
return fl.completedValue("hello")
.thenCompose((s) -> fl.supply(() -> {
if (s.equals("hello")) throw new MyException("foo");
else return s;
}))
.exceptionally(Throwable::getMessage);
}
@Test(17)
@Test.Expect("foo")
public FlowFuture<String> thenComposeWithErrorInBody(Flow fl) {
return fl.completedValue("hello")
.thenCompose((s) -> {
if (s.equals("hello")) throw new MyException("foo");
else return fl.completedValue(s);
})
.exceptionally(Throwable::getMessage);
}
@Test(18)
@Test.Expect("a")
@Test.Expect("b")
public FlowFuture<String> applyToEither(Flow fl) {
return fl.completedValue("a").applyToEither(fl.completedValue("b"), (x) -> x);
}
@Test(19)
@Test.Expect("a")
@Test.Expect("b")
public FlowFuture<String> applyToEitherLikelyPathB(Flow fl) {
return fl.supply(() -> "a").applyToEither(fl.completedValue("b"), (x) -> x);
}
@Test(20)
public FlowFuture<Void> harmlessAcceptBoth(Flow fl) {
return fl.completedValue("a")
.thenAcceptBoth(
fl.completedValue("b"),
(a, b) -> System.err.println(a + "; " + b)
);
}
@Test(21)
@Test.Catch({FlowCompletionException.class, MyException.class})
@Test.Expect("ab")
public FlowFuture<Void> acceptBoth(Flow fl) {
return fl.completedValue("a")
.thenAcceptBoth(
fl.completedValue("b"),
(a, b) -> {
System.err.println("A is " + a + " and B is " + b);
throw new MyException(a + b);
});
}
@Test(22)
@Test.Catch({FlowCompletionException.class, MyException.class})
@Test.Expect("a")
@Test.Expect("b")
public FlowFuture<Void> acceptEither(Flow fl) {
return fl.completedValue("a")
.acceptEither(
fl.completedValue("b"),
(x) -> {
throw new MyException(x);
}
);
}
@Test(23)
@Test.Expect("foobar")
public FlowFuture<String> thenCombine(Flow fl) {
return fl.completedValue("foo")
.thenCombine(fl.completedValue("bar"),
(a, b) -> a + b);
}
@Test(24)
@Test.Expect("foo")
public FlowFuture<String> thenCombineE1(Flow fl) {
return fl.supply(() -> {
throw new MyException("foo");
})
.thenCombine(fl.completedValue("bar"),
(a, b) -> a + b)
.exceptionally(Throwable::getMessage);
}
@Test(25)
@Test.Expect("bar")
public FlowFuture<String> thenCombineE2(Flow fl) {
return fl.completedValue("foo")
.thenCombine(fl.supply(() -> {
throw new MyException("bar");
}),
(a, b) -> a + b)
.exceptionally(Throwable::getMessage);
}
@Test(26)
@Test.Expect("foobar")
public FlowFuture<String> thenCombineE3(Flow fl) {
return fl.completedValue("foo")
.thenCombine(fl.completedValue("bar"),
(a, b) -> {
if (!a.equals(b)) throw new MyException(a + b);
else return "baz";
})
.exceptionally(Throwable::getMessage);
}
@Test(27)
@Test.Expect("foo")
public FlowFuture<String> handleNoError(Flow fl) {
return fl.completedValue("foo")
.handle((v, e) -> v);
}
@Test(28)
@Test.Expect("bar")
public FlowFuture<String> handleWithError(Flow fl) {
return fl.supply(() -> {
throw new MyException("bar");
})
.handle((v, e) -> e.getMessage());
}
@Test(29)
@Test.Expect("foo")
public FlowFuture<String> whenCompleteNoError(Flow fl) {
return fl.completedValue("foo")
.whenComplete((v, e) -> {
System.err.println("In whenComplete, v=" + v);
throw new MyException(v);
})
.exceptionally(t -> {
// Should *not* get called.
System.err.println("In whenComplete.exceptionally, t=" + t);
return t.getMessage() + "bar";
});
}
@Test(30)
@Test.Expect("barbaz")
public FlowFuture<String> whenCompleteWithError(Flow fl) {
return fl.supply(() -> {
if (true) throw new MyException("bar");
else return "";
})
.whenComplete((v, e) -> {
System.err.println("In whenComplete, e=" + e);
throw new MyException(e.getMessage());
})
.exceptionally(t -> {
System.err.println("In whenComplete (with error) exceptionally , t=" + t);
return t.getMessage() + "baz";
});
}
@Test(35)
@Test.Expect("foobar")
public FlowFuture<String> exceptionallyComposeHandle(Flow fl) throws IOException {
return fl.<String>failedFuture(new RuntimeException("foobar"))
.exceptionallyCompose((e) -> fl.completedValue(e.getMessage()));
}
@Test(36)
@Test.Expect("foobar")
public FlowFuture<String> exceptionallyComposePassThru(Flow fl) throws IOException {
return fl.completedValue("foobar")
.exceptionallyCompose((e) -> fl.completedValue(e.getMessage()));
}
@Test(37)
@Test.Expect("foobar")
public FlowFuture<String> exceptionallyComposePropagateError(Flow fl) throws IOException {
return fl.<String>failedFuture(new RuntimeException("foo"))
.exceptionallyCompose((e) -> {
throw new RuntimeException("foobar");
}).exceptionally(Throwable::getMessage);
}
private int id;
private final RuntimeContext runtimeContext;
public ExerciseEverything(RuntimeContext rtc){
this.runtimeContext = rtc;
}
void fail() {
if (!failures.contains(id)) {
failures.add(id);
}
okay = false;
}
public String handleRequest(InputEvent ie) {
this.inputEvent = ie;
String selector = ie.consumeBody((InputStream is) -> {
try {
return IOUtils.toString(is, "utf-8");
} catch (IOException e) {
return "FAIL";
}
});
if ("PASS".equals(selector)) {
return "okay";
} else if ("FAIL".equals(selector)) {
throw new MyException("failure demanded");
}
testSelector = selector;
Flow fl = Flows.currentFlow();
out.println("In main function");
Map<Integer, FlowFuture<Object>> awaiting = new TreeMap<>();
for (Map.Entry<Integer, Method> e : findTests(this).entrySet()) {
id = e.getKey();
Method m = e.getValue();
out.println("Running test " + id);
Test.Catch exWanted = m.getAnnotation(Test.Catch.class);
String[] values = expectedValues(m);
try {
awaiting.put(id, (FlowFuture<Object>) m.invoke(this, fl));
} catch (InvocationTargetException ex) {
out.println("Failure setting up test " + id + ": " + ex.getCause());
ex.printStackTrace(out);
fail();
} catch (IllegalAccessException e1) {
}
}
for (Map.Entry<Integer, Method> e : findTests(this).entrySet()) {
id = e.getKey();
Method m = e.getValue();
out.println("Running test " + id);
Test.Catch exWanted = m.getAnnotation(Test.Catch.class);
String[] values = expectedValues(m);
try {
FlowFuture<Object> cf = awaiting.get(id);
if (cf == null) {
continue;
}
Object r = cf.get();
// Coerce returned value to string
String rv = coerceToString(r);
if (!huntForValues(rv, values)) {
fail();
}
if (exWanted != null) {
out.println(" expecting throw of " + Arrays.toString(exWanted.value()));
fail();
}
} catch (Throwable t) {
if (exWanted != null) {
// We have a series of wrapped exceptions that should follow this containment pattern
boolean found = false;
for (Class<?> c : exWanted.value()) {
if (t == null) {
out.println(" end of exception chain, wanted " + c);
fail();
break;
}
if (c.isAssignableFrom(t.getClass())) {
out.println(" exception type as wanted: " + t);
String message = coerceToString(t);
found = found || huntForValues(message, values);
} else {
out.println(" exception type mismatch: " + t + ", wanted " + c);
out.println(" Class loaders: " + t.getClass().getClassLoader() + ", wanted " + c.getClassLoader());
t.printStackTrace(out);
fail();
break;
}
t = t.getCause();
}
if (!found && values.length > 0) {
out.println(" failed comparison, wanted exception with one of " + Arrays.toString(values));
fail();
}
} else {
out.println(" got an unexpected exception: " + t);
t.printStackTrace(out);
fail();
}
}
}
out.println(okay ? "Everything worked" : "There were failures: " + failures);
out.flush();
return bos.toString();
}
String coerceToString(Object r) {
if (r == null) {
return null;
} else if (r instanceof String) {
// okay
return (String) r;
} else if (r instanceof Throwable) {
return ((Throwable) r).getMessage();
} else if (r instanceof HttpRequest) {
return new String(((HttpRequest) r).getBodyAsBytes());
} else if (r instanceof HttpResponse) {
return new String(((HttpResponse) r).getBodyAsBytes());
} else {
return r.toString();
}
}
String[] expectedValues(Method m) {
Test.Expected ex = m.getAnnotation(Test.Expected.class);
if (ex != null) {
return Arrays.stream(ex.value()).map(Test.Expect::value).toArray(String[]::new);
} else {
Test.Expect ex2 = m.getAnnotation(Test.Expect.class);
if (ex2 != null) {
return new String[]{ex2.value()};
} else {
return new String[]{};
}
}
}
boolean huntForValues(String match, String... values) {
for (String v : values) {
if ((v == null && match == null) || (v != null && v.equals(match))) {
out.println(" successfully = " + match);
return true;
}
}
if (values.length > 0) {
out.println(" failed comparison, wanted one of " + Arrays.toString(values) + " but got " + match);
return false;
}
return true;
}
Map<Integer, Method> findTests(Object target) {
Map<Integer, Method> tests = new TreeMap<>();
for (Method m : target.getClass().getMethods()) {
Test ann = m.getAnnotation(Test.class);
if (ann == null)
continue;
int id = ann.value();
tests.put(id, m);
}
if (testSelector == null || testSelector.trim().isEmpty()) {
return tests;
}
return Arrays.stream(testSelector.split(","))
.map(String::trim)
.map(Integer::valueOf)
.filter(tests::containsKey)
.collect(Collectors.toMap((x) -> x, tests::get));
}
@Retention(RetentionPolicy.RUNTIME)
public static @interface Test {
int value();
@Retention(RetentionPolicy.RUNTIME)
@interface Expected {
Expect[] value();
}
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Expected.class)
@interface Expect {
String value();
}
@Retention(RetentionPolicy.RUNTIME)
@interface Catch {
Class<?>[] value();
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-testing/src/main/java/com/fnproject/fn/testing/flow/InMemCompleter.java | flow-testing/src/main/java/com/fnproject/fn/testing/flow/InMemCompleter.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.fnproject.fn.testing.flow;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.flow.*;
import com.fnproject.fn.runtime.flow.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* In memory completer
*/
class InMemCompleter implements CompleterClient, BlobStoreClient, CompleterClientFactory {
private final Map<FlowId, Flow> graphs = new ConcurrentHashMap<>();
private final AtomicInteger threadCount = new AtomicInteger();
private final CompleterInvokeClient completerInvokeClient;
private final FnInvokeClient fnInvokeClient;
private static ScheduledThreadPoolExecutor spe = new ScheduledThreadPoolExecutor(1);
private static ExecutorService faasExecutor = Executors.newCachedThreadPool();
@Override
public BlobResponse writeBlob(String prefix, byte[] bytes, String contentType) {
FlowId flow = new FlowId(prefix);
if (!graphs.containsKey(flow)) {
throw new IllegalStateException("flow " + flow + " does not exist");
}
String blobId = UUID.randomUUID().toString();
Blob blob = new Blob(bytes, contentType);
graphs.get(flow).blobs.put(blobId, blob);
BlobResponse returnBlob = new BlobResponse();
returnBlob.blobId = blobId;
returnBlob.contentType = contentType;
returnBlob.blobLength = (long) bytes.length;
return returnBlob;
}
@Override
public <T> T readBlob(String prefix, String blobId, Function<InputStream, T> reader, String expectedContentType) {
FlowId flow = new FlowId(prefix);
if (!graphs.containsKey(flow)) {
throw new IllegalStateException("flow " + flow + " does not exist");
}
Blob blob = graphs.get(flow).blobs.get(blobId);
if (blob == null) {
throw new IllegalStateException("Blob " + blobId + " not found");
}
if (!blob.contentType.equals(expectedContentType)) {
throw new IllegalStateException("Blob content type mismatch");
}
ByteArrayInputStream bis = new ByteArrayInputStream(blob.data);
return reader.apply(bis);
}
@Override
public CompleterClient getCompleterClient() {
return this;
}
@Override
public BlobStoreClient getBlobStoreClient() {
return this;
}
public interface CompleterInvokeClient {
APIModel.CompletionResult invokeStage(String fnId, FlowId flowId, CompletionId stageId, APIModel.Blob closure, List<APIModel.CompletionResult> body);
}
public interface FnInvokeClient {
CompletableFuture<HttpResponse> invokeFunction(String fnId, HttpMethod method, Headers headers, byte[] data);
}
InMemCompleter(CompleterInvokeClient completerInvokeClient, FnInvokeClient fnInvokeClient) {
this.completerInvokeClient = completerInvokeClient;
this.fnInvokeClient = fnInvokeClient;
}
void awaitTermination() {
while (true) {
int aliveCount = 0;
for (Map.Entry<FlowId, Flow> e : graphs.entrySet()) {
if (!e.getValue().isCompleted()) {
aliveCount++;
}
}
if (aliveCount > 0) {
try {
Thread.sleep(150);
} catch (InterruptedException e) {
}
} else {
break;
}
}
}
@Override
public FlowId createFlow(String functionId) {
FlowId id = new FlowId("flow-" + threadCount.incrementAndGet());
graphs.put(id, new Flow(functionId, id));
return id;
}
@Override
public CompletionId supply(FlowId flowID, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowID, flow -> flow.addSupplyStage(serializeJava(flowID, code))).getId();
}
private APIModel.Blob serializeJava(FlowId flowId, Object code) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(code);
oos.close();
BlobResponse blobResponse = writeBlob(flowId.getId(), bos.toByteArray(), RemoteFlowApiClient.CONTENT_TYPE_JAVA_OBJECT);
return APIModel.Blob.fromBlobResponse(blobResponse);
} catch (Exception e) {
e.printStackTrace();
throw new LambdaSerializationException("Error serializing closure");
}
}
private <T> T withActiveGraph(FlowId t, Function<Flow, T> act) {
Flow g = graphs.get(t);
if (g == null) {
throw new PlatformException("unknown graph " + t.getId());
}
if (g.mainFinished.get()) {
throw new PlatformException("graph already run");
}
return act.apply(g);
}
@Override
public CompletionId thenApply(FlowId flowID, CompletionId completionId, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowID,
(flow) -> flow.withStage(completionId,
(parent) -> parent.addThenApplyStage(serializeJava(flowID, code)))).getId();
}
@Override
public CompletionId whenComplete(FlowId flowID, CompletionId completionId, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowID,
(flow) -> flow.withStage(completionId,
(parent) -> parent.addWhenCompleteStage(serializeJava(flowID, code)))).getId();
}
@Override
public CompletionId thenCompose(FlowId flowId, CompletionId completionId, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) -> flow.withStage(completionId,
(parent) -> parent.addThenComposeStage(serializeJava(flowId, code)))).getId();
}
private <T> T doInClassLoader(ClassLoader cl, Callable<T> call) throws Exception {
ClassLoader myCL = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(cl);
return call.call();
} finally {
Thread.currentThread().setContextClassLoader(myCL);
}
}
@Override
public Object waitForCompletion(FlowId flowId, CompletionId completionId, ClassLoader loader) {
return withActiveGraph(flowId, (flow) -> flow.withStage(completionId, (stage) -> {
try {
return stage.outputFuture().toCompletableFuture().get().toJava(flowId, this, loader);
} catch (ExecutionException e) {
if (e.getCause() instanceof ResultException) {
APIModel.CompletionResult r = ((ResultException) e.getCause()).toResult();
Object err = r.toJava(flowId, this, loader);
if (err instanceof Throwable) {
throw new FlowCompletionException((Throwable) err);
} else if (err instanceof HttpResponse && !r.successful) {
throw new FlowCompletionException(new FunctionInvocationException((HttpResponse) err));
}
throw new PlatformException(e);
} else {
throw new PlatformException(e);
}
} catch (Exception e) {
throw new PlatformException(e);
}
}));
}
@Override
public Object waitForCompletion(FlowId flowId, CompletionId completionId, ClassLoader loader, long timeout, TimeUnit unit) throws TimeoutException {
try {
return withActiveGraph(flowId, (flow) -> flow.withStage(completionId, (stage) -> {
try {
ClassLoader myCL = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(loader);
return stage.outputFuture().toCompletableFuture().get().toJava(flowId, this, loader);
} finally {
Thread.currentThread().setContextClassLoader(myCL);
}
} catch (ExecutionException e) {
if (e.getCause() instanceof ResultException) {
APIModel.CompletionResult r = ((ResultException) e.getCause()).toResult();
Object err = r.toJava(flowId, this, loader);
if (err instanceof Throwable) {
throw new FlowCompletionException((Throwable) err);
} else if (err instanceof HttpResponse && !r.successful) {
throw new FlowCompletionException(new FunctionInvocationException((HttpResponse) err));
}
throw new PlatformException(e);
} else {
throw new PlatformException(e);
}
} catch (Exception e) {
throw new PlatformException(e);
}
}));
} catch (PlatformException e) {
if (e.getCause() instanceof TimeoutException) {
throw (TimeoutException) e.getCause();
} else throw e;
}
}
@Override
public CompletionId thenAccept(FlowId flowId, CompletionId completionId, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) -> flow.withStage(completionId,
(parent) -> parent.addThenAcceptStage(serializeJava(flowId, code)))).getId();
}
@Override
public CompletionId thenRun(FlowId flowId, CompletionId completionId, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) -> flow.withStage(completionId,
(parent) -> parent.addThenRunStage(serializeJava(flowId, code)))).getId();
}
@Override
public CompletionId acceptEither(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) ->
flow.withStage(alternate,
(other) ->
flow.appendChildStage(completionId,
(parent) -> parent.addAcceptEitherStage(other, serializeJava(flowId, code))).getId()));
}
@Override
public CompletionId applyToEither(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) ->
flow.withStage(alternate,
(other) ->
flow.withStage(completionId,
(parent) -> parent.addApplyToEitherStage(other, serializeJava(flowId, code))).getId()));
}
@Override
public boolean complete(FlowId flowId, CompletionId completionId, Object value, CodeLocation codeLocation) {
return withActiveGraph(flowId, (flow) -> flow.withStage(completionId, (stage) -> stage.complete(APIModel.BlobDatum.fromBlob(serializeJava(flowId, value)))));
}
@Override
public boolean completeExceptionally(FlowId flowId, CompletionId completionId, Throwable value, CodeLocation codeLocation) {
return withActiveGraph(flowId, (flow) -> flow.withStage(completionId, (stage) -> stage.completeExceptionally(APIModel.BlobDatum.fromBlob(serializeJava(flowId, value)))));
}
@Override
public CompletionId anyOf(FlowId flowId, List<CompletionId> cids, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) ->
flow.withStages(cids, flow::addAnyOf).getId());
}
@Override
public CompletionId delay(FlowId flowId, long l, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) -> flow.addDelayStage(l)).getId();
}
@Override
public CompletionId thenAcceptBoth(FlowId flowId, CompletionId completionId, CompletionId alternate, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) ->
flow.withStage(alternate,
(other) ->
flow.withStage(completionId,
(parent) -> parent.addThenAcceptBothStage(other, serializeJava(flowId, code))).getId()));
}
@Override
public CompletionId createCompletion(FlowId flowId, CodeLocation codeLocation) {
CompletableFuture<APIModel.CompletionResult> resultFuture = new CompletableFuture<>();
Flow.Stage stage = withActiveGraph(flowId,
flow -> flow.addExternalStage(resultFuture));
return stage.getId();
}
@Override
public CompletionId invokeFunction(FlowId flowId, String functionId, byte[] data, HttpMethod method, Headers headers, CodeLocation codeLocation) {
return withActiveGraph(flowId, (flow) ->
flow.addInvokeFunction(functionId, method, headers, data)).getId();
}
@Override
public CompletionId completedValue(FlowId flowId, boolean success, Object value, CodeLocation codeLocation) {
return withActiveGraph(flowId, (flow) ->
flow.addCompletedValue(success, APIModel.BlobDatum.fromBlob(serializeJava(flowId, value)))).getId();
}
@Override
public CompletionId allOf(FlowId flowId, List<CompletionId> cids, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) ->
flow.withStages(cids, flow::addAllOf).getId());
}
@Override
public CompletionId handle(FlowId flowId, CompletionId completionId, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) ->
flow.withStage(completionId,
(stage) -> stage.addHandleStage(serializeJava(flowId, code))).getId());
}
@Override
public CompletionId exceptionally(FlowId flowId, CompletionId completionId, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) ->
flow.withStage(completionId,
(stage) -> stage.addExceptionallyStage(serializeJava(flowId, code))).getId());
}
@Override
public CompletionId exceptionallyCompose(FlowId flowId, CompletionId completionId, Serializable code, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) ->
flow.withStage(completionId,
(stage) -> stage.addExceptionallyComposeStage(serializeJava(flowId, code))).getId());
}
@Override
public CompletionId thenCombine(FlowId flowId, CompletionId completionId, Serializable code, CompletionId alternate, CodeLocation codeLocation) {
return withActiveGraph(flowId,
(flow) ->
flow.withStage(alternate,
(other) ->
flow.appendChildStage(completionId,
(parent) -> parent.addThenCombineStage(other, serializeJava(flowId, code))).getId()));
}
@Override
public void commit(FlowId flowId) {
withActiveGraph(flowId, Flow::commit);
}
@Override
public void addTerminationHook(FlowId flowId, Serializable code, CodeLocation codeLocation) {
withActiveGraph(flowId, (g) -> {
g.addTerminationHook(serializeJava(flowId, code));
return null;
});
}
private static class TerminationHook {
private final CompletionId id;
private final APIModel.Blob code;
private TerminationHook(CompletionId id, APIModel.Blob code) {
this.id = id;
this.code = code;
}
}
class Blob {
private final byte[] data;
private final String contentType;
Blob(byte[] data, String contentType) {
this.data = data;
this.contentType = contentType;
}
}
class Flow {
private final Map<String, Blob> blobs = new HashMap<>();
private final String functionId;
private final FlowId flowId;
private final AtomicBoolean committed = new AtomicBoolean(false);
private final AtomicInteger stageCount = new AtomicInteger();
private final AtomicInteger activeCount = new AtomicInteger();
private final Map<CompletionId, Stage> stages = new ConcurrentHashMap<>();
private final AtomicBoolean mainFinished = new AtomicBoolean(false);
private final AtomicReference<com.fnproject.fn.api.flow.Flow.FlowState> terminationSTate = new AtomicReference<>();
private final AtomicBoolean complete = new AtomicBoolean(false);
private final List<TerminationHook> terminationHooks = Collections.synchronizedList(new ArrayList<>());
Flow(String functionId, FlowId flowId) {
this.functionId = functionId;
this.flowId = flowId;
}
boolean isCompleted() {
return complete.get();
}
private void checkCompletion() {
if (!mainFinished.get()) {
if (committed.get() && activeCount.get() == 0) {
mainFinished.set(true);
workShutdown();
}
}
}
private void workShutdown() {
if (terminationHooks.size() != 0) {
TerminationHook hook = terminationHooks.remove(0);
CompletableFuture.runAsync(() -> {
completerInvokeClient.invokeStage(functionId, flowId, hook.id, hook.code,
Collections.singletonList(APIModel.CompletionResult.success(APIModel.StatusDatum.fromType(APIModel.StatusDatumType.Succeeded))));
}).whenComplete((r, e) -> this.workShutdown());
} else {
complete.set(true);
}
}
private boolean commit() {
boolean commitResult = committed.compareAndSet(false, true);
if (commitResult) {
checkCompletion();
}
return commitResult;
}
private Optional<Stage> findStage(CompletionId ref) {
return Optional.ofNullable(stages.get(ref));
}
private Stage addStage(Stage stage) {
stages.put(stage.getId(), stage);
return stage;
}
private CompletionId newStageId() {
return new CompletionId("" + stageCount.incrementAndGet());
}
private Stage appendChildStage(CompletionId cid, Function<Stage, Stage> ctor) {
Stage newStage = withStage(cid, ctor);
stages.put(newStage.getId(), newStage);
return newStage;
}
private <T> T withStage(CompletionId cid, Function<Stage, T> function) {
Stage stage = stages.get(cid);
if (stage == null) {
throw new PlatformException("Stage not found in graph :" + cid);
}
return function.apply(stage);
}
private <T> T withStages(List<CompletionId> cids, Function<List<Stage>, T> function) {
List<Stage> stages = new ArrayList<>();
for (CompletionId cid : cids) {
Stage stage = this.stages.get(cid);
if (stage == null) {
throw new PlatformException("Stage not found in graph :" + cid);
}
stages.add(stage);
}
return function.apply(stages);
}
private Stage addCompletedValue(boolean success, APIModel.Datum value) {
CompletableFuture<APIModel.CompletionResult> future;
if (success) {
future = CompletableFuture.completedFuture(APIModel.CompletionResult.success(value));
} else {
future = new CompletableFuture<>();
future.completeExceptionally(new ResultException(value));
}
return addStage(new Stage(CompletableFuture.completedFuture(Collections.emptyList()),
(x, f) -> future));
}
private Stage addAllOf(List<Stage> cns) {
List<CompletableFuture<APIModel.CompletionResult>> outputs = cns.stream().map(Stage::outputFuture).map(CompletionStage::toCompletableFuture).collect(Collectors.toList());
CompletionStage<APIModel.CompletionResult> output = CompletableFuture
.allOf(outputs.toArray(new CompletableFuture<?>[outputs.size()]))
.thenApply((nv) -> APIModel.CompletionResult.success(new APIModel.EmptyDatum()));
return addStage(new Stage(
CompletableFuture.completedFuture(Collections.emptyList()),
(n, f) -> output));
}
private Stage addAnyOf(List<Stage> cns) {
List<CompletableFuture<APIModel.CompletionResult>> outputs = cns.stream().map(Stage::outputFuture).map(CompletionStage::toCompletableFuture).collect(Collectors.toList());
CompletionStage<APIModel.CompletionResult> output = CompletableFuture
.anyOf(outputs.toArray(new CompletableFuture<?>[outputs.size()])).thenApply((s) -> (APIModel.CompletionResult) s);
return addStage(new Stage(CompletableFuture.completedFuture(Collections.emptyList()),
(n, x) -> output
));
}
private Stage addSupplyStage(APIModel.Blob closure) {
CompletableFuture<List<APIModel.CompletionResult>> input = CompletableFuture.completedFuture(Collections.emptyList());
return addStage(new Stage(input, chainInvocation(closure)));
}
private Stage addExternalStage(CompletableFuture<APIModel.CompletionResult> future) {
return addStage(new Stage(CompletableFuture.completedFuture(Collections.emptyList()),
(n, v) -> future));
}
private Stage addDelayStage(long delay) {
CompletableFuture<APIModel.CompletionResult> future = new CompletableFuture<>();
spe.schedule(() -> future.complete(APIModel.CompletionResult.success(new APIModel.EmptyDatum())), delay, TimeUnit.MILLISECONDS);
return addStage(new Stage(CompletableFuture.completedFuture(Collections.emptyList()),
(n, v) -> future));
}
private Stage addInvokeFunction(String functionId, HttpMethod method, Headers headers, byte[] data) {
return addStage(new Stage(CompletableFuture.completedFuture(Collections.emptyList()),
(n, in) -> {
return in.thenComposeAsync((ignored) -> {
CompletionStage<HttpResponse> respFuture = fnInvokeClient.invokeFunction(functionId, method, headers, data);
return respFuture.thenApply((res) -> {
APIModel.HTTPResp apiResp = new APIModel.HTTPResp();
List<APIModel.HTTPHeader> callHeaders = new ArrayList<>();
for (Map.Entry<String, List<String>> e : res.getHeaders().asMap().entrySet()) {
for (String v : e.getValue()) {
callHeaders.add(APIModel.HTTPHeader.create(e.getKey(), v));
}
}
apiResp.headers = callHeaders;
BlobResponse blobResponse = writeBlob(flowId.getId(), res.getBodyAsBytes(), res.getHeaders().get("Content-type").orElse("application/octet-stream"));
apiResp.body = APIModel.Blob.fromBlobResponse(blobResponse);
apiResp.statusCode = res.getStatusCode();
APIModel.HTTPRespDatum datum = APIModel.HTTPRespDatum.create(apiResp);
if (apiResp.statusCode >= 200 && apiResp.statusCode < 400) {
return APIModel.CompletionResult.success(datum);
} else {
throw new ResultException(datum);
}
}).exceptionally(e -> {
if (e.getCause() instanceof ResultException) {
throw (ResultException) e.getCause();
} else {
throw new ResultException(APIModel.ErrorDatum.newError(APIModel.ErrorType.FunctionInvokeFailed, e.getMessage()));
}
});
}, faasExecutor);
}
));
}
private BiFunction<Stage, CompletionStage<List<APIModel.CompletionResult>>, CompletionStage<APIModel.CompletionResult>> chainInvocation(APIModel.Blob closure) {
return (stage, trigger) -> trigger.thenApplyAsync((input) -> {
return completerInvokeClient.invokeStage(functionId, flowId, stage.id, closure, input);
}, faasExecutor);
}
private void addTerminationHook(APIModel.Blob closure) {
this.terminationHooks.add(0, new TerminationHook(newStageId(), closure));
}
private final class Stage {
private final CompletionId id;
private final CompletionStage<APIModel.CompletionResult> outputFuture;
private Stage(CompletionStage<List<APIModel.CompletionResult>> input,
BiFunction<Stage, CompletionStage<List<APIModel.CompletionResult>>, CompletionStage<APIModel.CompletionResult>> invoke) {
this.id = newStageId();
input.whenComplete((in, err) -> activeCount.incrementAndGet());
this.outputFuture = invoke.apply(this, input);
outputFuture.whenComplete((in, err) -> {
activeCount.decrementAndGet();
checkCompletion();
});
}
private CompletionStage<APIModel.CompletionResult> outputFuture() {
return outputFuture;
}
private CompletionId getId() {
return id;
}
private boolean complete(APIModel.BlobDatum value) {
return outputFuture.toCompletableFuture().complete(APIModel.CompletionResult.success(value));
}
private boolean completeExceptionally(APIModel.BlobDatum value) {
return outputFuture.toCompletableFuture().completeExceptionally(new ResultException(value));
}
private Stage addThenApplyStage(APIModel.Blob closure) {
return addStage(new Stage(
outputFuture().thenApply(Collections::singletonList),
chainInvocation(closure)
));
}
private Stage addThenAcceptStage(APIModel.Blob closure) {
return addStage(new Stage(
outputFuture().thenApply(Collections::singletonList),
chainInvocation(closure)
));
}
private Stage addThenRunStage(APIModel.Blob closure) {
return addStage(new Stage(
outputFuture().thenApply((r)->Collections.emptyList()),
chainInvocation(closure)
));
}
private Stage addThenComposeStage(APIModel.Blob closure) {
BiFunction<Stage, CompletionStage<List<APIModel.CompletionResult>>, CompletionStage<APIModel.CompletionResult>> invokefn =
chainInvocation(closure)
.andThen((resultStage) -> resultStage.thenCompose(this::composeResultStage));
return addStage(new Stage(outputFuture().thenApply(Collections::singletonList), invokefn
));
}
private List<APIModel.CompletionResult> resultOrError(APIModel.CompletionResult input, Throwable err) {
if (err != null) {
return Arrays.asList(APIModel.CompletionResult.success(new APIModel.EmptyDatum()), errorToResult(err));
} else {
return Arrays.asList(input, APIModel.CompletionResult.success(new APIModel.EmptyDatum()));
}
}
private APIModel.CompletionResult errorToResult(Throwable err) {
if (err.getCause() instanceof ResultException) {
return ((ResultException) err.getCause()).toResult();
} else {
return APIModel.CompletionResult.failure(APIModel.ErrorDatum.newError(APIModel.ErrorType.UnknownError, "Unexpected error " + err.getMessage()));
}
}
private Stage addWhenCompleteStage(APIModel.Blob closure) {
// This is quite fiddly - because the semantics of whenComplete is.
// We need to construct a new completable future that can be completed only once the whenComplete continuation
// has been finished.
return addStage(new Stage(outputFuture().thenApply(Collections::singletonList), // result or exception
(stage, inputs) -> {
CompletableFuture<APIModel.CompletionResult> cf = new CompletableFuture<>();
inputs.whenComplete((results, err) -> {
// We have ([result], null) or (null, CompletionException(ResultException(datum=exception)))
// In the latter case, resultOrError will take err as-is.
APIModel.CompletionResult result = results != null ? results.get(0) : null;
chainInvocation(closure).apply(stage, CompletableFuture.completedFuture(resultOrError(result, err)))
.whenComplete((r, e2) -> { // Throw away the result of the whenComplete lambda
if (err != null) {
cf.completeExceptionally(err);
} else {
cf.complete(result);
}
});
});
return cf;
}));
}
private Stage addHandleStage(APIModel.Blob closure) {
return addStage(new Stage(outputFuture().handle(this::resultOrError)
, chainInvocation(closure)
));
}
private APIModel.CompletionResult toEmpty(APIModel.CompletionResult res) {
return APIModel.CompletionResult.success(new APIModel.EmptyDatum());
}
private Stage addAcceptEitherStage(Stage otherStage, APIModel.Blob closure) {
return addStage(new Stage(
outputFuture().applyToEither(otherStage.outputFuture, Function.identity())
.thenApply(Collections::singletonList),
chainInvocation(closure)
.andThen(c -> c.thenApply(this::toEmpty))
));
}
private Stage addApplyToEitherStage(Stage otherStage, APIModel.Blob closure) {
return addStage(new Stage(
outputFuture().applyToEither(otherStage.outputFuture, Collections::singletonList),
chainInvocation(closure)
));
}
private Stage addThenAcceptBothStage(Stage otherStage, APIModel.Blob closure) {
return addStage(new Stage(outputFuture()
.thenCombine(otherStage.outputFuture,
(input1, input2) -> Arrays.asList(input1, input2)),
chainInvocation(closure)
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | true |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-testing/src/main/java/com/fnproject/fn/testing/flow/FlowTesting.java | flow-testing/src/main/java/com/fnproject/fn/testing/flow/FlowTesting.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.fnproject.fn.testing.flow;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fnproject.fn.api.Headers;
import com.fnproject.fn.api.InputEvent;
import com.fnproject.fn.api.flow.*;
import com.fnproject.fn.runtime.flow.*;
import com.fnproject.fn.testing.*;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
/**
* FlowTesting allows you to test Fn Flow functions by emulating the Fn Flow completer in a testing environment.
*
* <p>
* * Created on 07/09/2018.
* <p>
* (c) 2018 Oracle Corporation
*/
public class FlowTesting implements FnTestingRuleFeature {
private Map<String, FnFunctionStub> functionStubs = new HashMap<>();
private static InMemCompleter completer = null;
private final FnTestingRule rule;
private static final ObjectMapper objectMapper = new ObjectMapper();
private FlowTesting(FnTestingRule rule) {
this.rule = rule;
rule.addSharedClass(InMemCompleter.CompleterInvokeClient.class);
rule.addSharedClass(BlobStoreClient.class);
rule.addSharedClass(BlobResponse.class);
rule.addSharedClass(CompleterClientFactory.class);
rule.addSharedClass(CompleterClient.class);
rule.addSharedClass(CompletionId.class);
rule.addSharedClass(FlowId.class);
rule.addSharedClass(Flow.FlowState.class);
rule.addSharedClass(CodeLocation.class);
rule.addSharedClass(HttpMethod.class);
rule.addSharedClass(com.fnproject.fn.api.flow.HttpRequest.class);
rule.addSharedClass(com.fnproject.fn.api.flow.HttpResponse.class);
rule.addSharedClass(FlowCompletionException.class);
rule.addSharedClass(FunctionInvocationException.class);
rule.addSharedClass(PlatformException.class);
rule.addFeature(this);
}
/**
* Create a Flow
*
* @param rule
* @return
*/
public static FlowTesting create(FnTestingRule rule) {
Objects.requireNonNull(rule, "rule");
return new FlowTesting(rule);
}
@Override
public void prepareTest(ClassLoader functionClassLoader, PrintStream stderr, String cls, String method) {
InMemCompleter.CompleterInvokeClient client = new TestRuleCompleterInvokeClient(functionClassLoader, stderr, cls, method);
InMemCompleter.FnInvokeClient fnInvokeClient = new TestRuleFnInvokeClient();
// The following must be a static: otherwise the factory (the lambda) will not be serializable.
completer = new InMemCompleter(client, fnInvokeClient);
}
@Override
public void prepareFunctionClassLoader(FnTestingClassLoader cl) {
setCompleterClient(cl, completer);
}
@Override
public void afterTestComplete() {
completer.awaitTermination();
}
private class TestRuleCompleterInvokeClient implements InMemCompleter.CompleterInvokeClient {
private final ClassLoader functionClassLoader;
private final PrintStream oldSystemErr;
private final String cls;
private final String method;
private final Set<FnTestingClassLoader> pool = new HashSet<>();
private TestRuleCompleterInvokeClient(ClassLoader functionClassLoader, PrintStream oldSystemErr, String cls, String method) {
this.functionClassLoader = functionClassLoader;
this.oldSystemErr = oldSystemErr;
this.cls = cls;
this.method = method;
}
@Override
public APIModel.CompletionResult invokeStage(String fnId, FlowId flowId, CompletionId stageId, APIModel.Blob closure, List<APIModel.CompletionResult> input) {
// Construct a new ClassLoader hierarchy with a copy of the statics embedded in the runtime.
// Initialise it appropriately.
FnTestingClassLoader fcl = new FnTestingClassLoader(functionClassLoader, rule.getSharedPrefixes());
setCompleterClient(fcl, completer);
APIModel.InvokeStageRequest request = new APIModel.InvokeStageRequest();
request.stageId = stageId.getId();
request.flowId = flowId.getId();
request.closure = closure;
request.args = input;
String inputBody = null;
try {
inputBody = objectMapper.writeValueAsString(request);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Invalid request");
}
// oldSystemErr.println("Body\n" + new String(inputBody));
InputEvent inputEvent = new FnHttpEventBuilder()
.withBody(inputBody)
.withHeader("Content-Type", "application/json")
.withHeader(FlowContinuationInvoker.FLOW_ID_HEADER, flowId.getId()).buildEvent();
Map<String, String> mutableEnv = new HashMap<>();
PrintStream functionErr = new PrintStream(oldSystemErr);
// Do we want to capture IO from continuations on the main log stream?
// System.setOut(functionErr);
// System.setErr(functionErr);
mutableEnv.putAll(rule.getConfig());
mutableEnv.putAll(rule.getEventEnv());
mutableEnv.put("FN_FORMAT", "http-stream");
List<FnResult> output = new ArrayList<>();
fcl.run(
mutableEnv,
new FnTestingRule.TestCodec(Collections.singletonList(inputEvent), output),
functionErr,
cls + "::" + method);
FnResult out = output.get(0);
APIModel.CompletionResult r;
try {
APIModel.InvokeStageResponse response = objectMapper.readValue(out.getBodyAsBytes(), APIModel.InvokeStageResponse.class);
r = response.result;
} catch (Exception e) {
oldSystemErr.println("Err\n" + e);
e.printStackTrace(oldSystemErr);
r = APIModel.CompletionResult.failure(APIModel.ErrorDatum.newError(APIModel.ErrorType.UnknownError, "Error reading fn Response:" + e.getMessage()));
}
if (!r.successful) {
throw new ResultException(r.result);
}
return r;
}
}
private void setCompleterClient(FnTestingClassLoader cl, CompleterClientFactory completerClientFactory) {
try {
Class<?> completerGlobals = cl.loadClass(FlowRuntimeGlobals.class.getName());
completerGlobals.getMethod("setCompleterClientFactory", CompleterClientFactory.class).invoke(completerGlobals, completerClientFactory);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | IllegalArgumentException e) {
throw new RuntimeException("Something broke in the reflective classloader", e);
}
}
private interface FnFunctionStub {
com.fnproject.fn.api.flow.HttpResponse stubFunction(HttpMethod method, Headers headers, byte[] body);
}
public FnFunctionStubBuilder<FlowTesting> givenFn(String id) {
return new FnFunctionStubBuilder<FlowTesting>() {
@Override
public FlowTesting withResult(byte[] result) {
return withAction((body) -> result);
}
@Override
public FlowTesting withFunctionError() {
return withAction((body) -> {
throw new FunctionError("simulated by testing platform");
});
}
@Override
public FlowTesting withPlatformError() {
return withAction((body) -> {
throw new PlatformError("simulated by testing platform");
});
}
@Override
public FlowTesting withAction(ExternalFunctionAction f) {
functionStubs.put(id, (HttpMethod method, Headers headers, byte[] body) -> {
try {
return new DefaultHttpResponse(200, Headers.emptyHeaders(), f.apply(body));
} catch (FunctionError functionError) {
return new DefaultHttpResponse(500, Headers.emptyHeaders(), functionError.getMessage().getBytes());
} catch (PlatformError platformError) {
throw new RuntimeException("Platform Error");
}
});
return FlowTesting.this;
}
};
}
private class TestRuleFnInvokeClient implements InMemCompleter.FnInvokeClient {
@Override
public CompletableFuture<HttpResponse> invokeFunction(String fnId, HttpMethod method, Headers headers, byte[] data) {
FnFunctionStub stub = functionStubs.computeIfAbsent(fnId, (k) -> {
throw new IllegalStateException("Function was invoked that had no definition: " + k + " defined functions are " + String.join(",",functionStubs.keySet()));
});
try {
return CompletableFuture.completedFuture(stub.stubFunction(method, headers, data));
} catch (Exception e) {
CompletableFuture<com.fnproject.fn.api.flow.HttpResponse> respFuture = new CompletableFuture<>();
respFuture.completeExceptionally(e);
return respFuture;
}
}
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-testing/src/main/java/com/fnproject/fn/testing/flow/FnFunctionStubBuilder.java | flow-testing/src/main/java/com/fnproject/fn/testing/flow/FnFunctionStubBuilder.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.fnproject.fn.testing.flow;
import com.fnproject.fn.testing.FunctionError;
import com.fnproject.fn.testing.PlatformError;
/**
* A builder for constructing stub external functions
*/
public interface FnFunctionStubBuilder<T> {
/**
* Consume the builder and stub the function to return the provided byte array
*
* @param result A byte array returned by the function
* @return The original testing rule (usually {@link FlowTesting}. The builder is consumed.
*/
T withResult(byte[] result);
/**
* Consume the builder and stub the function to throw an error when it is invoked: this simulates a failure of the
* called function, e.g. if the external function threw an exception.
*
* @return The original testing rule (usually {@link FlowTesting}. The builder is consumed.
*/
T withFunctionError();
/**
* Consume the builder and stub the function to throw a platform error, this simulates a failure of the Fn Flow
* completions platform, and not any error of the user code.
*
* @return The original testing rule (usually {@link FlowTesting}. The builder is consumed.
*/
T withPlatformError();
/**
* Consume the builder and stub the function to perform some action; the action is an implementation of the
* functional interface {@link ExternalFunctionAction}, this gives finer grained control over the behaviour of the
* stub compared to {@link #withResult(byte[])}, {@link #withFunctionError()} and {@link #withPlatformError()}.
* <p>
* Note that there are no thread-safety guarantees on any external state modified in the provided action. If shared
* external state is accessed, a synchronization mechanism should be used.
*
* @param f an action to apply when this function is invoked
* @return The original testing rule (usually {@link FlowTesting}. The builder is consumed.
*/
T withAction(ExternalFunctionAction f);
/**
* Represents the calling interface of an external function. It takes a byte[] as input,
* and produces a byte[] as output possibly throwing a {@link FunctionError} to simulate user code failure,
* or a {@link PlatformError} to simulate a failure of the Fn Flow completions platform.
*/
interface ExternalFunctionAction {
/**
* Run the external function action
*
* @param arg the body of the function invocation as a byte array
* @return the response to the function invocation as a byte array
* @throws FunctionError if the action should simulate a function failure
* @throws PlatformError if the action should simulate a platform failure
*/
byte[] apply(byte[] arg) throws FunctionError, PlatformError;
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
fnproject/fdk-java | https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-testing/src/main/java/com/fnproject/fn/testing/flow/ResultException.java | flow-testing/src/main/java/com/fnproject/fn/testing/flow/ResultException.java | /*
* Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
*
* 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 com.fnproject.fn.testing.flow;
import com.fnproject.fn.runtime.flow.APIModel;
class ResultException extends RuntimeException {
private final APIModel.Datum datum;
ResultException(APIModel.Datum datum) {
this.datum = datum;
}
APIModel.CompletionResult toResult() {
return APIModel.CompletionResult.failure(datum);
}
}
| java | Apache-2.0 | 6275fbbe73c167c221e8be5ab4b838c68966ea5e | 2026-01-05T02:37:41.914759Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/outros/001-ConversorDecimalBinario/src/conversor/decimal/binario/Conversor.java | outros/001-ConversorDecimalBinario/src/conversor/decimal/binario/Conversor.java | package conversor.decimal.binario;
import java.util.Scanner;
public class Conversor {
// Veja um conversor bacana em https://basesnumericas.pages.dev/conversor
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Digite um numero: ");
long numero = input.nextLong();
System.out.printf("%d (base 10) = %s (base 2)%n", numero, converter(numero));
input.close();
}
public static String converter(long numero){
return Long.toBinaryString(numero);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/outros/002-ConversorBinarioDecimal/src/conversor/binario/decimal/Conversor.java | outros/002-ConversorBinarioDecimal/src/conversor/binario/decimal/Conversor.java | package conversor.binario.decimal;
import java.util.Scanner;
public class Conversor {
// Veja um conversor bacana em https://basesnumericas.pages.dev/conversor
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Digite um numero: ");
String numero = input.nextLine();
System.out.printf("%s (base 2) = %d (base 10)%n", numero, converter(numero));
input.close();
}
public static long converter(String numero) {
try {
return Long.parseLong(numero, 2);
} catch (NumberFormatException e) {
System.out.println("Erro: o número informado não é binário!");
return -1;
}
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/044-CompararStreamParallel/src/compararstream/Comparar.java | nivel2/044-CompararStreamParallel/src/compararstream/Comparar.java | package compararstream;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.function.Supplier;
public class Comparar {
private static long measureMillis(Supplier<Long> supplier) {
long start = System.nanoTime();
long result = supplier.get(); // garante que o cálculo não seja removido
long end = System.nanoTime();
System.out.println("Resultado (soma): " + result);
return (end - start) / 1_000_000; // retorna em ms
}
public static void main(String[] args) {
final int N = 1_000_000;
System.out.println("Preparando dados: somar 1.." + N);
// Lista com boxing (List<Integer>) — simula uso comum de coleções
List<Integer> numerosBoxed = IntStream.rangeClosed(1, N)
.boxed()
.collect(Collectors.toList());
// Warm-up (ajuda o JIT a otimizar antes das medições)
System.out.println("Warm-up...");
for (int i = 0; i < 3; i++) {
LongStream.rangeClosed(1, N).sum();
LongStream.rangeClosed(1, N).parallel().sum();
numerosBoxed.stream().mapToLong(Integer::longValue).sum();
numerosBoxed.parallelStream().mapToLong(Integer::longValue).sum();
}
final int runs = 5;
long totalBoxedSeq = 0, totalBoxedPar = 0, totalPrimSeq = 0, totalPrimPar = 0;
System.out.println("Executando medições (" + runs + " runs)...");
for (int i = 1; i <= runs; i++) {
System.out.println("\n--- Run " + i + " ---");
long tBoxedSeq = measureMillis(() -> numerosBoxed.stream()
.mapToLong(Integer::longValue).sum());
long tBoxedPar = measureMillis(() -> numerosBoxed.parallelStream()
.mapToLong(Integer::longValue).sum());
long tPrimSeq = measureMillis(() -> LongStream.rangeClosed(1, N).sum());
long tPrimPar = measureMillis(() -> LongStream.rangeClosed(1, N).parallel().sum());
System.out.printf("Tempos (ms) -> Boxed seq: %d, Boxed par: %d, Prim seq: %d, Prim par: %d%n",
tBoxedSeq, tBoxedPar, tPrimSeq, tPrimPar);
totalBoxedSeq += tBoxedSeq;
totalBoxedPar += tBoxedPar;
totalPrimSeq += tPrimSeq;
totalPrimPar += tPrimPar;
}
System.out.println("\n=== MÉDIAS (ms) ===");
System.out.printf("Boxed stream (List<Integer>.stream()): %.2f ms%n", totalBoxedSeq / (double) runs);
System.out.printf("Boxed parallelStream (List<Integer>.parallelStream()): %.2f ms%n", totalBoxedPar / (double) runs);
System.out.printf("Primitive LongStream (sequential): %.2f ms%n", totalPrimSeq / (double) runs);
System.out.printf("Primitive LongStream (parallel): %.2f ms%n", totalPrimPar / (double) runs);
System.out.println("\nObservações:");
System.out.println("- Resultados variam conforme número de núcleos, carga do sistema e JVM.");
System.out.println("- Boxing (List<Integer>) adiciona overhead; comparações com LongStream são mais justas.");
System.out.println("- Para benchmarking sério, use JMH (Java Microbenchmark Harness).");
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/021-MaximoDivisorComum/src/maximo/divisor/comum/MaximoDivisorComum.java | nivel2/021-MaximoDivisorComum/src/maximo/divisor/comum/MaximoDivisorComum.java | package maximo.divisor.comum;
import java.util.Scanner;
public class MaximoDivisorComum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Digite o primeiro número: ");
int a = scanner.nextInt();
System.out.print("Digite o segundo número: ");
int b = scanner.nextInt();
int maximoDivisorComum = calcularMDC(a, b);
System.out.println("O MDC de " + a + " e " + b + " é: " + maximoDivisorComum);
}
public static int calcularMDC(int a, int b) {
// Caso base: quando o segundo número é 0, retornamos o primeiro
if (b == 0) {
return a;
}
// Chamada recursiva: MDC(b, a % b)
return calcularMDC(b, a % b);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/014-ElementosRepetidos/src/elementos/repetidos/ElementosRepetidos.java | nivel2/014-ElementosRepetidos/src/elementos/repetidos/ElementosRepetidos.java | package elementos.repetidos;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
public class ElementosRepetidos {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Digite os números separados por espaço:");
String entrada = scanner.nextLine();
// Quebra a entrada por espaços e converte para inteiros
String[] partes = entrada.split(" ");
Set<Integer> unicos = new LinkedHashSet<>();
for (String parte : partes) {
try{
int numero = Integer.parseInt(parte);
unicos.add(numero); // adiciona ao LinkedHashSet (sem duplicados)
} catch (NumberFormatException e) {
System.out.println("Ignorado valor inválido: " + parte);
}
}
System.out.println("Sem duplicados:");
for (int num : unicos) {
System.out.print(num + " ");
}
scanner.close();
}
}
/**
* | Componente | Função |
* | --------------- | -------------------------------------------------------------------- |
* | `LinkedHashSet` | Armazena elementos únicos mantendo a ordem original |
* | `for-each` loop | Adiciona cada elemento do array no `Set` |
* | `Set<Integer>` | Usado no lugar de `List` para eliminar os duplicados automaticamente |
*/ | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/002-Fibonacci/src/fibonacci/Main.java | nivel2/002-Fibonacci/src/fibonacci/Main.java | package fibonacci;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try{
System.out.println("=== Sequência de Fibonacci ====");
System.out.print("Digite o número de termos da sequência de Fibonacci: ");
int n = scanner.nextInt();
if (n <= 0) {
System.out.println("Por favor, digite um número positivo.");
return;
}
System.out.println("***** RESULTADO *****");
System.out.println("Sequência de Fibonacci com " + n + " termos:");
int primeiro = 0;
int segundo = 1;
for (int i = 0; i < n; i++) { // Garante imprimir n termos da sequência
System.out.print(primeiro + " ");
int proximo = primeiro + segundo; // Soma dos dois anteriores
primeiro = segundo;
segundo = proximo;
}
} catch (Exception e) {
System.out.println("Erro: digite um número inteiro válido.");
} finally {
scanner.close();
}
}
} | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/016-OrdenarArrayDeInteiros/src/ordenar/inteiros/OrdenarArrayDeInteiros.java | nivel2/016-OrdenarArrayDeInteiros/src/ordenar/inteiros/OrdenarArrayDeInteiros.java | package ordenar.inteiros;
import java.util.Scanner;
public class OrdenarArrayDeInteiros {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Digite números inteiros separados por espaço:");
String[] entrada = scanner.nextLine().split(" ");
int[] numeros = new int[entrada.length];
// Convertendo os valores para inteiros
for (int i = 0; i < entrada.length; i++) {
numeros[i] = Integer.parseInt(entrada[i]);
}
// Algoritmo Bubble Sort
for (int i = 0; i < numeros.length - 1; i++) {
for (int j = 0; j < numeros.length - 1 - i; j++) {
if (numeros[j] > numeros[j + 1]) {
// Trocar os elementos
int temp = numeros[j];
numeros[j] = numeros[j + 1];
numeros[j + 1] = temp;
}
}
}
/*
// Resolução mais simples com Arrays.sort() ao invés do Algoritmo Bubble Sort
Arrays.sort(numeros);
*/
// Exibindo o array ordenado
System.out.println("Array ordenado:");
for (int num : numeros) {
System.out.print(num + " ");
}
scanner.close();
}
}
/**
* Leitura da entrada do usuário via Scanner.
* Conversão para int[].
* Ordenação manual usando o algoritmo Bubble Sort.
* Exibição dos números já ordenados.
*/
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/027-NormalizarTexto/src/normalizar/texto/NormalizarTexto.java | nivel2/027-NormalizarTexto/src/normalizar/texto/NormalizarTexto.java | package normalizar.texto;
import java.text.Normalizer;
import java.util.Scanner;
public class NormalizarTexto {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Informe um texto que deseja normalizar: ");
String textoDigitado = scanner.nextLine();
String semAcentos = Normalizer.normalize(textoDigitado, Normalizer.Form.NFD)
.replaceAll("\\p{M}", ""); // O regex \\p{M} remove todos os diacríticos (acentos, cedilhas etc.).
String normalizado = semAcentos.toLowerCase();
System.out.println("\nTexto normalizado:");
System.out.println(normalizado);
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/005-FrequenciaCaracteres/src/frequencia/caracteres/FrequenciaCaracteres.java | nivel2/005-FrequenciaCaracteres/src/frequencia/caracteres/FrequenciaCaracteres.java | package frequencia.caracteres;
import java.util.*;
public class FrequenciaCaracteres {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Digite uma palavra ou frase: ");
String texto = scanner.nextLine().toLowerCase(); // tudo minúsculo
Map<Character, Integer> frequencia = new HashMap<>();
for (char c : texto.toCharArray()) {
if (c == ' ') continue; // ignora espaços
// Se já existe no mapa, soma +1
if (frequencia.containsKey(c)) {
frequencia.put(c, frequencia.get(c) + 1);
} else {
frequencia.put(c, 1); // primeira vez
}
}
System.out.println("\nFrequência de caracteres:");
for (Map.Entry<Character, Integer> entry : frequencia.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
scanner.close();
}
}
/*
| Parte | Explicação |
| ------------------------- | ---------------------------------------------------------- |
| `.toCharArray()` | Transforma a `String` em um array de caracteres (`char[]`) |
| `Map<Character, Integer>` | Associa cada caractere a um contador (frequência) |
| `containsKey(c)` | Verifica se o caractere já está no mapa |
| `put(c, valor)` | Insere ou atualiza o valor da chave (caractere) |
| `toLowerCase()` | Evita contar ‘A’ e ‘a’ como diferentes |
*/ | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/031-GeradorSenha/src/gerador/senha/GeradorSenha.java | nivel2/031-GeradorSenha/src/gerador/senha/GeradorSenha.java | package gerador.senha;
import java.util.Random;
import java.util.Scanner;
public class GeradorSenha {
private static final Random random = new Random();
private static final String LETRAS_MINUSCULAS = "abcdefghijklmnopqrstuvwxyz";
private static final String LETRAS_MAIUSCULAS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String DIGITOS = "0123456789";
private static final String SIMBOLOS = "!@#$%^&*()-_=+[]{}\\\\|;:'\\\",.<>?/";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Deseja uma senha de quantos dígitos? ");
int tamanho = input.nextInt();
System.out.println("Sua senha: " + gerarSenha(tamanho));
input.close();
}
public static String gerarSenha(int tamanho) {
StringBuilder senha = new StringBuilder();
for (int i = 0; i < tamanho; i++) {
int escolha = random.nextInt(4); // agora vai de case 0 até 3
switch (escolha) {
case 0 -> senha.append(LETRAS_MAIUSCULAS.charAt(random.nextInt(LETRAS_MAIUSCULAS.length())));
case 1 -> senha.append(LETRAS_MINUSCULAS.charAt(random.nextInt(LETRAS_MINUSCULAS.length())));
case 2 -> senha.append(SIMBOLOS.charAt(random.nextInt(SIMBOLOS.length())));
case 3 -> senha.append(DIGITOS.charAt(random.nextInt(DIGITOS.length())));
}
}
return senha.toString();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/015-SomarPositivos/src/somar/positivos/SomarPositivos.java | nivel2/015-SomarPositivos/src/somar/positivos/SomarPositivos.java | package somar.positivos;
import java.util.Scanner;
public class SomarPositivos {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Digite números separados por espaço: ");
String entrada = scanner.nextLine();
String[] partes = entrada.split(" ");
int soma = 0;
for (String parte : partes) {
try {
int numero = Integer.parseInt(parte);
if (numero > 0) {
soma += numero;
}
} catch (NumberFormatException e) {
System.out.println("Ignorado valor inválido: " + parte);
}
}
System.out.println("Soma dos números positivos: " + soma);
scanner.close();
}
}
/**
* split(" ") → separa a entrada do usuário.
* Integer.parseInt() → converte cada string para número.
* if (numero > 0) → garante que só positivos sejam somados.
* try-catch → protege contra valores inválidos (ex: letras).
*/ | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/018-ClassificacaoTriangulos/src/classificacao/triangulos/ClassificacaoTriangulos.java | nivel2/018-ClassificacaoTriangulos/src/classificacao/triangulos/ClassificacaoTriangulos.java | /* Crie uma função que recebe os comprimentos dos três lados de um triângulo
/* e retorne sua classificação quanto ao tamanho de seus lados.
*/
package classificacao.triangulos;
import java.util.Scanner;
public class ClassificacaoTriangulos {
public static void definirTipoDeTriangulo(double l1, double l2, double l3) {
// Verificação de existência do triângulo
if (l1 + l2 <= l3 || l1 + l3 <= l2 || l2 + l3 <= l1) {
System.out.println("ERRO! Impossível formar um triângulo.");
return;
}
// Classificação
if (l1 == l2 && l2 == l3) {
System.out.println("Triângulo Equilátero formado!");
} else if (l1 == l2 || l2 == l3 || l1 == l3) {
System.out.println("Triângulo Isósceles formado!");
} else {
System.out.println("Triângulo Escaleno formado!");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Informe o primeiro lado: ");
double l1 = scanner.nextDouble();
System.out.print("Informe o segundo lado: ");
double l2 = scanner.nextDouble();
System.out.print("Informe o terceiro lado: ");
double l3 = scanner.nextDouble();
definirTipoDeTriangulo(l1, l2, l3);
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/007-Tabuada/src/tabuada/Tabuada.java | nivel2/007-Tabuada/src/tabuada/Tabuada.java | package tabuada;
import java.util.Scanner;
public class Tabuada {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("==== INICIALIZANDO PROGRAMA ====");
System.out.print("Digite um número para ver a tabuada: ");
int numero = scanner.nextInt();
System.out.println("\nTabuada de " + numero + ":");
for (int i = 1; i <= 10; i++) {
int resultado = numero * i;
System.out.println(numero + " x " + i + " = " + resultado);
}
System.out.println("=====================");
} catch (Exception e) {
System.out.println("[ERRO!]Informe um número inteiro válido!");
} finally {
scanner.close();
}
}
} | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/026-MediaPonderada/src/media/ponderada/MediaPonderada.java | nivel2/026-MediaPonderada/src/media/ponderada/MediaPonderada.java | package media.ponderada;
import java.util.Scanner;
public class MediaPonderada {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Informe a quantidade de notas: ");
int qtdNotas = scanner.nextInt();
double somaNotasPesos = 0;
double somaPesos = 0;
for (int i = 1; i <= qtdNotas; i++) {
System.out.print("Digite a nota " + i + ": ");
double nota = scanner.nextDouble();
System.out.print("Digite o peso: ");
double peso = scanner.nextDouble();
somaNotasPesos += nota * peso;
somaPesos += peso;
}
if (somaPesos > 0) {
double mediaPonderada = somaNotasPesos / somaPesos;
System.out.printf("Média ponderada = %.2f%n", mediaPonderada);
} else {
System.out.println("Erro: a soma dos pesos não pode ser zero.");
}
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/043-ReduceProdutoInteiros/src/reduceproduto/ReduceProdutoInteiros.java | nivel2/043-ReduceProdutoInteiros/src/reduceproduto/ReduceProdutoInteiros.java | package reduceproduto;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class ReduceProdutoInteiros {
public static void main(String[] args) {
List<Integer> numeros = Arrays.asList(1,2,3,4,5);
// 1) Usando reduce com identidade
int produtoComIdentidade = numeros.stream()
.reduce(1, (a,b) -> a * b);
System.out.println("Produto (com identidade): " + produtoComIdentidade);
// 2) Usando reduce sem identidade (retorna Optional)
Optional<Integer> produtoOpcional = numeros.stream()
.reduce((a,b) -> a * b);
produtoOpcional.ifPresentOrElse(
p -> System.out.println("Produto (Optional): " + p),
() -> System.out.println("Lista vazia — sem produto definido")
);
// 3) Exemplo com lista vazia (mostra comportamento com identidade)
List<Integer> vazia = Collections.emptyList();
int produtoVazia = vazia.stream()
.reduce(1, (a,b) -> a * b);
System.out.println("Produto (lista vazia, com identidade): " + produtoVazia);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/024-MatrizQuadradaSimetrica/src/matriz/quadrada/simetrica/MatrizQuadradaSimetrica.java | nivel2/024-MatrizQuadradaSimetrica/src/matriz/quadrada/simetrica/MatrizQuadradaSimetrica.java | package matriz.quadrada.simetrica;
import java.util.Scanner;
public class MatrizQuadradaSimetrica {
/* Posição dos elementos em 3x3
[00] [01] [02]
[10] [11] [12]
[20] [21] [22]
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("==== Verificador de Matriz Quadrada Simétrica ====\n");
// 1. Perguntar o tamanho da matriz
System.out.print("Informe o tamanho da matriz (n x n): ");
int n = scanner.nextInt();
int[][] matriz = new int[n][n];
// 2. Ler os elementos da matriz
System.out.println("\nDigite os elementos da matriz: ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("Elemento [%d][%d]: ", i, j);
matriz[i][j] = scanner.nextInt();
}
}
// 3. Mostra a matriz digitada
System.out.println("\nMatriz informada:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matriz[i][j] + "\t");
}
System.out.println();
}
// 4. Verificar se é simétrica
boolean simetrica = true;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) { // só compara acima da diagonal
if (matriz[i][j] != matriz[j][i]) {
simetrica = false;
break; // para e sai do loop de comparação
}
}
if (!simetrica) break;
}
// 5. Mostrar resultado
System.out.println("\n==== Resultado ====");
if (simetrica) {
System.out.println("A matriz é SIMÉTRICA!");
} else {
System.out.println("A matriz NÃO é simétrica!");
}
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/046-MinMaxNomesPorTamanho/src/minmaxnomes/MinMaxNomesPorTamanho.java | nivel2/046-MinMaxNomesPorTamanho/src/minmaxnomes/MinMaxNomesPorTamanho.java | package minmaxnomes;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
public class MinMaxNomesPorTamanho {
public static void main(String[] args) {
List<String> nomes = Arrays.asList("Ana", "Beatriz", "Carlos", "João", "Felipe", "Z");
// Comparator: primeiro por tamanho, depois por ordem lexicográfica (para desempate)
Comparator<String> lengthThenLex = Comparator
.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder());
Optional<String> menor = nomes.stream().min(lengthThenLex);
Optional<String> maior = nomes.stream().max(lengthThenLex);
System.out.println("Lista: " + nomes);
menor.ifPresentOrElse(
s -> System.out.println("Menor: " + s + " (tamanho= " + s.length() + ")"),
() -> System.out.println("Lista vazia — nenhum menor.")
);
maior.ifPresentOrElse(
s -> System.out.println("Maior: " + s + " (tamanho= " + s.length() + ")"),
() -> System.out.println("Lista vazia — nenhum maior.")
);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/037-LambdaOrdenarListaStrings/src/ordenar/strings/LambdaOrdenarListaStrings.java | nivel2/037-LambdaOrdenarListaStrings/src/ordenar/strings/LambdaOrdenarListaStrings.java | package ordenar.strings;
import java.util.Arrays;
import java.util.List;
public class LambdaOrdenarListaStrings {
public static void main(String[] args) {
List<String> listaDeCompras = Arrays.asList("Feijão", "Arroz", "Macarrão", "Alface", "Tomate", "Vinho", "Água", "Batata");
listaDeCompras.sort((a , b) -> a.compareTo(b));
System.out.println("Lista de Compras Ordenada: " + listaDeCompras);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/049-TakeWhileMenores50/src/takewhile/TakeWhileMenores50.java | nivel2/049-TakeWhileMenores50/src/takewhile/TakeWhileMenores50.java | package takewhile;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class TakeWhileMenores50 {
public static void main(String[] args) {
// Exemplo 1: primeiros elementos menores que 50, depois aparecendo >=50
List<Integer> lista1 = Arrays.asList(10, 20, 30, 49, 50, 40, 25);
// Exemplo 2: há um elemento >=50 no meio (takeWhile para antes dele)
List<Integer> lista2 = Arrays.asList(5, 15, 60, 10, 20, 30);
// Exemplo 3: todos menores que 50
List<Integer> lista3 = Arrays.asList(1, 2, 3);
// Usando takeWhile (em cada caso)
List<Integer> resultado1 = lista1.stream()
.takeWhile(n -> n < 50)
.collect(Collectors.toList());
List<Integer> resultado2 = lista2.stream()
.takeWhile(n -> n < 50)
.collect(Collectors.toList());
List<Integer> resultado3 = lista3.stream()
.takeWhile(n -> n < 50)
.collect(Collectors.toList());
System.out.println("Lista1: " + lista1);
System.out.println("takeWhile (<50) -> " + resultado1);
// Observação: 50 interrompe a sequência, então 40 e 25 depois não são incluídos
System.out.println("\nLista2: " + lista2);
System.out.println("takeWhile (<50) -> " + resultado2);
// 60 interrompe; elementos após 60 (10,20,30) não são considerados
System.out.println("\nLista3: " + lista3);
System.out.println("takeWhile (<50) -> " + resultado3);
// Nesse caso melhor opção é usar .filter() ou ordenar a lista (Collections.sort(lista1);) e depois usar o takeWhile()
System.out.println("\nComparação (filter):");
System.out.println("lista1.filter(<50) -> " + lista1.stream().filter(n -> n < 50).collect(Collectors.toList()));
System.out.println("lista2.filter(<50) -> " + lista2.stream().filter(n -> n < 50).collect(Collectors.toList()));
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/011-CaracteresUnicos/src/caracteres/unicos/CaracteresUnicos.java | nivel2/011-CaracteresUnicos/src/caracteres/unicos/CaracteresUnicos.java | package caracteres.unicos;
import java.util.HashSet;
import java.util.Scanner;
public class CaracteresUnicos {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("==== TESTANDO CARACTERES ====");
System.out.print("Informe uma palavra para o teste: ");
String entrada = scanner.nextLine();
boolean resultado = todosCaracteresUnicos(entrada);
System.out.println("Todos os caracteres de [" + entrada + "] são únicos? " + resultado);
} catch (Exception e) {
System.out.println("[ERRO!] Informe um caractere válido!");
} finally {
scanner.close();
}
}
public static boolean todosCaracteresUnicos(String str) {
HashSet<Character> caracteresVistos = new HashSet<>();
for (char c : str.toCharArray()) {
if (caracteresVistos.contains(c)) {
return false;
}
caracteresVistos.add(c);
}
return true;
}
}
/*
- Scanner: Lê a entrada do usuário.
- HashSet<Character>: Armazena os caracteres já vistos (sem repetições).
- for (char c : str.toCharArray()): Converte a string em um array de caracteres e percorre um por um.
Verificação:
- Se o caractere já estiver no HashSet, então já apareceu antes → retorna false.
- Se não, adiciona o caractere ao HashSet.
- Se nenhum caractere for repetido, retorna true.
str.toCharArray()
- A expressão str.toCharArray() em Java transforma uma String em um vetor de caracteres (char[])
- Facilita operações como:
-> Percorrer cada caractere com um for
-> Comparar caracteres individualmente
-> Armazenar ou processar cada letra separadamente
*/ | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/038-LambdaContaLetraInicial/src/conta/letras/ContaLetraInicial.java | nivel2/038-LambdaContaLetraInicial/src/conta/letras/ContaLetraInicial.java | package conta.letras;
import java.util.Arrays;
import java.util.List;
public class ContaLetraInicial {
public static void main(String[] args) {
List<String> palavras = Arrays.asList("Amor", "Sol", "Avião", "Lua", "Amizade", "Estrela");
long quantidade = palavras.stream()
.filter(p -> p.startsWith("A"))
.count();
System.out.println("Quantidade de palavras que começam com 'A': " + quantidade);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/006-ParOuImpar/src/par/ou/impar/ParOuImpar.java | nivel2/006-ParOuImpar/src/par/ou/impar/ParOuImpar.java | package par.ou.impar;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ParOuImpar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> pares = new ArrayList<>();
List<Integer> impares = new ArrayList<>();
try {
System.out.println("==== PAR OU ÍMPAR ====");
System.out.print("Quantos números deseja digitar? ");
int quantidade = scanner.nextInt();
for (int i = 1; i <= quantidade; i++) {
System.out.print("Digite o " + i + "º número: ");
int n = scanner.nextInt();
if (n % 2 == 0) {
pares.add(n);
} else {
impares.add(n);
}
}
// Exibição dos resultados
System.out.println("\nRESULTADO:");
System.out.println("Números pares: " + pares);
System.out.println("Números ímpares: " + impares);
} catch (Exception e) {
System.out.println("[ERRO!] Informe um número inteiro válido!");
} finally {
scanner.close();
}
}
}
/*
| Modificação | Função |
| --------------------------------------- | -------------------------------------------- |
| `List<Integer> pares` | Guarda os números pares digitados |
| `List<Integer> impares` | Guarda os números ímpares digitados |
| `for (int i = 1; i <= quantidade; i++)` | Permite o usuário digitar múltiplos números |
| `for (int i = 1; ...)` | Cria a variável i e começa em 1. Contador |
| `for (...; i <= quantidade; ...)` | Enquanto i <= quantidade, o loop continua. |
| `for (...; ...; i++)` | Após cada repetição, incrementa i em 1. i = i + 1.|
| `pares.add(...)` / `impares.add(...)` | Adiciona cada número na lista correspondente |
*/ | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/009-ContadorDePalavras/src/contador/de/palavras/ContadorDePalavras.java | nivel2/009-ContadorDePalavras/src/contador/de/palavras/ContadorDePalavras.java | package contador.de.palavras;
import java.util.Scanner;
public class ContadorDePalavras {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Digite uma frase: ");
String frase = scanner.nextLine();
String[] palavras = frase.trim().split("\\s+");
int contador = (frase.trim().isEmpty()) ? 0 : palavras.length;
System.out.println("Quantidade de palavras: " + contador);
} catch (Exception e) {
System.out.println("[ERRO!] Digite palavras para formar uma frase!");
} finally {
scanner.close();
}
}
}
/*
`trim()` remove espaços do começo e fim da string.
`split("\\s+")` divide a frase em palavras usando um ou mais espaços como separador (\\s+ significa “um ou mais espaços”).
A verificação `frase.trim().isEmpty()` evita contar uma palavra se o usuário só digitou espaços.
*/ | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/034-LambdaStringParaMaiusculas/src/string/para/maiusculas/LambdaStringParaMaiusculas.java | nivel2/034-LambdaStringParaMaiusculas/src/string/para/maiusculas/LambdaStringParaMaiusculas.java | package string.para.maiusculas;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class LambdaStringParaMaiusculas {
public static void main(String[] args) {
List<String> nomes = Arrays.asList("ana", "gui", "lia", "bia", "carlos", "josé");
nomes.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
List<String> listaNomesMaiusculos = nomes.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println("\nLista final em maiúsculas: " + listaNomesMaiusculos);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/048-SkipLimitInteiros/src/skiplimit/SkipLimitInteiros.java | nivel2/048-SkipLimitInteiros/src/skiplimit/SkipLimitInteiros.java | package skiplimit;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SkipLimitInteiros {
public static void main(String[] args) {
// Exemplo: números de 1 a 30
List<Integer> numeros = IntStream.rangeClosed(1,30)
.boxed()
.collect(Collectors.toList());
// Pular os 5 primeiros e pegar os 10 seguintes
List<Integer> resultado = numeros.stream()
.skip(5) // pula 1,2,3,4,5
.limit(10) // pega os próximos 10 (6..15)
.collect(Collectors.toList());
System.out.println("Lista original: " + numeros);
System.out.println("Resultado (skip 5, limit 10): " + resultado);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/033-LambdaSomentePares/src/somente/pares/LambdaSomentePares.java | nivel2/033-LambdaSomentePares/src/somente/pares/LambdaSomentePares.java | package somente.pares;
import java.util.Arrays;
import java.util.List;
public class LambdaSomentePares {
public static void main(String[] args) {
List<Integer> listaDeInteiros = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
listaDeInteiros.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/022-MinimoMultiploComum/src/minimo/multiplo/comum/MinimoMultiploComum.java | nivel2/022-MinimoMultiploComum/src/minimo/multiplo/comum/MinimoMultiploComum.java | package minimo.multiplo.comum;
import java.util.Scanner;
public class MinimoMultiploComum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Digite o primeiro número: ");
int a = scanner.nextInt();
System.out.print("Digite o segundo número: ");
int b = scanner.nextInt();
int maximoDivisorComum = calcularMDC(a, b);
int minimoMultiploComum = (a * b) / maximoDivisorComum;
System.out.println("MMC de " + a + " e " + b + " é: " + minimoMultiploComum);
}
// Método recursivo do MDC
public static int calcularMDC(int a, int b) {
if (b == 0) return a;
return calcularMDC(b, a % b);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/042-FiltrarStringsMais5Caracteres/src/filtrarstrings/FiltrarStringsMais5Caracteres.java | nivel2/042-FiltrarStringsMais5Caracteres/src/filtrarstrings/FiltrarStringsMais5Caracteres.java | package filtrarstrings;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FiltrarStringsMais5Caracteres {
public static void main(String[] args) {
List<String> palavras = Arrays.asList("exemplo", "casa", "aviao", "programacao", "java", "stream", "filtro");
List<String> resultado = palavras.stream()
.filter(s -> s.trim().length() > 5)
.collect(Collectors.toList());
System.out.printf("Lista original: " + palavras);
System.out.printf("\nLista com mais de 5 caracteres: " + resultado);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/035-LambdaSomarInteiros/src/somar/inteiros/LambdaSomarInteiros.java | nivel2/035-LambdaSomarInteiros/src/somar/inteiros/LambdaSomarInteiros.java | package somar.inteiros;
import java.util.Arrays;
import java.util.List;
public class LambdaSomarInteiros {
public static void main(String[] args) {
List<Integer> listaDeInteiros = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
System.out.println(listaDeInteiros.stream()
.reduce(0, (a,b) -> a + b));
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/008-VerificarAnagramas/src/verificar/anagramas/VerificarAnagramas.java | nivel2/008-VerificarAnagramas/src/verificar/anagramas/VerificarAnagramas.java | package verificar.anagramas;
import java.util.Arrays;
import java.util.Scanner;
public class VerificarAnagramas {
public static boolean ehAnagrama (String str1, String str2) {
if (str1 == null || str2 == null || str1.length() != str2.length()) {
return false;
}
char[] charArray1 = str1.toLowerCase().toCharArray();
char[] charArray2 = str2.toLowerCase().toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
return Arrays.equals(charArray1, charArray2);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("==== ANAGRAMA? ==== ");
System.out.print("Primeira palavra: ");
String palavra1 = scanner.nextLine();
System.out.print("Segunda palavra: ");
String palavra2 = scanner.nextLine();
System.out.println(palavra1 + " e " + palavra2 + " são anagramas? " + ehAnagrama(palavra1, palavra2));
} catch (Exception e) {
System.out.println("[ERRO!] Informe uma palavra válida!");
} finally {
scanner.close();
}
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/013-ValidadorDeSenha/src/validador/de/senha/ValidadorDeSenha.java | nivel2/013-ValidadorDeSenha/src/validador/de/senha/ValidadorDeSenha.java | package validador.de.senha;
import java.util.Scanner;
public class ValidadorDeSenha {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("==== VALIDADOR DE SENHA ====");
System.out.print("Digite a senha: ");
String senha = scanner.nextLine();
boolean tamanhoOk = senha.length() >= 8;
boolean temMaiuscula = senha.matches(".*[A-Z].*");
boolean temNumero = senha.matches(".*[0-9].*");
boolean temEspecial = senha.matches(".*[!@#$%^&*()_+\\-={}:;\"',.<>?/].*");
if (tamanhoOk && temMaiuscula && temNumero && temEspecial) {
System.out.println("Senha forte!");
} else {
System.out.println("Senha fraca. Requisitos:");
if (!tamanhoOk) System.out.println("- Insira pelo menos 8 caracteres!");
if (!temMaiuscula) System.out.println("- Insira pelo 1 letra maiúscula!");
if (!temNumero) System.out.println("- Insira pelo menos 1 número!");
if (!temEspecial) System.out.println("- Insira pelo menos 1 caractere especial!");
}
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/017-StringEmTitulo/src/string/em/titulo/StringEmTitulo.java | nivel2/017-StringEmTitulo/src/string/em/titulo/StringEmTitulo.java | package string.em.titulo;
import java.util.Scanner;
public class StringEmTitulo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Digite um frase: ");
String frase = scanner.nextLine();
String[] palavras = frase.trim().split("\\s+");
StringBuilder titulo = new StringBuilder();
for (String palavra : palavras) {
if (!palavra.isEmpty()) {
// Capitaliza a primeira letra e junta com o restante em minúsculo
String capitalizada = palavra.substring(0, 1).toUpperCase() + palavra.substring(1).toLowerCase();
titulo.append(capitalizada).append(" ");
}
}
// Imprime o resultado removendo o espaço extra no final
System.out.println("Resultado: " + titulo.toString().trim());
scanner.close();
}
}
/**
* | **Linha de Código** | **Explicação** | **Exemplo / Observação** |
* | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
* | `String[] palavras = frase.trim().split("\\s+");` | Remove espaços extras e divide a frase em palavras, mesmo com múltiplos espaços. | `" ola mundo "` → `["ola", "mundo"]` |
* | `StringBuilder titulo = new StringBuilder();` | Cria um `StringBuilder` para montar a frase final de forma eficiente. | Evita uso excessivo de `+` com `String` |
* | `for (String palavra : palavras) {` | Percorre cada palavra do array. | Loop `for-each` |
* | `if (!palavra.isEmpty()) {` | Garante que a palavra não esteja vazia antes de capitalizar. | Evita erro com `substring` |
* | `String capitalizada = palavra.substring(0, 1).toUpperCase() + palavra.substring(1).toLowerCase();` | Capitaliza a primeira letra da palavra e coloca o restante em minúsculo. | `"jAVa"` → `"Java"` |
* | `titulo.append(capitalizada).append(" ");` | Adiciona a palavra capitalizada ao resultado final com um espaço. | Frase final sendo montada |
* | — | **Resultado Final:** string com cada palavra capitalizada e separada por espaço. | `"ola MUNDO java"` → `"Ola Mundo Java "` (pode usar `.trim()` ao final se quiser remover o último espaço) |
*/ | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/001-SomaDosDigitos/src/somadosdigitos/Main.java | nivel2/001-SomaDosDigitos/src/somadosdigitos/Main.java | package somadosdigitos;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("==== Soma dos Dígitos ====");
System.out.print("Digite um número positivo: ");
int numero = scanner.nextInt();
if (numero < 0) {
System.out.println("Número negativo! Digite apenas positivos.");
return;
}
int soma = 0;
while (numero > 0) {
soma += numero % 10; // pega o último dígito
numero /= 10; // remove o último dígito (Atalho: numero = numero / 10;)
}
/* 2a Possibilidade:
String numeroStr = String.valueOf(numero); //Converte o número para String
for (int i = 0; i < numeroStr.length(); i++) {
char c = numeroStr.charAt(i); // Pega cada caractere da string
int digito = Character.getNumericValue(c); // Converte o caractere para número (ex: '3' → 3)
soma += digito; // Vai somando cada dígito
} */
System.out.println("Soma dos dígitos: " + soma);
} catch (Exception e) {
System.out.println("Erro: digite um número inteiro válido.");
} finally {
scanner.close();
}
}
} | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/029-GeradorMegaSena/src/gerador/megasena/Gerador.java | nivel2/029-GeradorMegaSena/src/gerador/megasena/Gerador.java | package gerador.megasena;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
public class Gerador {
public static void main(String[] args){
System.out.println("Simples: " + gerarSimples());
System.out.println("===");
System.out.println("Ordenado: " + gerarOrdenado());
}
public static String gerarSimples(){
String numero = "";
int cont = 0;
Random random = new Random();
while(cont < 6){
int numeroTemporario = random.nextInt(59) + 1;
if(!numero.contains(Integer.toString(numeroTemporario))){
numero += numeroTemporario + ", ";
cont++;
}
}
numero = numero.substring(0, numero.length() - 2);
return numero;
}
public static String gerarOrdenado(){
Random random = new Random();
Set<Integer> numeros = new TreeSet<>();
while(numeros.size() < 6){
int numeroTemporario = random.nextInt(59) + 1;
numeros.add(numeroTemporario);
}
StringBuilder sb = new StringBuilder();
for(int numero: numeros){
sb.append(numero).append(", ");
}
sb.setLength(sb.length()-2);
return sb.toString();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/047-DistinctInteiros/src/distinctinteiros/DistinctInteiros.java | nivel2/047-DistinctInteiros/src/distinctinteiros/DistinctInteiros.java | package distinctinteiros;
import java.util.*;
import java.util.stream.Collectors;
public class DistinctInteiros {
public static void main(String[] args) {
// 1) Usando Stream.distinct()
List<Integer> numeros = Arrays.asList(1,1,2,3,4,5,6,6,7,7,8,8,9,9,9,10);
List<Integer> unicos = numeros.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("Original: " + numeros);
System.out.println("Únicos (stream.distinct): " + unicos);
// 2) Alternativa one-pass usando LinkedHashSet (preserva ordem)
Set<Integer> setUnicos = new LinkedHashSet<>(numeros);
List<Integer> unicosOnePass = new ArrayList<>(setUnicos);
System.out.println("Únicos (LinkedHashSet one-pass): " + unicosOnePass);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/010-PrimeiroCaractereRepetido/src/primeiro/caractere/repetido/PrimeiroCaractereRepetido.java | nivel2/010-PrimeiroCaractereRepetido/src/primeiro/caractere/repetido/PrimeiroCaractereRepetido.java | package primeiro.caractere.repetido;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class PrimeiroCaractereRepetido {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Digite uma frase: ");
String texto = scanner.nextLine();
Character repetido = encontrarPrimeiroRepetido(texto);
if (repetido != null) {
System.out.println("O primeiro caractere repetido é: '" + repetido + "'");
} else {
System.out.println("Nenhum caractere se repete.");
}
scanner.close();
}
public static Character encontrarPrimeiroRepetido(String texto) {
Set<Character> vistos = new HashSet<>();
for (char c : texto.toLowerCase().toCharArray()) {
if (c == ' ') continue;
if (vistos.contains(c)) {
return c;
}
vistos.add(c);
}
return null; // nenhum repetido
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/030-IntercalarListas/src/intercalar/listas/Listas.java | nivel2/030-IntercalarListas/src/intercalar/listas/Listas.java | package intercalar.listas;
import java.util.List;
public class Listas {
public static void main(String[] args) {
List<String> lista1 = List.of("A", "B", "C");
List<String> lista2 = List.of("1", "2", "3", "4", "5");
System.out.println("Teste: lista 1 menor que lista 2");
Listas.intercalarListas(lista1, lista2);
System.out.println("Teste: lista 1 igual lista 2");
lista2 = List.of("X", "Y", "Z");
Listas.intercalarListas(lista1, lista2);
System.out.println("Teste: lista 1 maior que lista 2");
lista1 = List.of("A", "B", "C", "D");
lista2 = List.of("9", "8");
Listas.intercalarListas(lista1, lista2);
}
public static void intercalarListas(List lista1, List lista2){
int tamanhoLista1 = lista1.size();
int tamanhoLista2 = lista2.size();
System.out.println("=====================");
if(tamanhoLista1 == tamanhoLista2){
for(int i = 0; i < tamanhoLista1; i++){
System.out.println("Lista 1: " + lista1.get(i) + " Lista 2: " + lista2.get(i));
}
return;
} else if(tamanhoLista1 < tamanhoLista2){
for(int i = 0; i < tamanhoLista1; i++){
System.out.println("Lista 1: " + lista1.get(i) + " Lista 2: " + lista2.get(i));
}
for(int i = tamanhoLista1; i < tamanhoLista2; i++){
System.out.println("Lista 2: " + lista2.get(i));
}
} else {
for(int i = 0; i < tamanhoLista2; i++){
System.out.println("Lista 1: " + lista1.get(i) + " Lista 2: " + lista2.get(i));
}
for(int i = tamanhoLista2; i < tamanhoLista1; i++){
System.out.println("Lista 1: " + lista1.get(i));
}
}
System.out.println("=====================");
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/039-LambdaThread/src/thread/LambdaThread.java | nivel2/039-LambdaThread/src/thread/LambdaThread.java | package thread;
public class LambdaThread {
public static void main(String[] args) {
Runnable tarefa = () -> System.out.println("Executando a tarefa em uma nova thread!");
Thread thread = new Thread(tarefa);
thread.start();
System.out.println("Thread principal continua executando...");
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/019-Potencia/src/potencia/Potencia.java | nivel2/019-Potencia/src/potencia/Potencia.java | package potencia;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Potencia {
public static double calcularPotencia(double base, double expoente) {
if (expoente == 0) {
return 1.0;
}
if (base == 0 && expoente < 0) {
throw new IllegalArgumentException("Não é possível calcular 0 elevado a um expoente negativo (divisão por zero).");
}
return Math.pow(base, expoente);
}
// Método auxiliar para ler números com validação
public static double lerNumero(Scanner scanner, String mensagem) {
while (true) {
try {
System.out.print(mensagem);
return scanner.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Entrada inválida! Digite apenas números.");
scanner.nextLine(); // descarta a entrada errada para evitar loop infinito
}
}
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
double base = lerNumero(scanner, "Informe o número base: ");
double expoente = lerNumero(scanner, "Informe o expoente: ");
try {
double resultado = calcularPotencia(base, expoente);
System.out.printf("Resultado: %.4f%n", resultado);
} catch (IllegalArgumentException e) {
System.out.println("Erro: " + e.getMessage());
}
}
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/032-LambdaImprimirElementos/src/imprimir/elementos/LambdaImprimirElementos.java | nivel2/032-LambdaImprimirElementos/src/imprimir/elementos/LambdaImprimirElementos.java | package imprimir.elementos;
import java.util.Arrays;
import java.util.List;
public class LambdaImprimirElementos {
public static void main(String[] args) {
List<Integer> listaDeInteiros = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
listaDeInteiros.forEach(n -> System.out.println(n));
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/028-SimuladorDeEstoque/src/simulador/estoque/Produto.java | nivel2/028-SimuladorDeEstoque/src/simulador/estoque/Produto.java | package simulador.estoque;
public class Produto {
String nome;
int quantidade;
// Construtor
public Produto(String nome, int quantidade) {
this.nome = nome;
this.quantidade = quantidade;
}
// Getters
public String getNome() {
return nome;
}
public int getQuantidade() {
return quantidade;
}
// Adicionar quantidade
public void adicionar(int qtd) {
if (qtd > 0) {
quantidade += qtd;
System.out.println(qtd + " unidade(s) adicionada(s) ao estoque.");
} else {
System.out.println("[ERRO] Quantidade deve ser maior que 0!");
}
}
// Remover quantidade
public void remover(int qtd){
if (qtd <= 0) {
System.out.println("[ERRO] Quantidade deve ser maior que 0!");
} else if (qtd > quantidade) {
System.out.println("[ERRO] Estoque insuficiente!");
} else {
quantidade -= qtd;
System.out.println(qtd + " unidade(s) removida(s) do estoque.");
}
}
@Override
public String toString() {
return String.format("Produto: %-20s | Estoque: %d", nome, quantidade);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/028-SimuladorDeEstoque/src/simulador/estoque/ControleEsqtoque.java | nivel2/028-SimuladorDeEstoque/src/simulador/estoque/ControleEsqtoque.java | package simulador.estoque;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ControleEsqtoque {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Produto> produtos = new ArrayList<>();
int opcao;
do {
System.out.println("\n==== MENU ESTOQUE ====");
System.out.println("1 - Cadastrar produto");
System.out.println("2 - Adicionar ao estoque");
System.out.println("3 - Remover do estoque");
System.out.println("4 - Listar produtos");
System.out.println("5 - Sair");
System.out.print("Escolha uma opção: ");
opcao = scanner.nextInt();
scanner.nextLine();
switch (opcao) {
case 1:
System.out.print("Nome do produto: ");
String nome = scanner.nextLine();
System.out.print("Quantidade inicial: ");
int qtdInicial = scanner.nextInt();
produtos.add(new Produto(nome, qtdInicial));
System.out.println("Produto cadastrado com sucesso!");
break;
case 2:
System.out.print("Nome do produto para adicionar: ");
String nomeAdd = scanner.nextLine();
Produto produtoAdd = buscarProduto(produtos, nomeAdd);
if (produtoAdd != null) {
System.out.print("Quantidade a adicionar: ");
int qtdAdd = scanner.nextInt();
produtoAdd.adicionar(qtdAdd);
} else {
System.out.println("[ERRO] Produto não encontrado!");
}
break;
case 3:
System.out.print("Nome do produto para remover: ");
String nomeRemover = scanner.nextLine();
Produto produtoRemover = buscarProduto(produtos, nomeRemover);
if (produtoRemover != null) {
System.out.print("Quantidade a remover: ");
int qtdRemover = scanner.nextInt();
produtoRemover.remover(qtdRemover);
} else {
System.out.println("[ERRO] Produto não encontrado!");
}
break;
case 4:
if (produtos.isEmpty()){
System.out.println("Nenhum produto cadastrado.");
} else {
System.out.println("\n==== ESTOQUE ATUAL ====");
produtos.forEach(System.out::println);
}
break;
case 5:
System.out.println("Encerrando o sistema...");
break;
default:
System.out.println("[ERRO] Opção inválida!");
}
} while (opcao != 5);
scanner.close();
}
// Método auxiliar para buscar produto pelo nome
private static Produto buscarProduto(List<Produto> produtos, String nome) {
for (Produto p : produtos) {
if (p.getNome().equalsIgnoreCase(nome)) {
return p;
}
}
return null;
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/003-DuplicadosArray/src/duplicadosarray/Main.java | nivel2/003-DuplicadosArray/src/duplicadosarray/Main.java | package duplicadosarray;
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] numeros = {1, 2, 2, 3, 4, 4, 5};
Set<Integer> setSemDuplicados = new LinkedHashSet<>();
for (int num : numeros) {
setSemDuplicados.add(num);
}
Integer[] resultado = setSemDuplicados.toArray(new Integer[0]);
System.out.println("Array sem duplicados: " + Arrays.toString(resultado));
}
}
// Set<Integer> Cria uma coleção que não aceita repetidos
// LinkedHashSet Mantém a ordem original dos elementos
// for (int num : numeros) Percorre cada número do array
// setSemDuplicados.add(num) Adiciona ao Set, mas ignora os duplicados automaticamente
// toArray(new Integer[0]) Transforma o Set de volta em um array
// Arrays.toString(...) Converte o array para uma String bonitinha para impressão | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/023-BuscaBinaria/src/busca/binaria/BuscaBinaria.java | nivel2/023-BuscaBinaria/src/busca/binaria/BuscaBinaria.java | package busca.binaria;
import java.util.Arrays;
import java.util.Scanner;
public class BuscaBinaria {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int tamanhoArray = lerNumero(scanner, "Digite o número de elementos do array: ");
int[] array = new int[tamanhoArray];
for (int i = 0; i < tamanhoArray; i++) {
array[i] = lerNumero(scanner, "Digite o " + (i + 1) + "° elemento: ");
}
Arrays.sort(array);
System.out.println("Array em ordem crescente: " + Arrays.toString(array));
int elementoAlvo = lerNumero(scanner, "\nDigite o elemento alvo: ");
int indiceEncontrado = Arrays.binarySearch(array, elementoAlvo);
if (indiceEncontrado >= 0) {
System.out.println("Elemento encontrado na posição (índice): " + indiceEncontrado);
} else {
System.out.println("Elemento não encontrado no array.");
}
scanner.close();
}
// 🔹 Método auxiliar para ler somente números inteiros
public static int lerNumero(Scanner scanner, String mensagem) {
System.out.print(mensagem);
while (!scanner.hasNextInt()) {
System.out.print("Entrada inválida! Digite apenas números: ");
scanner.next(); // descarta a entrada inválida
}
return scanner.nextInt();
}
} | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/004-MaiorEMenor/src/maior/e/menor/Main.java | nivel2/004-MaiorEMenor/src/maior/e/menor/Main.java | package maior.e.menor;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Digite os números separados por espaço: ");
String entrada = scanner.nextLine(); //Lê tudo que foi digitado como uma String
String[] partes = entrada.split(" ");
if (partes.length == 0) {
System.out.println("Nenhum número foi informado.");
return;
}
try {
int menor = Integer.MAX_VALUE;
int maior = Integer.MIN_VALUE;
int soma = 0;
List<Integer> pares = new ArrayList<>();
List<Integer> impares = new ArrayList<>();
for (String parte : partes) {
int numero = Integer.parseInt(parte);
// Atualiza maior e menor
if (numero < menor) menor = numero;
if (numero > maior) maior = numero;
// Soma para média
soma += numero;
// Separa pares e ímpares
if (numero % 2 == 0) {
pares.add(numero);
} else {
impares.add(numero);
}
}
int quantidade = partes.length;
double media = (double) soma / quantidade;
String mediaFormatada = String.format("%.2f", media);
// Saídas:
System.out.println("\n📌 Resultados:");
System.out.println("Menor número: " + menor);
System.out.println("Maior número: " + maior);
System.out.println("Média: " + mediaFormatada);
System.out.println("Pares: " + pares);
System.out.println("Ímpares: " + impares);
} catch (NumberFormatException e) {
System.out.println("Erro: Digite apenas números inteiros válidos.");
} finally {
scanner.close();
}
}
}
/*
| Parte do código | O que faz |
| ------------------------- | ---------------------------------------------------------------------- |
| `Integer.MAX_VALUE` | Valor inicial enorme para garantir que qualquer número seja menor |
| `Integer.MIN_VALUE` | Valor inicial muito baixo para garantir que qualquer número seja maior |
| `entrada.split(" ")` | Divide os números digitados pelo usuário |
| `Integer.parseInt(parte)` | Converte cada parte da String em inteiro |
| `if (numero < menor)` | Atualiza o menor valor encontrado |
| `if (numero > maior)` | Atualiza o maior valor encontrado |
| Parte nova do código | O que faz |
| -------------------------------------------- | ------------------------------------------------ |
| `soma += numero;` | Acumula os valores para cálculo da média |
| `double media = (double) soma / quantidade;` | Faz o cálculo da média usando cast para precisão |
| `numero % 2 == 0` | Verifica se o número é par |
| `pares.add(...)` / `impares.add(...)` | Separa os números em duas listas |
*/ | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/036-LambdaMaiorElemento/src/maior/elemento/LambdaMaiorElemento.java | nivel2/036-LambdaMaiorElemento/src/maior/elemento/LambdaMaiorElemento.java | package maior.elemento;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class LambdaMaiorElemento {
public static void main(String[] args) {
List<Integer> listaDeElementos = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Optional<Integer> maior = listaDeElementos.stream()
.max((a, b) -> Integer.compare(a, b));
maior.ifPresent(m -> System.out.println("Maior presente: " + m));
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/040-LambdaPercorrerListaInteiros/src/percorrerlista/PercorrerListaInteiros.java | nivel2/040-LambdaPercorrerListaInteiros/src/percorrerlista/PercorrerListaInteiros.java | package percorrerlista;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class PercorrerListaInteiros {
public static void main(String[] args) {
List<Integer> inteiros = Arrays.asList(1,2,3,4,5,6,7,8,9, 10);
// Parte 1: Usando Iterator
System.out.println("Percorrendo com Interator: ");
Iterator<Integer> iterator = inteiros.iterator();
while (iterator.hasNext()) {
Integer numero = iterator.next();
System.out.println(numero);
}
// Parte 2: Usando Stream
System.out.println("\nPercorrendo com Stream:");
inteiros.stream().forEach(System.out::println);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/012-CaixaEletronico/src/app/Main.java | nivel2/012-CaixaEletronico/src/app/Main.java | package app;
import model.Conta;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Conta conta = new Conta();
int opcao;
do {
System.out.println("\n=== Caixa Eletrônico ===");
System.out.println("1 - Ver saldo");
System.out.println("2 - Depositar");
System.out.println("3 - Sacar");
System.out.println("0 - Sair");
System.out.print("Escolha uma opção: ");
opcao = scanner.nextInt();
switch (opcao) {
case 1:
conta.exibirSaldo();
break;
case 2:
System.out.print("Digite o valor para depositar: ");
double valorDepositado = scanner.nextDouble();
conta.depositar(valorDepositado);
break;
case 3:
System.out.print("Digite o valor para sacar: ");
double valorSaque = scanner.nextDouble();
conta.sacar(valorSaque);
break;
case 0:
System.out.println("Saindo... Obrigado por usar o Caixa Eletrônico!");
break;
default:
System.out.println("Opção inválida!");
}
} while (opcao !=0);
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/012-CaixaEletronico/src/model/Conta.java | nivel2/012-CaixaEletronico/src/model/Conta.java | package model;
public class Conta {
private double saldo;
public Conta () {
this.saldo = 0.0;
}
public double getSaldo() {
return saldo;
}
public void depositar(double valor) {
if (valor > 0) {
saldo += valor;
System.out.println("Depósito de R$" + valor + " realizado com sucesso.");
} else {
System.out.println("Valor inválido para depósito.");
}
}
public void sacar(double valor) {
if (valor <= 0) {
System.out.println("Valor inválido para saque.");
} else if (valor > saldo) {
System.out.println("[ERRO] Saldo insuficiente!");
} else {
saldo -= valor;
System.out.println("Saque de R$" + valor + " realizado com sucesso.");
}
}
public void exibirSaldo() {
System.out.printf("Saldo atual: R$ %.2f%n", saldo);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/020-RestoDaDivisao/src/divisao/ConsoleUI.java | nivel2/020-RestoDaDivisao/src/divisao/ConsoleUI.java | package divisao;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ConsoleUI {
private final Scanner scanner;
private final DivisaoService service;
public ConsoleUI() {
this.scanner = new Scanner(System.in);
this.service = new DivisaoService();
}
public void iniciar() {
boolean continuar = true;
while (continuar) {
System.out.println("\n--- Calculadora de Divisão Empresarial ---");
int dividendo = lerNumero("Digite o dividendo: ");
int divisor = lerNumero("Digite o divisor: ");
try {
Divisao divisao = new Divisao(dividendo, divisor);
exibirResultado(divisao);
} catch (IllegalArgumentException e) {
System.out.println("Erro: " + e.getMessage());
}
continuar = desejaContinuar();
}
scanner.close();
System.out.println("Programa encerrado. Até mais!");
}
private int lerNumero(String mensagem) {
while (true) {
try {
System.out.print(mensagem);
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Entrada inválida! Digite apenas números inteiros.");
scanner.nextLine(); // limpa buffer inválido
}
}
}
private void exibirResultado(Divisao divisao) {
int resultado = service.calcularResultado(divisao);
int resto = service.calcularResto(divisao);
System.out.println("\n--- Resultados ---");
System.out.println("Resultado da divisão: " + resultado);
System.out.println("Resto da divisão: " + resto);
}
private boolean desejaContinuar() {
while (true) {
System.out.print("\nDeseja realizar outro cálculo? (S/N): ");
String resposta = scanner.next().trim();
if (resposta.equalsIgnoreCase("S")) {
return true;
} else if (resposta.equalsIgnoreCase("N")) {
return false;
} else {
System.out.println("Entrada inválida! Digite apenas 'S' para sim ou 'N' para não.");
}
}
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/020-RestoDaDivisao/src/divisao/App.java | nivel2/020-RestoDaDivisao/src/divisao/App.java | package divisao;
public class App {
public static void main(String[] args) {
new ConsoleUI().iniciar();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/020-RestoDaDivisao/src/divisao/DivisaoService.java | nivel2/020-RestoDaDivisao/src/divisao/DivisaoService.java | package divisao;
public class DivisaoService {
public int calcularResultado(Divisao divisao) {
return divisao.getDividendo() / divisao.getDivisor();
}
public int calcularResto(Divisao divisao) {
return divisao.getDividendo() % divisao.getDivisor();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/020-RestoDaDivisao/src/divisao/Divisao.java | nivel2/020-RestoDaDivisao/src/divisao/Divisao.java | package divisao;
public class Divisao {
private final int dividendo;
private final int divisor;
public Divisao(int dividendo, int divisor) {
if (divisor == 0) {
throw new IllegalArgumentException("Divisor não pode ser zero.");
}
this.dividendo = dividendo;
this.divisor = divisor;
}
public int getDividendo() {
return dividendo;
}
public int getDivisor() {
return divisor;
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/041-MapQuadradosInteiros/src/mapquadrados/MapQuadradosInteiros.java | nivel2/041-MapQuadradosInteiros/src/mapquadrados/MapQuadradosInteiros.java | package mapquadrados;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MapQuadradosInteiros {
public static void main(String[] args) {
List<Integer> numeros = Arrays.asList(2,4,6,8,10);
List<Integer> quadrados = numeros.stream()
.map(n -> n * n)
.collect(Collectors.toList());
System.out.printf("Lista original: " + numeros);
System.out.printf("\nLista dos quadrados: " + quadrados);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/025-RotacionarArray/src/array/rotacao/RotacionarArray.java | nivel2/025-RotacionarArray/src/array/rotacao/RotacionarArray.java | package array.rotacao;
import java.util.Arrays;
import java.util.Scanner;
public class RotacionarArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numeros = {1, 2, 3, 4, 5};
System.out.println("==== Rotacionador de Array ====");
System.out.println("Array inicial: " + Arrays.toString(numeros));
System.out.print("Quantas rotações deseja fazer? ");
int k = scanner.nextInt();
System.out.print("Digite 'E' para esquerda ou 'D' para direita: ");
String direcao = scanner.next().trim().toUpperCase();
k = k % numeros.length; // Otimização: não precisa rotacionar mais que o tamanho do array
if (direcao.equals("E")) {
rotacionarEsquerda(numeros, k);
} else if (direcao.equals("D")) {
rotacionarDireita(numeros, k);
} else {
System.out.println("Direção inválida!");
scanner.close();
return;
}
System.out.println("Array após rotação: " + Arrays.toString(numeros));
scanner.close();
}
// Rotacionar para a esquerda k vezes
private static void rotacionarEsquerda(int[] arr, int k) {
for (int r = 0; r < k; r++) {
int primeiro = arr[0];
for (int i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr[arr.length - 1] = primeiro;
}
}
// Rotacionar para a direita k vezes
private static void rotacionarDireita(int[] arr, int k) {
for (int r = 0; r < k; r++) {
int ultimo = arr[arr.length - 1];
for (int i = arr.length - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = ultimo;
}
}
} | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel2/045-VerificarMatchInteiros/src/verificarmatch/VerificarMatchInteiros.java | nivel2/045-VerificarMatchInteiros/src/verificarmatch/VerificarMatchInteiros.java | package verificarmatch;
import java.util.*;
public class VerificarMatchInteiros {
public static void main(String[] args) {
List<Integer> numeros = Arrays.asList(2, 3, 14, -5, 9);
// 1) Todos positivos, algum par, nenhum múltiplo de 7
boolean todosPositivos = numeros.stream().allMatch(n -> n > 0);
boolean algumPar = numeros.stream().anyMatch(n -> n % 2 == 0);
boolean nenhumMultiplo7 = numeros.stream().noneMatch(n -> n % 7 == 0);
List<Integer> positivos = new ArrayList<>();
List<Integer> negativos = new ArrayList<>();
List<Integer> pares = new ArrayList<>();
List<Integer> impares = new ArrayList<>();
List<Integer> multiplosDe7 = new ArrayList<>();
for (Integer n : numeros){
if (n == null) continue;
// positivos e negativos
if (n > 0) { positivos.add(n); } else { negativos.add(n); }
// pares e ímpares
if (n % 2 == 0) { pares.add(n); } else { impares.add(n); }
// múltiplos de 7
if (n % 7 == 0) { multiplosDe7.add(n); }
}
System.out.println("Lista: " + numeros);
System.out.println("\n--- allMatch ---");
System.out.println("Todos positivos? " + todosPositivos);
System.out.println("Positivos: " + positivos);
System.out.println("Negativos: " + negativos);
System.out.println("\n--- anyMatch ---");
System.out.println("Algum é par? " + algumPar);
System.out.println("Pares: " + pares);
System.out.println("Ímpares: " + impares);
System.out.println("\n--- noneMatch ---");
System.out.println("Nenhum é múltiplo de 7? " + nenhumMultiplo7);
System.out.println("Múltiplos de 7: " + multiplosDe7);
}
} | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/015-JogoNumeroSecreto/src/jogo/JogoNumeroSecreto.java | nivel3/015-JogoNumeroSecreto/src/jogo/JogoNumeroSecreto.java | package jogo;
import java.util.Random;
import java.util.Scanner;
public class JogoNumeroSecreto {
/**
* 039. Jogo de adivinhação com tentativas limitadas
* Com um número de tentativas definido pelo usuário.
* Armazene um número secreto
* Diga se o número digitado é maior ou menor.
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int numeroSorteado = random.nextInt(100); // Número entre 0 e 99
int tentativasMaximas, tentativasUsadas = 0;
boolean acertou = false;
System.out.println("=== Jogo da Adivinhação! ===");
System.out.print("Quantas tentativas você quer? ");
tentativasMaximas = scanner.nextInt();
System.out.printf("Você usará %d tentativa(s). Vamos começar!\n", tentativasMaximas);
while (tentativasUsadas < tentativasMaximas) {
System.out.printf("\nTentativa %d de %d\n", tentativasUsadas + 1, tentativasMaximas);
System.out.print("Informe um número de 0 a 99: ");
int palpite = scanner.nextInt();
if (palpite > numeroSorteado) {
System.out.printf("[ERROU!] %d é MAIOR que o valor sorteado!\n", palpite);
} else if (palpite < numeroSorteado) {
System.out.printf("[ERROU!] %d é MENOR que o valor sorteado!\n", palpite);
} else {
System.out.printf("\n[ACERTOU!] PARABÉNS! O valor sorteado foi: %d\n", numeroSorteado);
System.out.printf("Você utilizou %d tentativa(s).\n", tentativasUsadas + 1);
acertou = true;
break;
}
tentativasUsadas++;
}
if (!acertou) {
System.out.printf("\n[GAME OVER!] Todas as %d tentativas foram usadas.\n", tentativasMaximas);
System.out.printf("O número correto era: %d\n", numeroSorteado);
}
System.out.println("\nObrigado por jogar!");
System.out.println("Finalizando jogo...");
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/001-ContagemRegressiva/src/contagem/regressiva/ContagemRegressiva.java | nivel3/001-ContagemRegressiva/src/contagem/regressiva/ContagemRegressiva.java | package contagem.regressiva;
import java.util.Scanner;
public class ContagemRegressiva {
public static void main(String[] args) {
/**
* Peça ao usuário um número inteiro e faça uma contagem regressiva até 0, exibindo os números um por um.
*/
Scanner scanner = new Scanner(System.in);
System.out.print("Informe um número inteiro: ");
int numero = scanner.nextInt();
System.out.println("\nContagem regressiva: ");
for (int i = numero; i >= 0; i--) {
System.out.println(i);
}
System.out.println("Fim!");
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/020-Tabuada1ao10/src/tabuada/Tabuada.java | nivel3/020-Tabuada1ao10/src/tabuada/Tabuada.java | package tabuada;
public class Tabuada {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println("===============");
gerarTabuada(i);
}
}
public static void gerarTabuada(int num) {
for (int i = 0; i <= 10; i++) {
System.out.printf("%d x %d = %d%n", num, i, (num * i));
}
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/021-RelogioDigital/src/relogio/digital/RelogioDigital.java | nivel3/021-RelogioDigital/src/relogio/digital/RelogioDigital.java | package relogio.digital;
import java.util.Scanner;
public class RelogioDigital {
private int hora;
private int minuto;
private int segundo;
public RelogioDigital(int hora, int minuto, int segundo) {
this.hora = hora;
this.minuto = minuto;
this.segundo = segundo;
}
public void start() {
System.out.println("=== Relogio Digital ===");
while (true) {
segundo++;
if(segundo == 60){
segundo = 0;
minuto++;
}
if(minuto == 60){
minuto = 0;
hora++;
}
if(hora == 24){
hora = 0;
minuto = 0;
segundo = 0;
}
System.out.printf("%02d:%02d:%02d%n", hora, minuto, segundo);
try {
Thread.sleep(1000);
}catch (InterruptedException e){
break;
}
}
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Digite a hora:");
int hora = input.nextInt();
System.out.println("Digite a Minuto:");
int minuto = input.nextInt();
System.out.println("Digite a Segundo:");
int segundo = input.nextInt();
hora = hora > 23 ? 0 : hora;
minuto = minuto > 59 ? 0 : minuto;
segundo = segundo > 59 ? 0 : segundo;
RelogioDigital relogio = new RelogioDigital(hora, minuto, segundo);
relogio.start();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/002-Pares1A100/src/pares/Pares1A100.java | nivel3/002-Pares1A100/src/pares/Pares1A100.java | package pares;
public class Pares1A100 {
public static void main(String[] args) {
/**
* Use um for ou while para imprimir todos os números pares entre 1 e 100.
*/
for (int i = 0; i < 101; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/012-NumeroPrimoComBreak/src/numero/primo/NumeroPrimoComBreak.java | nivel3/012-NumeroPrimoComBreak/src/numero/primo/NumeroPrimoComBreak.java | package numero.primo;
import java.util.Scanner;
public class NumeroPrimoComBreak {
/**
* 036. Número Primo com break
* Dado um número,
* verifique se é primo
* interrompendo o laço assim que encontrar um divisor.
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Informe um número inteiro positivo: ");
int n = scanner.nextInt();
boolean ehPrimo = true;
for (int i = 2; i < n; i++) {
if (n % i == 0) {
ehPrimo = false;
break;
}
}
if (ehPrimo) {
System.out.println(n + " é primo.");
} else {
System.out.println(n + " NÃO é primo.");
}
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/017-TrianguloAsteriscosDireita/src/triangulo/direita/TrianguloDireita.java | nivel3/017-TrianguloAsteriscosDireita/src/triangulo/direita/TrianguloDireita.java | package triangulo.direita;
import java.util.Scanner;
public class TrianguloDireita {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Digite o tamanho da pirâmide: ");
int tamanho = input.nextInt();
gerarTriangulo(tamanho);
input.close();
}
public static void gerarTriangulo(int tamanho) {
for (int linha = 1; linha <= tamanho; linha++) {
System.out.println(" ".repeat(tamanho - linha) + "*".repeat(linha));
}
}
} | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/016-TrianguloAsteriscosEsquerda/src/triangulo/esquerda/TrianguloEsquerda.java | nivel3/016-TrianguloAsteriscosEsquerda/src/triangulo/esquerda/TrianguloEsquerda.java | package triangulo.esquerda;
import java.util.Scanner;
public class TrianguloEsquerda {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Deseja uma pirâmide com quantas linhas? ");
int tamanho = input.nextInt();
gerarTriangulo(tamanho);
}
public static void gerarTriangulo(int tamanho) {
for (int linha = 1; linha <= tamanho; linha++) {
System.out.println("*".repeat(linha));
}
}
} | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/011-MediaDeNotasComLaco/src/media/MediaDeNotasComLaco.java | nivel3/011-MediaDeNotasComLaco/src/media/MediaDeNotasComLaco.java | package media;
import java.util.Scanner;
public class MediaDeNotasComLaco {
/**
* 035. Média de notas com laço
* O usuário digita as notas dos alunos (até digitar -1).
* Ao final, calcule e exiba a média das notas.
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int contadorDeNotas = 0;
double somatorioDasNotas = 0;
double nota;
do {
System.out.print("Nota do aluno (-1 para calcular média): ");
nota = scanner.nextDouble();
if (nota != -1) {
somatorioDasNotas += nota;
contadorDeNotas++;
}
} while (nota != -1);
if (contadorDeNotas > 0) {
double media = somatorioDasNotas / contadorDeNotas;
System.out.println("\nA média do aluno é: " + media);
} else {
System.out.println("\nNenhuma nota válida foi inserida.");
}
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/022-Cronometro/src/cronometro/Cronometro.java | nivel3/022-Cronometro/src/cronometro/Cronometro.java | package cronometro;
import java.util.Scanner;
public class Cronometro {
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
System.out.println("Quer um contador de quantos segundos? ");
int segundos = input.nextInt();
iniciarCronometro(segundos);
}
public static void iniciarCronometro(int segundos) throws InterruptedException {
int segundosContador = 0;
while(true){
System.out.println(formatarHorario(segundosContador));
segundosContador++;
Thread.sleep(1000);
if(segundosContador > segundos){
break;
}
}
System.out.println("FIM!");
}
private static String formatarHorario(int segundos) {
int horas = segundos / 3600;
int minutos = (segundos % 3600) / 60;
int segs = segundos % 60;
return String.format("%02d:%02d:%02d", horas, minutos, segs);
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/013-ContadorDeDigitos/src/contador/ContadorDeDigitos.java | nivel3/013-ContadorDeDigitos/src/contador/ContadorDeDigitos.java | package contador;
import java.util.Scanner;
public class ContadorDeDigitos {
/**
* 037. Contar dígitos de um número
* Peça um número inteiro
* Conte quantos dígitos ele possui usando while.
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Informe um número inteiro: ");
int numero = scanner.nextInt();
if (numero == 0) {
System.out.println("Quantidade de dígitos: 1");
} else {
numero = Math.abs(numero); // Garante que o número seja positivo
int contador = 0;
while (numero != 0) {
numero = numero / 10;
contador++;
}
System.out.println("Quantidade de dígitos: " + contador);
}
scanner.close();
}
} | java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/003-SomaComLaco/src/soma/SomaComLaco.java | nivel3/003-SomaComLaco/src/soma/SomaComLaco.java | package soma;
import java.util.Scanner;
public class SomaComLaco {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int contador = 0;
int soma = 0;
do {
System.out.printf("Informe o %dº número: ", contador + 1);
int valor = scanner.nextInt();
soma += valor;
contador++;
} while (contador != 10);
System.out.println("\nA soma dos valores é " + soma);
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/005-MenuComDoWhile/src/menu/MenuComDoWhile.java | nivel3/005-MenuComDoWhile/src/menu/MenuComDoWhile.java | package menu;
import java.util.Scanner;
public class MenuComDoWhile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int opcao;
do {
System.out.println("\nEscolha uma opção do Menu:");
System.out.println("[1] Ver saldo");
System.out.println("[2] Depositar");
System.out.println("[3] Sair");
System.out.print("Opção: ");
opcao = scanner.nextInt();
if (opcao == 1) {
System.out.println("Saldo: 1.000,00R$");
} else if (opcao == 2) {
System.out.println("Depósito efetuado com sucesso!");
} else if (opcao != 3) {
System.out.println("Informe uma opção válida!");
}
} while (opcao != 3);
System.out.println("Finalizando menu...");
System.out.println("Volte sempre!");
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/008-SomaComLaco/src/soma/SomaComLaco.java | nivel3/008-SomaComLaco/src/soma/SomaComLaco.java | package soma;
import java.util.Scanner;
public class SomaComLaco {
public static void main(String[] args) {
/**
* 032. Soma até número negativo
* O programa deve somar os números digitados
* até que o usuário informe um número negativo.
*/
Scanner scanner = new Scanner(System.in);
int soma = 0;
int valor = 0;
while (valor >= 0) {
System.out.print("Informe um valor inteiro (negativo para sair): ");
valor = scanner.nextInt();
if (valor >= 0) {
soma += valor;
}
}
System.out.printf("\nA soma dos valores é: " + soma);
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/014-InverterNumero/src/inverter/numero/InverterNumero.java | nivel3/014-InverterNumero/src/inverter/numero/InverterNumero.java | package inverter.numero;
import java.util.Scanner;
public class InverterNumero {
/**
* 038. Inverter número inteiro
* Digite: 12345
* Saída: 54321
* (Dica: use while com % e /)
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("==== INVERSOR DE NÚMEROS ====");
System.out.print("Informe um número inteiro: ");
int numero = scanner.nextInt();
System.out.print("Número invertido: ");
while (numero !=0) {
int digito = numero % 10;
numero = numero / 10;
System.out.print(digito);
}
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/009-NumeroPerfeito/src/numero/perfeito/NumeroPerfeito.java | nivel3/009-NumeroPerfeito/src/numero/perfeito/NumeroPerfeito.java | package numero.perfeito;
import java.util.Scanner;
public class NumeroPerfeito {
public static void main(String[] args) {
/**
* 033. Verificar número perfeito
* Um número é perfeito se a soma dos seus divisores próprios
* (excluindo ele mesmo) for igual a ele.
* → Ex: 6 → 1 + 2 + 3 = 6
*/
Scanner scanner = new Scanner(System.in);
System.out.println("==== Número Perfeito ====");
System.out.print("Informe um número inteiro: ");
int numeroDigitado = scanner.nextInt();
int soma = 0;
for (int i = 1; i < numeroDigitado; i++) {
if (numeroDigitado % i == 0) {
soma += i;
}
}
if (soma == numeroDigitado) {
System.out.printf("O número %d é perfeito!", numeroDigitado);
} else {
System.out.printf("O número %d não é perfeito!", numeroDigitado);
}
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/006-ContaNumeros/src/conta/numeros/ContaNumeros.java | nivel3/006-ContaNumeros/src/conta/numeros/ContaNumeros.java | package conta.numeros;
import java.util.Scanner;
public class ContaNumeros {
public static void main(String[] args) {
/**
* 030. Contar números negativos, positivos e zeros
* O usuário digita 10 números.
* Conte quantos são negativos, positivos ou zero.
*/
Scanner scanner = new Scanner(System.in);
int contador = 0;
int contadorNegativos = 0;
int contadorPositivos = 0;
int contadorZeros = 0;
do {
System.out.printf("Informe o %dº número: ", contador + 1);
int valor = scanner.nextInt();
if (valor < 0) {
contadorNegativos++;
} else if (valor > 0) {
contadorPositivos++;
} else if (valor == 0) {
contadorZeros++;
}
contador++;
} while (contador != 10);
System.out.printf("\nAo todo foram digitados: ");
System.out.printf("\n%d números negativos.", contadorNegativos);
System.out.printf("\n%d números positivos.", contadorPositivos);
System.out.printf("\n%d números zeros.", contadorZeros);
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/004-NumeroSecreto/src/numero/secreto/NumeroSecreto.java | nivel3/004-NumeroSecreto/src/numero/secreto/NumeroSecreto.java | package numero.secreto;
import java.util.Random;
import java.util.Scanner;
public class NumeroSecreto {
public static void main(String[] args) {
/**
* Armazene um número secreto e peça tentativas até o usuário acertar.
* Diga se o número digitado é maior ou menor.
*/
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int numeroSorteado = random.nextInt(100
);
int valor = 0;
System.out.println("=== Jogo da Adivinhação! ===");
while (numeroSorteado != valor) {
System.out.print("\nInforme um número de 1 a 100: ");
valor = scanner.nextInt();
if (numeroSorteado > valor) {
System.out.println("[ERROU!]" + valor + " é MENOR que o valor sorteado!");
} else if (numeroSorteado < valor) {
System.out.println("[ERROU!]" + valor + " é MAIOR que o valor sorteado!");
} else {
System.out.println("[ACERTOU!] PARABÉNS! o valor sorteado foi: " + numeroSorteado);
}
}
System.out.println("Finalizando jogo...");
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/010-GeradorDePotencia/src/potencia/GeradorDePotencia.java | nivel3/010-GeradorDePotencia/src/potencia/GeradorDePotencia.java | package potencia;
import java.util.Scanner;
public class GeradorDePotencia {
/**
* 034. Gerador de sequência: potências de 2
* Peça um número n e exiba as potências de 2 até 2^n.
* → Ex: Entrada: 5 → Saída: 1, 2, 4, 8, 16, 32
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = 1;
System.out.println("==== POTÊNCIA DE 2 ====");
System.out.print("Informe um número inteiro que representará até onde a sequência vai: ");
n = scanner.nextInt();
for (int i = 0; i <= n; i++) {
int resultado = (int) Math.pow(2, i); // Calcula 2^i
if (i == n) {
System.out.print(resultado); // Exibe sem a vírgula final
} else {
System.out.print(resultado + ", "); // Exibe com vírgula
}
}
scanner.close();
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
pitercoding/desafios-tecnicos-java | https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/018-TrianguloSimetrico/src/triangulo/simetrico/TrianguloSimétrico.java | nivel3/018-TrianguloSimetrico/src/triangulo/simetrico/TrianguloSimétrico.java | package triangulo.simetrico;
import java.util.Scanner;
public class TrianguloSimétrico {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Deseja uma pirâmide com quantas linhas? ");
int linhas = input.nextInt();
gerarTriangulo(linhas);
input.close();
}
public static void gerarTriangulo(int tamanho) {
int i = 0;
for (int linha = 1; linha <= tamanho; linha++) {
i++;
System.out.println(" ".repeat(tamanho - linha) + "*".repeat(i * 2 - 1) + " ".repeat(tamanho - linha));
}
}
}
| java | MIT | bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5 | 2026-01-05T02:38:06.070299Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.