file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
BadRequestException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/BadRequestException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; public class BadRequestException extends RuntimeException { public BadRequestException(String message) { super(message); } }
1,019
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
ErrorResponseException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/ErrorResponseException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; import de.adorsys.xs2a.adapter.api.ResponseHeaders; import de.adorsys.xs2a.adapter.api.model.ErrorResponse; import java.util.Optional; // Following error schemas don't have the body: // Error406_NG_PIS // Error408_NG_PIS // Error415_NG_PIS // Error429_NG_PIS // Error500_NG_PIS // Error503_NG_PIS public class ErrorResponseException extends RuntimeException { private final int statusCode; private final transient ResponseHeaders responseHeaders; private final transient ErrorResponse errorResponse; public ErrorResponseException(int statusCode, ResponseHeaders responseHeaders, ErrorResponse errorResponse, String response) { super(response); this.statusCode = statusCode; this.responseHeaders = responseHeaders; this.errorResponse = errorResponse; } public ErrorResponseException(int statusCode, ResponseHeaders responseHeaders, ErrorResponse errorResponse) { this(statusCode, responseHeaders, errorResponse, null); } public ErrorResponseException(int statusCode, ResponseHeaders responseHeaders) { this(statusCode, responseHeaders, null); } public int getStatusCode() { return statusCode; } public Optional<ErrorResponse> getErrorResponse() { return Optional.ofNullable(errorResponse); } public ResponseHeaders getResponseHeaders() { return responseHeaders; } }
2,385
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
Xs2aAdapterException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/Xs2aAdapterException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; public class Xs2aAdapterException extends RuntimeException { public Xs2aAdapterException(Throwable cause) { super(cause); } public Xs2aAdapterException(String message, Throwable cause) { super(message, cause); } }
1,125
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
OAuthException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/OAuthException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; import de.adorsys.xs2a.adapter.api.ResponseHeaders; import de.adorsys.xs2a.adapter.api.model.ErrorResponse; public class OAuthException extends RuntimeException { private final transient ResponseHeaders responseHeaders; private final transient ErrorResponse errorResponse; public OAuthException(ResponseHeaders responseHeaders, ErrorResponse errorResponse, String response) { super(response); this.responseHeaders = responseHeaders; this.errorResponse = errorResponse; } public ResponseHeaders getResponseHeaders() { return responseHeaders; } public ErrorResponse getErrorResponse() { return errorResponse; } }
1,565
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
AspspRegistrationNotFoundException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/AspspRegistrationNotFoundException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; public class AspspRegistrationNotFoundException extends AspspRegistrationException { public AspspRegistrationNotFoundException(String message) { super(message); } }
1,060
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
UncheckedSSLHandshakeException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/UncheckedSSLHandshakeException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; import javax.net.ssl.SSLHandshakeException; public class UncheckedSSLHandshakeException extends RuntimeException { public UncheckedSSLHandshakeException(SSLHandshakeException e) { super(e); } }
1,090
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
PsuPasswordEncodingException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/PsuPasswordEncodingException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; public class PsuPasswordEncodingException extends RuntimeException { public PsuPasswordEncodingException(String message) { super(message); } public PsuPasswordEncodingException(String message, Throwable cause) { super(message, cause); } }
1,151
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
IbanException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/IbanException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; public class IbanException extends RuntimeException { public IbanException(String message) { super(message); } }
1,007
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
HttpRequestSigningException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/HttpRequestSigningException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; public class HttpRequestSigningException extends RuntimeException { public HttpRequestSigningException(String message) { super(message); } public HttpRequestSigningException(Throwable cause) { super(cause); } }
1,123
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
AccessTokenException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/AccessTokenException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; public class AccessTokenException extends RuntimeException { private final Integer originalStatusCode; private final String originalMessage; private final boolean bankOriginator; public AccessTokenException(String message) { this(message, null, null, false); } public AccessTokenException(String message, Integer originalStatusCode, String originalMessage, Boolean bankOriginator) { super(message); this.originalStatusCode = originalStatusCode; this.originalMessage = originalMessage; this.bankOriginator = bankOriginator; } public Integer getOriginalStatusCode() { return originalStatusCode; } public String getOriginalMessage() { return originalMessage; } public boolean isBankOriginator() { return bankOriginator; } }
1,816
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
RequestAuthorizationValidationException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/RequestAuthorizationValidationException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; import de.adorsys.xs2a.adapter.api.RequestHeaders; import de.adorsys.xs2a.adapter.api.model.ErrorResponse; import de.adorsys.xs2a.adapter.api.validation.RequestValidationException; import de.adorsys.xs2a.adapter.api.validation.ValidationError; import java.util.Collections; public class RequestAuthorizationValidationException extends RequestValidationException { private final transient ErrorResponse errorResponse; public RequestAuthorizationValidationException(ErrorResponse errorResponse, String message) { super(Collections.singletonList(new ValidationError(ValidationError.Code.REQUIRED, RequestHeaders.AUTHORIZATION, message))); this.errorResponse = errorResponse; } public ErrorResponse getErrorResponse() { return errorResponse; } }
1,668
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
AspspRegistrationException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/AspspRegistrationException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; public class AspspRegistrationException extends RuntimeException { public AspspRegistrationException() { } public AspspRegistrationException(String message) { super(message); } public AspspRegistrationException(Throwable cause) { super(cause); } }
1,168
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
AdapterNotFoundException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/AdapterNotFoundException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; public class AdapterNotFoundException extends RuntimeException { private static final String MESSAGE = "Adapter with id [%s] is not found"; public AdapterNotFoundException(String adapterId) { super(String.format(MESSAGE, adapterId)); } }
1,137
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
NotAcceptableException.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/exception/NotAcceptableException.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.exception; public class NotAcceptableException extends RuntimeException { public NotAcceptableException(String message) { super(message); } }
1,026
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
EmbeddedPreAuthorisationRequest.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/model/EmbeddedPreAuthorisationRequest.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.model; public class EmbeddedPreAuthorisationRequest { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
1,289
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
Scope.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/model/Scope.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.model; import java.util.Arrays; import java.util.EnumSet; import java.util.Set; import java.util.stream.Collectors; public enum Scope { AIS("ais"), AIS_BALANCES("ais_balances"), AIS_TRANSACTIONS("ais_transactions"), PIS("pis"); private static final EnumSet<Scope> AIS_VALUES = EnumSet.of(AIS, AIS_BALANCES, AIS_TRANSACTIONS); private static final EnumSet<Scope> PIS_VALUES = EnumSet.of(PIS); private static final Set<String> VALUES = getValues(); private final String value; Scope(String value) { this.value = value; } public static Scope fromValue(String value) { for (Scope e : Scope.values()) { if (e.value.equals(value)) { return e; } } throw new IllegalArgumentException(value); } public static boolean isAis(Scope scope) { return AIS_VALUES.contains(scope); } public static boolean isPis(Scope scope) { return PIS_VALUES.contains(scope); } private static Set<String> getValues() { return Arrays.stream(Scope.values()) .map(scope -> scope.value) .collect(Collectors.toSet()); } public static boolean contains(String value) { return VALUES.contains(value); } @Override public String toString() { return value; } public String getValue() { return value; } }
2,296
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
TokenResponse.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/model/TokenResponse.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; public class TokenResponse { @JsonProperty("access_token") private String accessToken; @JsonProperty("token_type") private String tokenType; @JsonProperty("expires_in") private Long expiresInSeconds; @JsonProperty("refresh_token") private String refreshToken; private String scope; public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public String getTokenType() { return tokenType; } public void setTokenType(String tokenType) { this.tokenType = tokenType; } public Long getExpiresInSeconds() { return expiresInSeconds; } public void setExpiresInSeconds(Long expiresInSeconds) { this.expiresInSeconds = expiresInSeconds; } public String getRefreshToken() { return refreshToken; } public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TokenResponse that = (TokenResponse) o; return Objects.equals(accessToken, that.accessToken) && Objects.equals(tokenType, that.tokenType) && Objects.equals(expiresInSeconds, that.expiresInSeconds) && Objects.equals(refreshToken, that.refreshToken) && Objects.equals(scope, that.scope); } @Override public int hashCode() { return Objects.hash(accessToken, tokenType, expiresInSeconds, refreshToken, scope); } }
2,777
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
AspspScaApproach.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/model/AspspScaApproach.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.model; public enum AspspScaApproach { EMBEDDED, REDIRECT, DECOUPLED, OAUTH }
960
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
Aspsp.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/model/Aspsp.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.api.model; import java.util.List; import java.util.Objects; // all setters should treat an empty value as null public class Aspsp { private String id; private String name; private String bic; private String bankCode; private String url; private String adapterId; private String idpUrl; private List<AspspScaApproach> scaApproaches; private String paginationId; public String getId() { return id; } public void setId(String id) { this.id = emptyAsNull(id); } private String emptyAsNull(String s) { if (s == null || s.trim().isEmpty()) { return null; } return s; } public String getName() { return name; } public void setName(String name) { this.name = emptyAsNull(name); } public String getBic() { return bic; } public void setBic(String bic) { this.bic = emptyAsNull(bic); } public String getBankCode() { return bankCode; } public void setBankCode(String bankCode) { this.bankCode = emptyAsNull(bankCode); } public String getUrl() { return url; } public void setUrl(String url) { this.url = emptyAsNull(url); } public String getAdapterId() { return adapterId; } public void setAdapterId(String adapterId) { this.adapterId = emptyAsNull(adapterId); } public String getIdpUrl() { return idpUrl; } public void setIdpUrl(String idpUrl) { this.idpUrl = emptyAsNull(idpUrl); } public List<AspspScaApproach> getScaApproaches() { return scaApproaches; } public void setScaApproaches(List<AspspScaApproach> scaApproaches) { this.scaApproaches = emptyAsNull(scaApproaches); } private List<AspspScaApproach> emptyAsNull(List<AspspScaApproach> list) { if (list == null || list.isEmpty()) { return null; } return list; } public String getPaginationId() { return paginationId; } public void setPaginationId(String paginationId) { this.paginationId = paginationId; } @Override public String toString() { return "Aspsp{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", bic='" + bic + '\'' + ", bankCode='" + bankCode + '\'' + ", url='" + url + '\'' + ", adapterId='" + adapterId + '\'' + ", idpUrl='" + idpUrl + '\'' + ", scaApproaches=" + scaApproaches + ", paginationId='" + paginationId + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Aspsp aspsp = (Aspsp) o; return Objects.equals(name, aspsp.name) && Objects.equals(bic, aspsp.bic) && Objects.equals(bankCode, aspsp.bankCode) && Objects.equals(url, aspsp.url) && Objects.equals(adapterId, aspsp.adapterId) && Objects.equals(idpUrl, aspsp.idpUrl) && Objects.equals(scaApproaches, aspsp.scaApproaches); } @Override public int hashCode() { return Objects.hash(name, bic, bankCode, url, adapterId, idpUrl, scaApproaches); } }
4,352
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
PaymentControllerWebMvcTest.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-app/src/test/java/de/adorsys/xs2a/adapter/app/PaymentControllerWebMvcTest.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.app; import de.adorsys.xs2a.adapter.api.PaymentInitiationService; import de.adorsys.xs2a.adapter.mapper.HeadersMapper; import de.adorsys.xs2a.adapter.rest.impl.controller.PaymentController; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.startsWith; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ExtendWith(SpringExtension.class) @WebMvcTest(PaymentController.class) class PaymentControllerWebMvcTest { @Autowired private MockMvc mockMvc; @MockBean private PaymentInitiationService paymentService; @MockBean private HeadersMapper headersMapper; @Test void illegalPaymentService() throws Exception { mockMvc.perform(get("/v1/PAYMENTS/sepa-credit-transfers/id")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.tppMessages[0].text").value( startsWith("Illegal value 'PAYMENTS' for parameter 'payment-service', allowed values: payments,"))); } @Test void illegalPaymentProduct() throws Exception { mockMvc.perform(get("/v1/payments/SEPA-CREDIT-TRANSFERS/id")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.tppMessages[0].text").value( startsWith("Illegal value 'SEPA-CREDIT-TRANSFERS' for parameter 'payment-product', allowed values: sepa-credit-transfers,"))); } }
2,816
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
ConsentControllerWebMvcTest.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-app/src/test/java/de/adorsys/xs2a/adapter/app/ConsentControllerWebMvcTest.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.app; import de.adorsys.xs2a.adapter.api.AccountInformationService; import de.adorsys.xs2a.adapter.mapper.HeadersMapper; import de.adorsys.xs2a.adapter.rest.impl.controller.ConsentController; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ExtendWith(SpringExtension.class) @WebMvcTest(ConsentController.class) class ConsentControllerWebMvcTest { @Autowired private MockMvc mockMvc; @MockBean private AccountInformationService accountInformationService; @MockBean private HeadersMapper headersMapper; @Test void illegalBookingStatus() throws Exception { mockMvc.perform(get("/v1/accounts/resource-id/transactions").param("bookingStatus", "BOOKED")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.tppMessages[0].text") .value("Illegal value 'BOOKED' for parameter 'bookingStatus', allowed values: " + "information, booked, pending, both, all")); } }
2,457
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
WebConfigurationTest.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-app/src/test/java/de/adorsys/xs2a/adapter/app/config/WebConfigurationTest.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.app.config; import org.junit.jupiter.api.Test; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; class WebConfigurationTest { @Test void addInterceptors() { TestInterceptorRegistry registry = new TestInterceptorRegistry(); new WebConfiguration() { @Override public void addInterceptors(InterceptorRegistry interceptorRegistry) { super.addInterceptors(interceptorRegistry); } }.addInterceptors(registry); assertThat(registry.interceptors()).hasSize(1); assertThat(registry.interceptors().get(0)).isExactlyInstanceOf(AuditHandlerInterceptor.class); } private static class TestInterceptorRegistry extends InterceptorRegistry { public List<Object> interceptors() { return getInterceptors(); } } }
1,813
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
AuditRequestBodyAdviceTest.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-app/src/test/java/de/adorsys/xs2a/adapter/app/config/AuditRequestBodyAdviceTest.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.app.config; import de.adorsys.xs2a.adapter.api.AccountInformationService; import de.adorsys.xs2a.adapter.api.RequestHeaders; import de.adorsys.xs2a.adapter.api.RequestParams; import de.adorsys.xs2a.adapter.api.model.AccountAccess; import de.adorsys.xs2a.adapter.api.model.AccountReference; import de.adorsys.xs2a.adapter.api.model.Consents; import org.junit.jupiter.api.Test; import org.slf4j.MDC; import org.springframework.core.MethodParameter; import java.lang.reflect.Method; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; class AuditRequestBodyAdviceTest { private final MethodParameter methodParameter = mock(MethodParameter.class); private final AuditRequestBodyAdvice advice = new AuditRequestBodyAdvice(); @Test void supportsMethodIsNull() { AuditRequestBodyAdvice advice = new AuditRequestBodyAdvice(); boolean supports = advice.supports(methodParameter, null, null); assertThat(supports).isFalse(); } @Test void supportsMethodIsDifferent() throws NoSuchMethodException { Method method = AccountInformationService.class.getMethod("getConsentStatus", String.class, RequestHeaders.class, RequestParams.class); doReturn(method).when(methodParameter).getMethod(); boolean supports = advice.supports(methodParameter, null, null); assertThat(supports).isFalse(); method = AccountInformationService.class.getMethod("createConsent", RequestHeaders.class, RequestParams.class, Consents.class); doReturn(method).when(methodParameter).getMethod(); supports = advice.supports(methodParameter, null, null); assertThat(supports).isTrue(); } @Test void supports() throws NoSuchMethodException { AuditRequestBodyAdvice advice = new AuditRequestBodyAdvice(); Method method = AccountInformationService.class.getMethod("createConsent", RequestHeaders.class, RequestParams.class, Consents.class); doReturn(method).when(methodParameter).getMethod(); boolean supports = advice.supports(methodParameter, null, null); assertThat(supports).isTrue(); } @Test void afterBodyReadGetIbanAndDetailsConsent() { String iban1 = "account-iban"; String iban2 = "balance-iban"; String iban3 = "trx-iban"; Consents consents = new Consents(); consents.setAccess(buildAccess(iban1, iban2, iban3)); advice.afterBodyRead(consents, null, null, null, null); String ibans = MDC.get("iban"); assertThat(ibans) .contains(iban1) .contains(iban2) .contains(iban3); assertThat(MDC.get("consentModel")).isEqualTo("detailed"); } @Test void afterBodyReadConsentModelBankOffered() { Consents consents = new Consents(); consents.setAccess(new AccountAccess()); advice.afterBodyRead(consents, null, null, null, null); assertThat(MDC.get("consentModel")).contains("bank-offered"); } @Test void afterBodyReadConsentModelGlobal() { Consents consents = new Consents(); AccountAccess access = new AccountAccess(); access.setAllPsd2(AccountAccess.AllPsd2.ALLACCOUNTS); consents.setAccess(access); advice.afterBodyRead(consents, null, null, null, null); assertThat(MDC.get("consentModel")).contains("global"); } @Test void afterBodyReadConsentModelUnknown() { advice.afterBodyRead(new Consents(), null, null, null, null); assertThat(MDC.get("consentModel")).contains("unknown"); } @Test void afterBodyReadDifferentObject() { MDC.clear(); advice.afterBodyRead(new Object(), null, null, null, null); assertThat(MDC.get("ibans")).isNull(); assertThat(MDC.get("consentModel")).isNull(); } private AccountReference buildReference(String iban) { AccountReference accounts = new AccountReference(); accounts.setIban(iban); return accounts; } private AccountAccess buildAccess(String accIban, String blncIban, String trxIban) { AccountAccess accountAccess = new AccountAccess(); accountAccess.setAccounts(Collections.singletonList(buildReference(accIban))); accountAccess.setBalances(Collections.singletonList(buildReference(blncIban))); accountAccess.setTransactions(Collections.singletonList(buildReference(trxIban))); return accountAccess; } }
6,033
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
AuditHandlerInterceptorTest.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-app/src/test/java/de/adorsys/xs2a/adapter/app/config/AuditHandlerInterceptorTest.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.app.config; import de.adorsys.xs2a.adapter.api.RequestHeaders; import de.adorsys.xs2a.adapter.api.ResponseHeaders; import org.junit.jupiter.api.Test; import org.slf4j.MDC; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; class AuditHandlerInterceptorTest { private static final String URI = "/v1/accounts/E9A850CBB0D24C98A612C6209AF54E2B/transactions"; private static final String METHOD = "GET"; private static final String OPERATION = "operation"; private final HttpServletRequest request = mock(HttpServletRequest.class); private final AuditHandlerInterceptor interceptor = new AuditHandlerInterceptor(); @Test void preHandleSanitized() { AuditHandlerInterceptor interceptor = new AuditHandlerInterceptor(true); HttpServletResponse response = mock(HttpServletResponse.class); doReturn(URI).when(request).getRequestURI(); doReturn(METHOD).when(request).getMethod(); interceptor.preHandle(request, response, new Object()); assertThat(MDC.get(OPERATION)).isEqualTo(METHOD + " /v1/accounts/******/transactions"); } @Test void preHandleNotSanitized() { HttpServletResponse response = mock(HttpServletResponse.class); doReturn(URI).when(request).getRequestURI(); doReturn(METHOD).when(request).getMethod(); interceptor.preHandle(request, response, new Object()); assertThat(MDC.get(OPERATION)).isEqualTo(METHOD + " " + URI); } @Test void preHandle() { String uri = "/request/uri"; String method = "GET"; String correlationId = "correlation-id"; String bankCode = "bank-code"; String aspsId = "aspsp-id"; doReturn(uri).when(request).getRequestURI(); doReturn(method).when(request).getMethod(); doReturn(correlationId).when(request).getHeader(RequestHeaders.CORRELATION_ID); doReturn(bankCode).when(request).getHeader(RequestHeaders.X_GTW_BANK_CODE); doReturn(aspsId).when(request).getHeader(RequestHeaders.X_GTW_ASPSP_ID); boolean preHandle = interceptor.preHandle(request, null, null); assertThat(preHandle).isTrue(); assertThat(MDC.get("operation")).isEqualTo(method + " " + uri); assertThat(MDC.get("correlationId")).isEqualTo(correlationId); assertThat(MDC.get("bankCode")).isEqualTo(bankCode); assertThat(MDC.get("aspspId")).isEqualTo(aspsId); } @Test void afterCompletion() { String approach = "approach"; HttpServletResponse response = mock(HttpServletResponse.class); doReturn(approach).when(response).getHeader(ResponseHeaders.ASPSP_SCA_APPROACH); interceptor.afterCompletion(request, response, null, null); verify(response, times(1)).getHeader(ResponseHeaders.ASPSP_SCA_APPROACH); assertThat(MDC.getCopyOfContextMap()).isNull(); } }
3,896
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
Xs2aAdapterApplication.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-app/src/main/java/de/adorsys/xs2a/adapter/app/Xs2aAdapterApplication.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages = "de.adorsys.xs2a.adapter") public class Xs2aAdapterApplication { public static void main(String[] args) { SpringApplication.run(Xs2aAdapterApplication.class, args); } }
1,216
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
AuditRequestBodyAdvice.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-app/src/main/java/de/adorsys/xs2a/adapter/app/config/AuditRequestBodyAdvice.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.app.config; import de.adorsys.xs2a.adapter.api.model.AccountAccess; import de.adorsys.xs2a.adapter.api.model.AccountReference; import de.adorsys.xs2a.adapter.api.model.Consents; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.core.MethodParameter; import org.springframework.http.HttpInputMessage; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.HashSet; import java.util.List; import java.util.Set; import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toSet; @ControllerAdvice public class AuditRequestBodyAdvice extends RequestBodyAdviceAdapter { private static final Logger logger = LoggerFactory.getLogger(AuditRequestBodyAdvice.class); @Override public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) { Method method = methodParameter.getMethod(); if (method == null) { return false; } return "createConsent".equals(method.getName()); } @Override public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) { if (body instanceof Consents) { Consents consents = (Consents) body; MDC.put("iban", getIbans(consents).toString()); MDC.put("consentModel", getModel(consents)); } else { logger.warn("Unexpected body type {} for create consent", body.getClass()); } return body; } private Set<String> getIbans(Consents consents) { Set<String> ibans = new HashSet<>(); AccountAccess access = consents.getAccess(); if (access != null) { ibans.addAll(getIbans(access.getAccounts())); ibans.addAll(getIbans(access.getBalances())); ibans.addAll(getIbans(access.getTransactions())); } return ibans; } private Set<String> getIbans(List<AccountReference> accountRefs) { if (accountRefs == null || accountRefs.isEmpty()) { return emptySet(); } return accountRefs.stream() .map(AccountReference::getIban) .collect(toSet()); } private String getModel(Consents consents) { AccountAccess access = consents.getAccess(); if (access != null) { if (access.getAllPsd2() == AccountAccess.AllPsd2.ALLACCOUNTS) { return "global"; } if ((access.getAccounts() == null || access.getAccounts().isEmpty()) && (access.getBalances() == null || access.getBalances().isEmpty()) && (access.getTransactions() == null || access.getTransactions().isEmpty())) { return "bank-offered"; } return "detailed"; } return "unknown"; } }
4,247
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
RestConfiguration.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-app/src/main/java/de/adorsys/xs2a/adapter/app/config/RestConfiguration.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.app.config; import de.adorsys.xs2a.adapter.api.*; import de.adorsys.xs2a.adapter.api.http.HttpClientConfig; import de.adorsys.xs2a.adapter.api.http.HttpClientFactory; import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer; import de.adorsys.xs2a.adapter.api.link.LinksRewriter; import de.adorsys.xs2a.adapter.impl.http.ApacheHttpClientFactory; import de.adorsys.xs2a.adapter.impl.http.BaseHttpClientConfig; import de.adorsys.xs2a.adapter.impl.http.Xs2aHttpLogSanitizer; import de.adorsys.xs2a.adapter.impl.http.wiremock.WiremockHttpClientFactory; import de.adorsys.xs2a.adapter.impl.link.identity.IdentityLinksRewriter; import de.adorsys.xs2a.adapter.registry.LuceneAspspRepositoryFactory; import de.adorsys.xs2a.adapter.serviceloader.*; import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import java.io.IOException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.List; @Configuration public class RestConfiguration { @Value("${xs2a-adapter.loader.choose-first-from-multiple-aspsps:false}") private boolean chooseFirstFromMultipleAspsps; @Value("${xs2a-adapter.wire-mock.mode:false}") private boolean wireMockEnabled; @Value("${xs2a-adapter.sanitizer.whitelist}") private List<String> sanitizerWhitelist; @Value("${xs2a-adapter.wire-mock.validation.enabled:false}") private boolean wiremockValidationEnabled; @Value("${xs2a-adapter.wire-mock.standalone.url:}") private String wiremockStandaloneUrl; @Bean HttpLogSanitizer xs2aHttpLogSanitizer() { return new Xs2aHttpLogSanitizer(sanitizerWhitelist); } @Bean HttpClientConfig httpClientConfig(HttpLogSanitizer logSanitizer, Pkcs12KeyStore keyStore) { return new BaseHttpClientConfig(logSanitizer, keyStore, wiremockStandaloneUrl); } @Bean PaymentInitiationService paymentInitiationService(AdapterServiceLoader adapterServiceLoader) { return new PaymentInitiationServiceImpl(adapterServiceLoader); } @Bean AccountInformationService accountInformationService(AdapterServiceLoader adapterServiceLoader) { return new AccountInformationServiceImpl(adapterServiceLoader); } @Bean AdapterServiceLoader adapterServiceLoader(LinksRewriter accountInformationLinksRewriter, LinksRewriter paymentInitiationLinksRewriter, HttpClientFactory httpClientFactory) { return new AdapterServiceLoader(aspspRepository(), httpClientFactory, accountInformationLinksRewriter, paymentInitiationLinksRewriter, chooseFirstFromMultipleAspsps, wiremockValidationEnabled); } @Bean LinksRewriter accountInformationLinksRewriter() { return new IdentityLinksRewriter(); } @Bean LinksRewriter paymentInitiationLinksRewriter() { return new IdentityLinksRewriter(); } @Bean HttpClientFactory httpClientFactory(HttpClientBuilder httpClientBuilder, HttpClientConfig clientConfig) { return wireMockEnabled ? new WiremockHttpClientFactory(httpClientBuilder, clientConfig) : new ApacheHttpClientFactory(httpClientBuilder, clientConfig); } @Bean @Profile("!dev") HttpClientBuilder httpClientBuilder() { return httpClientBuilderWithSharedConfiguration(); } @Bean @Profile("dev") HttpClientBuilder httpClientBuilderWithDisabledCompression() { return httpClientBuilderWithSharedConfiguration() .disableContentCompression(); } private HttpClientBuilder httpClientBuilderWithSharedConfiguration() { return HttpClientBuilder.create() .disableDefaultUserAgent(); } @Bean AspspRepository aspspRepository() { return new LuceneAspspRepositoryFactory().newLuceneAspspRepository(); } @Bean Oauth2Service oauth2Service(AdapterServiceLoader adapterServiceLoader) { return new AdapterDelegatingOauth2Service(adapterServiceLoader); } @Bean Pkcs12KeyStore pkcs12KeyStore() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { char[] keyStorePassword = System.getProperty("pkcs12.keyStorePassword", "").toCharArray(); return new Pkcs12KeyStore(System.getProperty("pkcs12.keyStore"), keyStorePassword); } @Bean DownloadService downloadService(AdapterServiceLoader adapterServiceLoader) { return new DownloadServiceImpl(adapterServiceLoader); } @Bean EmbeddedPreAuthorisationService embeddedPreAuthorisationService(AdapterServiceLoader adapterServiceLoader) { return new EmbeddedPreAuthorisationServiceImpl(adapterServiceLoader); } }
5,952
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
AuditHandlerInterceptor.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-app/src/main/java/de/adorsys/xs2a/adapter/app/config/AuditHandlerInterceptor.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.app.config; import de.adorsys.xs2a.adapter.api.RequestHeaders; import de.adorsys.xs2a.adapter.api.ResponseHeaders; import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer; import de.adorsys.xs2a.adapter.impl.http.Xs2aHttpLogSanitizer; import org.slf4j.MDC; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AuditHandlerInterceptor extends HandlerInterceptorAdapter { private final HttpLogSanitizer logSanitizer = new Xs2aHttpLogSanitizer(); private final boolean sanitized; public AuditHandlerInterceptor() { this(false); } public AuditHandlerInterceptor(boolean sanitized) { this.sanitized = sanitized; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { String uri = request.getRequestURI(); String requestURI = sanitized ? logSanitizer.sanitize(uri) : uri; MDC.put("operation", request.getMethod() + " " + requestURI); String correlationId = request.getHeader(RequestHeaders.CORRELATION_ID); if (correlationId != null) { MDC.put("correlationId", correlationId); } String bankCode = request.getHeader(RequestHeaders.X_GTW_BANK_CODE); if (bankCode != null) { MDC.put("bankCode", bankCode); } String aspspId = request.getHeader(RequestHeaders.X_GTW_ASPSP_ID); if (aspspId != null) { MDC.put("aspspId", aspspId); } return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { String approach = response.getHeader(ResponseHeaders.ASPSP_SCA_APPROACH); if (approach != null) { MDC.put("approach", approach); } MDC.clear(); } }
2,825
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
WebConfiguration.java
/FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-app/src/main/java/de/adorsys/xs2a/adapter/app/config/WebConfiguration.java
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.app.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfiguration implements WebMvcConfigurer { @Value("${xs2a-adapter.audit.sanitized:true}") private boolean auditSanitized; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new AuditHandlerInterceptor(auditSanitized)); } }
1,477
Java
.java
adorsys/xs2a-adapter
37
25
5
2019-04-01T09:31:44Z
2024-03-09T08:27:14Z
PNGImageWriterBackportTest.java
/FileExtraction/Java_unseen/gredler_jdk9-png-writer-backport/src/test/java/com/sun/imageio/plugins/png/PNGImageWriterBackportTest.java
package com.sun.imageio.plugins.png; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Iterator; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; import javax.imageio.stream.MemoryCacheImageOutputStream; import org.junit.Test; public class PNGImageWriterBackportTest { @Test public void testPrecedence() { Iterator< ImageWriter > writer = ImageIO.getImageWritersByFormatName("png"); assertTrue(writer.next() instanceof PNGImageWriterBackport); assertTrue(writer.next() instanceof PNGImageWriter); } @Test public void testCompressionLevels() throws IOException { BufferedImage img = ImageIO.read(getClass().getResourceAsStream("placeholder-text.gif")); byte[] bd = toPng(img, null); // default byte[] b00 = toPng(img, 0.0f); // highest compression, slowest byte[] b01 = toPng(img, 0.1f); byte[] b02 = toPng(img, 0.2f); byte[] b03 = toPng(img, 0.3f); byte[] b04 = toPng(img, 0.4f); byte[] b05 = toPng(img, 0.5f); byte[] b06 = toPng(img, 0.6f); byte[] b07 = toPng(img, 0.7f); byte[] b08 = toPng(img, 0.8f); byte[] b09 = toPng(img, 0.9f); byte[] b10 = toPng(img, 1.0f); // lowest compression, fastest assertArrayEquals(bd, b05); assertArrayEquals(bd, b06); assertTrue(b00.length < b01.length); assertTrue(b01.length < b02.length); assertTrue(b02.length < b03.length); assertTrue(b03.length < b04.length); assertTrue(b04.length < b05.length); assertTrue(b05.length == b06.length); assertTrue(b06.length < b07.length); assertTrue(b07.length < b08.length); assertTrue(b08.length < b09.length); assertTrue(b09.length < b10.length); } private byte[] toPng(BufferedImage img, Float compressionQuality) throws IOException { ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next(); ImageWriteParam writeParam = writer.getDefaultWriteParam(); if (compressionQuality != null) { writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); writeParam.setCompressionQuality(compressionQuality); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream stream = new MemoryCacheImageOutputStream(baos); try { writer.setOutput(stream); writer.write(null, new IIOImage(img, null, null), writeParam); } finally { stream.close(); writer.dispose(); } return baos.toByteArray(); } }
2,914
Java
.java
gredler/jdk9-png-writer-backport
13
2
0
2016-05-19T04:15:31Z
2016-05-19T06:25:34Z
PNGImageWriterBackport.java
/FileExtraction/Java_unseen/gredler_jdk9-png-writer-backport/src/main/java/com/sun/imageio/plugins/png/PNGImageWriterBackport.java
/* * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.imageio.plugins.png; import java.awt.Rectangle; import java.awt.image.IndexColorModel; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.SampleModel; import java.awt.image.WritableRaster; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.Locale; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import javax.imageio.IIOException; import javax.imageio.IIOImage; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageWriterSpi; import javax.imageio.stream.ImageOutputStream; import javax.imageio.stream.ImageOutputStreamImpl; final class CRCBackport { private static final int[] crcTable = new int[256]; private int crc = 0xffffffff; static { // Initialize CRC table for (int n = 0; n < 256; n++) { int c = n; for (int k = 0; k < 8; k++) { if ((c & 1) == 1) { c = 0xedb88320 ^ (c >>> 1); } else { c >>>= 1; } crcTable[n] = c; } } } CRCBackport() {} void reset() { crc = 0xffffffff; } void update(byte[] data, int off, int len) { int c = crc; for (int n = 0; n < len; n++) { c = crcTable[(c ^ data[off + n]) & 0xff] ^ (c >>> 8); } crc = c; } void update(int data) { crc = crcTable[(crc ^ data) & 0xff] ^ (crc >>> 8); } int getValue() { return crc ^ 0xffffffff; } } final class ChunkStreamBackport extends ImageOutputStreamImpl { private final ImageOutputStream stream; private final long startPos; private final CRCBackport crc = new CRCBackport(); ChunkStreamBackport(int type, ImageOutputStream stream) throws IOException { this.stream = stream; this.startPos = stream.getStreamPosition(); stream.writeInt(-1); // length, will backpatch writeInt(type); } @Override public int read() throws IOException { throw new RuntimeException("Method not available"); } @Override public int read(byte[] b, int off, int len) throws IOException { throw new RuntimeException("Method not available"); } @Override public void write(byte[] b, int off, int len) throws IOException { crc.update(b, off, len); stream.write(b, off, len); } @Override public void write(int b) throws IOException { crc.update(b); stream.write(b); } void finish() throws IOException { // Write CRC stream.writeInt(crc.getValue()); // Write length long pos = stream.getStreamPosition(); stream.seek(startPos); stream.writeInt((int)(pos - startPos) - 12); // Return to end of chunk and flush to minimize buffering stream.seek(pos); stream.flushBefore(pos); } @Override protected void finalize() throws Throwable { // Empty finalizer (for improved performance; no need to call // super.finalize() in this case) } } // Compress output and write as a series of 'IDAT' chunks of // fixed length. final class IDATOutputStreamBackport extends ImageOutputStreamImpl { private static final byte[] chunkType = { (byte)'I', (byte)'D', (byte)'A', (byte)'T' }; private final ImageOutputStream stream; private final int chunkLength; private long startPos; private final CRCBackport crc = new CRCBackport(); private final Deflater def; private final byte[] buf = new byte[512]; // reused 1 byte[] array: private final byte[] wbuf1 = new byte[1]; private int bytesRemaining; IDATOutputStreamBackport(ImageOutputStream stream, int chunkLength, int deflaterLevel) throws IOException { this.stream = stream; this.chunkLength = chunkLength; this.def = new Deflater(deflaterLevel); startChunk(); } private void startChunk() throws IOException { crc.reset(); this.startPos = stream.getStreamPosition(); stream.writeInt(-1); // length, will backpatch crc.update(chunkType, 0, 4); stream.write(chunkType, 0, 4); this.bytesRemaining = chunkLength; } private void finishChunk() throws IOException { // Write CRC stream.writeInt(crc.getValue()); // Write length long pos = stream.getStreamPosition(); stream.seek(startPos); stream.writeInt((int)(pos - startPos) - 12); // Return to end of chunk and flush to minimize buffering stream.seek(pos); try { stream.flushBefore(pos); } catch (IOException e) { /* * If flushBefore() fails we try to access startPos in finally * block of write_IDAT(). We should update startPos to avoid * IndexOutOfBoundException while seek() is happening. */ this.startPos = stream.getStreamPosition(); throw e; } } @Override public int read() throws IOException { throw new RuntimeException("Method not available"); } @Override public int read(byte[] b, int off, int len) throws IOException { throw new RuntimeException("Method not available"); } @Override public void write(byte[] b, int off, int len) throws IOException { if (len == 0) { return; } if (!def.finished()) { def.setInput(b, off, len); while (!def.needsInput()) { deflate(); } } } void deflate() throws IOException { int len = def.deflate(buf, 0, buf.length); int off = 0; while (len > 0) { if (bytesRemaining == 0) { finishChunk(); startChunk(); } int nbytes = Math.min(len, bytesRemaining); crc.update(buf, off, nbytes); stream.write(buf, off, nbytes); off += nbytes; len -= nbytes; bytesRemaining -= nbytes; } } @Override public void write(int b) throws IOException { wbuf1[0] = (byte)b; write(wbuf1, 0, 1); } void finish() throws IOException { try { if (!def.finished()) { def.finish(); while (!def.finished()) { deflate(); } } finishChunk(); } finally { def.end(); } } @Override protected void finalize() throws Throwable { // Empty finalizer (for improved performance; no need to call // super.finalize() in this case) } } final class PNGImageWriteParamBackport extends ImageWriteParam { /** Default quality level = 0.5 ie medium compression */ private static final float DEFAULT_QUALITY = 0.5f; private static final String[] compressionNames = {"Deflate"}; private static final float[] qualityVals = { 0.00F, 0.30F, 0.75F, 1.00F }; private static final String[] qualityDescs = { "High compression", // 0.00 -> 0.30 "Medium compression", // 0.30 -> 0.75 "Low compression" // 0.75 -> 1.00 }; PNGImageWriteParamBackport(Locale locale) { super(); this.canWriteProgressive = true; this.locale = locale; this.canWriteCompressed = true; this.compressionTypes = compressionNames; this.compressionType = compressionTypes[0]; this.compressionMode = MODE_DEFAULT; this.compressionQuality = DEFAULT_QUALITY; } /** * Removes any previous compression quality setting. * * <p> The default implementation resets the compression quality * to <code>0.5F</code>. * * @exception IllegalStateException if the compression mode is not * <code>MODE_EXPLICIT</code>. */ @Override public void unsetCompression() { super.unsetCompression(); this.compressionType = compressionTypes[0]; this.compressionQuality = DEFAULT_QUALITY; } /** * Returns <code>true</code> since the PNG plug-in only supports * lossless compression. * * @return <code>true</code>. */ @Override public boolean isCompressionLossless() { return true; } @Override public String[] getCompressionQualityDescriptions() { super.getCompressionQualityDescriptions(); return qualityDescs.clone(); } @Override public float[] getCompressionQualityValues() { super.getCompressionQualityValues(); return qualityVals.clone(); } } /** */ public final class PNGImageWriterBackport extends ImageWriter { /** Default compression level = 4 ie medium compression */ private static final int DEFAULT_COMPRESSION_LEVEL = 4; ImageOutputStream stream = null; PNGMetadata metadata = null; // Factors from the ImageWriteParam int sourceXOffset = 0; int sourceYOffset = 0; int sourceWidth = 0; int sourceHeight = 0; int[] sourceBands = null; int periodX = 1; int periodY = 1; int numBands; int bpp; RowFilter rowFilter = new RowFilter(); byte[] prevRow = null; byte[] currRow = null; byte[][] filteredRows = null; // Per-band scaling tables // // After the first call to initializeScaleTables, either scale and scale0 // will be valid, or scaleh and scalel will be valid, but not both. // // The tables will be designed for use with a set of input but depths // given by sampleSize, and an output bit depth given by scalingBitDepth. // int[] sampleSize = null; // Sample size per band, in bits int scalingBitDepth = -1; // Output bit depth of the scaling tables // Tables for 1, 2, 4, or 8 bit output byte[][] scale = null; // 8 bit table byte[] scale0 = null; // equivalent to scale[0] // Tables for 16 bit output byte[][] scaleh = null; // High bytes of output byte[][] scalel = null; // Low bytes of output int totalPixels; // Total number of pixels to be written by write_IDAT int pixelsDone; // Running count of pixels written by write_IDAT public PNGImageWriterBackport(ImageWriterSpi originatingProvider) { super(originatingProvider); } @Override public void setOutput(Object output) { super.setOutput(output); if (output != null) { if (!(output instanceof ImageOutputStream)) { throw new IllegalArgumentException("output not an ImageOutputStream!"); } this.stream = (ImageOutputStream)output; } else { this.stream = null; } } @Override public ImageWriteParam getDefaultWriteParam() { return new PNGImageWriteParamBackport(getLocale()); } @Override public IIOMetadata getDefaultStreamMetadata(ImageWriteParam param) { return null; } @Override public IIOMetadata getDefaultImageMetadata(ImageTypeSpecifier imageType, ImageWriteParam param) { PNGMetadata m = new PNGMetadata(); m.initialize(imageType, imageType.getSampleModel().getNumBands()); return m; } @Override public IIOMetadata convertStreamMetadata(IIOMetadata inData, ImageWriteParam param) { return null; } @Override public IIOMetadata convertImageMetadata(IIOMetadata inData, ImageTypeSpecifier imageType, ImageWriteParam param) { // TODO - deal with imageType if (inData instanceof PNGMetadata) { return (PNGMetadata)((PNGMetadata)inData).clone(); } else { return new PNGMetadata(inData); } } private void write_magic() throws IOException { // Write signature byte[] magic = { (byte)137, 80, 78, 71, 13, 10, 26, 10 }; stream.write(magic); } private void write_IHDR() throws IOException { // Write IHDR chunk ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.IHDR_TYPE, stream); cs.writeInt(metadata.IHDR_width); cs.writeInt(metadata.IHDR_height); cs.writeByte(metadata.IHDR_bitDepth); cs.writeByte(metadata.IHDR_colorType); if (metadata.IHDR_compressionMethod != 0) { throw new IIOException( "Only compression method 0 is defined in PNG 1.1"); } cs.writeByte(metadata.IHDR_compressionMethod); if (metadata.IHDR_filterMethod != 0) { throw new IIOException( "Only filter method 0 is defined in PNG 1.1"); } cs.writeByte(metadata.IHDR_filterMethod); if (metadata.IHDR_interlaceMethod < 0 || metadata.IHDR_interlaceMethod > 1) { throw new IIOException( "Only interlace methods 0 (node) and 1 (adam7) are defined in PNG 1.1"); } cs.writeByte(metadata.IHDR_interlaceMethod); cs.finish(); } private void write_cHRM() throws IOException { if (metadata.cHRM_present) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.cHRM_TYPE, stream); cs.writeInt(metadata.cHRM_whitePointX); cs.writeInt(metadata.cHRM_whitePointY); cs.writeInt(metadata.cHRM_redX); cs.writeInt(metadata.cHRM_redY); cs.writeInt(metadata.cHRM_greenX); cs.writeInt(metadata.cHRM_greenY); cs.writeInt(metadata.cHRM_blueX); cs.writeInt(metadata.cHRM_blueY); cs.finish(); } } private void write_gAMA() throws IOException { if (metadata.gAMA_present) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.gAMA_TYPE, stream); cs.writeInt(metadata.gAMA_gamma); cs.finish(); } } private void write_iCCP() throws IOException { if (metadata.iCCP_present) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.iCCP_TYPE, stream); cs.writeBytes(metadata.iCCP_profileName); cs.writeByte(0); // null terminator cs.writeByte(metadata.iCCP_compressionMethod); cs.write(metadata.iCCP_compressedProfile); cs.finish(); } } private void write_sBIT() throws IOException { if (metadata.sBIT_present) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.sBIT_TYPE, stream); int colorType = metadata.IHDR_colorType; if (metadata.sBIT_colorType != colorType) { processWarningOccurred(0, "sBIT metadata has wrong color type.\n" + "The chunk will not be written."); return; } if (colorType == PNGImageReader.PNG_COLOR_GRAY || colorType == PNGImageReader.PNG_COLOR_GRAY_ALPHA) { cs.writeByte(metadata.sBIT_grayBits); } else if (colorType == PNGImageReader.PNG_COLOR_RGB || colorType == PNGImageReader.PNG_COLOR_PALETTE || colorType == PNGImageReader.PNG_COLOR_RGB_ALPHA) { cs.writeByte(metadata.sBIT_redBits); cs.writeByte(metadata.sBIT_greenBits); cs.writeByte(metadata.sBIT_blueBits); } if (colorType == PNGImageReader.PNG_COLOR_GRAY_ALPHA || colorType == PNGImageReader.PNG_COLOR_RGB_ALPHA) { cs.writeByte(metadata.sBIT_alphaBits); } cs.finish(); } } private void write_sRGB() throws IOException { if (metadata.sRGB_present) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.sRGB_TYPE, stream); cs.writeByte(metadata.sRGB_renderingIntent); cs.finish(); } } private void write_PLTE() throws IOException { if (metadata.PLTE_present) { if (metadata.IHDR_colorType == PNGImageReader.PNG_COLOR_GRAY || metadata.IHDR_colorType == PNGImageReader.PNG_COLOR_GRAY_ALPHA) { // PLTE cannot occur in a gray image processWarningOccurred(0, "A PLTE chunk may not appear in a gray or gray alpha image.\n" + "The chunk will not be written"); return; } ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.PLTE_TYPE, stream); int numEntries = metadata.PLTE_red.length; byte[] palette = new byte[numEntries*3]; int index = 0; for (int i = 0; i < numEntries; i++) { palette[index++] = metadata.PLTE_red[i]; palette[index++] = metadata.PLTE_green[i]; palette[index++] = metadata.PLTE_blue[i]; } cs.write(palette); cs.finish(); } } private void write_hIST() throws IOException, IIOException { if (metadata.hIST_present) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.hIST_TYPE, stream); if (!metadata.PLTE_present) { throw new IIOException("hIST chunk without PLTE chunk!"); } cs.writeChars(metadata.hIST_histogram, 0, metadata.hIST_histogram.length); cs.finish(); } } private void write_tRNS() throws IOException, IIOException { if (metadata.tRNS_present) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.tRNS_TYPE, stream); int colorType = metadata.IHDR_colorType; int chunkType = metadata.tRNS_colorType; // Special case: image is RGB and chunk is Gray // Promote chunk contents to RGB int chunkRed = metadata.tRNS_red; int chunkGreen = metadata.tRNS_green; int chunkBlue = metadata.tRNS_blue; if (colorType == PNGImageReader.PNG_COLOR_RGB && chunkType == PNGImageReader.PNG_COLOR_GRAY) { chunkType = colorType; chunkRed = chunkGreen = chunkBlue = metadata.tRNS_gray; } if (chunkType != colorType) { processWarningOccurred(0, "tRNS metadata has incompatible color type.\n" + "The chunk will not be written."); return; } if (colorType == PNGImageReader.PNG_COLOR_PALETTE) { if (!metadata.PLTE_present) { throw new IIOException("tRNS chunk without PLTE chunk!"); } cs.write(metadata.tRNS_alpha); } else if (colorType == PNGImageReader.PNG_COLOR_GRAY) { cs.writeShort(metadata.tRNS_gray); } else if (colorType == PNGImageReader.PNG_COLOR_RGB) { cs.writeShort(chunkRed); cs.writeShort(chunkGreen); cs.writeShort(chunkBlue); } else { throw new IIOException("tRNS chunk for color type 4 or 6!"); } cs.finish(); } } private void write_bKGD() throws IOException { if (metadata.bKGD_present) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.bKGD_TYPE, stream); int colorType = metadata.IHDR_colorType & 0x3; int chunkType = metadata.bKGD_colorType; // Special case: image is RGB(A) and chunk is Gray // Promote chunk contents to RGB int chunkRed = metadata.bKGD_red; int chunkGreen = metadata.bKGD_red; int chunkBlue = metadata.bKGD_red; if (colorType == PNGImageReader.PNG_COLOR_RGB && chunkType == PNGImageReader.PNG_COLOR_GRAY) { // Make a gray bKGD chunk look like RGB chunkType = colorType; chunkRed = chunkGreen = chunkBlue = metadata.bKGD_gray; } // Ignore status of alpha in colorType if (chunkType != colorType) { processWarningOccurred(0, "bKGD metadata has incompatible color type.\n" + "The chunk will not be written."); return; } if (colorType == PNGImageReader.PNG_COLOR_PALETTE) { cs.writeByte(metadata.bKGD_index); } else if (colorType == PNGImageReader.PNG_COLOR_GRAY || colorType == PNGImageReader.PNG_COLOR_GRAY_ALPHA) { cs.writeShort(metadata.bKGD_gray); } else { // colorType == PNGImageReader.PNG_COLOR_RGB || // colorType == PNGImageReader.PNG_COLOR_RGB_ALPHA cs.writeShort(chunkRed); cs.writeShort(chunkGreen); cs.writeShort(chunkBlue); } cs.finish(); } } private void write_pHYs() throws IOException { if (metadata.pHYs_present) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.pHYs_TYPE, stream); cs.writeInt(metadata.pHYs_pixelsPerUnitXAxis); cs.writeInt(metadata.pHYs_pixelsPerUnitYAxis); cs.writeByte(metadata.pHYs_unitSpecifier); cs.finish(); } } private void write_sPLT() throws IOException { if (metadata.sPLT_present) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.sPLT_TYPE, stream); cs.writeBytes(metadata.sPLT_paletteName); cs.writeByte(0); // null terminator cs.writeByte(metadata.sPLT_sampleDepth); int numEntries = metadata.sPLT_red.length; if (metadata.sPLT_sampleDepth == 8) { for (int i = 0; i < numEntries; i++) { cs.writeByte(metadata.sPLT_red[i]); cs.writeByte(metadata.sPLT_green[i]); cs.writeByte(metadata.sPLT_blue[i]); cs.writeByte(metadata.sPLT_alpha[i]); cs.writeShort(metadata.sPLT_frequency[i]); } } else { // sampleDepth == 16 for (int i = 0; i < numEntries; i++) { cs.writeShort(metadata.sPLT_red[i]); cs.writeShort(metadata.sPLT_green[i]); cs.writeShort(metadata.sPLT_blue[i]); cs.writeShort(metadata.sPLT_alpha[i]); cs.writeShort(metadata.sPLT_frequency[i]); } } cs.finish(); } } private void write_tIME() throws IOException { if (metadata.tIME_present) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.tIME_TYPE, stream); cs.writeShort(metadata.tIME_year); cs.writeByte(metadata.tIME_month); cs.writeByte(metadata.tIME_day); cs.writeByte(metadata.tIME_hour); cs.writeByte(metadata.tIME_minute); cs.writeByte(metadata.tIME_second); cs.finish(); } } private void write_tEXt() throws IOException { Iterator<String> keywordIter = metadata.tEXt_keyword.iterator(); Iterator<String> textIter = metadata.tEXt_text.iterator(); while (keywordIter.hasNext()) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.tEXt_TYPE, stream); String keyword = keywordIter.next(); cs.writeBytes(keyword); cs.writeByte(0); String text = textIter.next(); cs.writeBytes(text); cs.finish(); } } private byte[] deflate(byte[] b) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream dos = new DeflaterOutputStream(baos); dos.write(b); dos.close(); return baos.toByteArray(); } private void write_iTXt() throws IOException { Iterator<String> keywordIter = metadata.iTXt_keyword.iterator(); Iterator<Boolean> flagIter = metadata.iTXt_compressionFlag.iterator(); Iterator<Integer> methodIter = metadata.iTXt_compressionMethod.iterator(); Iterator<String> languageIter = metadata.iTXt_languageTag.iterator(); Iterator<String> translatedKeywordIter = metadata.iTXt_translatedKeyword.iterator(); Iterator<String> textIter = metadata.iTXt_text.iterator(); while (keywordIter.hasNext()) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.iTXt_TYPE, stream); cs.writeBytes(keywordIter.next()); cs.writeByte(0); Boolean compressed = flagIter.next(); cs.writeByte(compressed ? 1 : 0); cs.writeByte(methodIter.next().intValue()); cs.writeBytes(languageIter.next()); cs.writeByte(0); cs.write(translatedKeywordIter.next().getBytes("UTF8")); cs.writeByte(0); String text = textIter.next(); if (compressed) { cs.write(deflate(text.getBytes("UTF8"))); } else { cs.write(text.getBytes("UTF8")); } cs.finish(); } } private void write_zTXt() throws IOException { Iterator<String> keywordIter = metadata.zTXt_keyword.iterator(); Iterator<Integer> methodIter = metadata.zTXt_compressionMethod.iterator(); Iterator<String> textIter = metadata.zTXt_text.iterator(); while (keywordIter.hasNext()) { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.zTXt_TYPE, stream); String keyword = keywordIter.next(); cs.writeBytes(keyword); cs.writeByte(0); int compressionMethod = (methodIter.next()).intValue(); cs.writeByte(compressionMethod); String text = textIter.next(); cs.write(deflate(text.getBytes("ISO-8859-1"))); cs.finish(); } } private void writeUnknownChunks() throws IOException { Iterator<String> typeIter = metadata.unknownChunkType.iterator(); Iterator<byte[]> dataIter = metadata.unknownChunkData.iterator(); while (typeIter.hasNext() && dataIter.hasNext()) { String type = typeIter.next(); ChunkStreamBackport cs = new ChunkStreamBackport(chunkType(type), stream); byte[] data = dataIter.next(); cs.write(data); cs.finish(); } } private static int chunkType(String typeString) { char c0 = typeString.charAt(0); char c1 = typeString.charAt(1); char c2 = typeString.charAt(2); char c3 = typeString.charAt(3); int type = (c0 << 24) | (c1 << 16) | (c2 << 8) | c3; return type; } private void encodePass(ImageOutputStream os, RenderedImage image, int xOffset, int yOffset, int xSkip, int ySkip) throws IOException { int minX = sourceXOffset; int minY = sourceYOffset; int width = sourceWidth; int height = sourceHeight; // Adjust offsets and skips based on source subsampling factors xOffset *= periodX; xSkip *= periodX; yOffset *= periodY; ySkip *= periodY; // Early exit if no data for this pass int hpixels = (width - xOffset + xSkip - 1)/xSkip; int vpixels = (height - yOffset + ySkip - 1)/ySkip; if (hpixels == 0 || vpixels == 0) { return; } // Convert X offset and skip from pixels to samples xOffset *= numBands; xSkip *= numBands; // Create row buffers int samplesPerByte = 8/metadata.IHDR_bitDepth; int numSamples = width*numBands; int[] samples = new int[numSamples]; int bytesPerRow = hpixels*numBands; if (metadata.IHDR_bitDepth < 8) { bytesPerRow = (bytesPerRow + samplesPerByte - 1)/samplesPerByte; } else if (metadata.IHDR_bitDepth == 16) { bytesPerRow *= 2; } IndexColorModel icm_gray_alpha = null; if (metadata.IHDR_colorType == PNGImageReader.PNG_COLOR_GRAY_ALPHA && image.getColorModel() instanceof IndexColorModel) { // reserve space for alpha samples bytesPerRow *= 2; // will be used to calculate alpha value for the pixel icm_gray_alpha = (IndexColorModel)image.getColorModel(); } currRow = new byte[bytesPerRow + bpp]; prevRow = new byte[bytesPerRow + bpp]; filteredRows = new byte[5][bytesPerRow + bpp]; int bitDepth = metadata.IHDR_bitDepth; for (int row = minY + yOffset; row < minY + height; row += ySkip) { Rectangle rect = new Rectangle(minX, row, width, 1); Raster ras = image.getData(rect); if (sourceBands != null) { ras = ras.createChild(minX, row, width, 1, minX, row, sourceBands); } ras.getPixels(minX, row, width, 1, samples); if (image.getColorModel().isAlphaPremultiplied()) { WritableRaster wr = ras.createCompatibleWritableRaster(); wr.setPixels(wr.getMinX(), wr.getMinY(), wr.getWidth(), wr.getHeight(), samples); image.getColorModel().coerceData(wr, false); wr.getPixels(wr.getMinX(), wr.getMinY(), wr.getWidth(), wr.getHeight(), samples); } // Reorder palette data if necessary int[] paletteOrder = metadata.PLTE_order; if (paletteOrder != null) { for (int i = 0; i < numSamples; i++) { samples[i] = paletteOrder[samples[i]]; } } int count = bpp; // leave first 'bpp' bytes zero int pos = 0; int tmp = 0; switch (bitDepth) { case 1: case 2: case 4: // Image can only have a single band int mask = samplesPerByte - 1; for (int s = xOffset; s < numSamples; s += xSkip) { byte val = scale0[samples[s]]; tmp = (tmp << bitDepth) | val; if ((pos++ & mask) == mask) { currRow[count++] = (byte)tmp; tmp = 0; pos = 0; } } // Left shift the last byte if ((pos & mask) != 0) { tmp <<= ((8/bitDepth) - pos)*bitDepth; currRow[count++] = (byte)tmp; } break; case 8: if (numBands == 1) { for (int s = xOffset; s < numSamples; s += xSkip) { currRow[count++] = scale0[samples[s]]; if (icm_gray_alpha != null) { currRow[count++] = scale0[icm_gray_alpha.getAlpha(0xff & samples[s])]; } } } else { for (int s = xOffset; s < numSamples; s += xSkip) { for (int b = 0; b < numBands; b++) { currRow[count++] = scale[b][samples[s + b]]; } } } break; case 16: for (int s = xOffset; s < numSamples; s += xSkip) { for (int b = 0; b < numBands; b++) { currRow[count++] = scaleh[b][samples[s + b]]; currRow[count++] = scalel[b][samples[s + b]]; } } break; } // Perform filtering int filterType = rowFilter.filterRow(metadata.IHDR_colorType, currRow, prevRow, filteredRows, bytesPerRow, bpp); os.write(filterType); os.write(filteredRows[filterType], bpp, bytesPerRow); // Swap current and previous rows byte[] swap = currRow; currRow = prevRow; prevRow = swap; pixelsDone += hpixels; processImageProgress(100.0F*pixelsDone/totalPixels); // If write has been aborted, just return; // processWriteAborted will be called later if (abortRequested()) { return; } } } // Use sourceXOffset, etc. private void write_IDAT(RenderedImage image, int deflaterLevel) throws IOException { IDATOutputStreamBackport ios = new IDATOutputStreamBackport(stream, 32768, deflaterLevel); try { if (metadata.IHDR_interlaceMethod == 1) { for (int i = 0; i < 7; i++) { encodePass(ios, image, PNGImageReader.adam7XOffset[i], PNGImageReader.adam7YOffset[i], PNGImageReader.adam7XSubsampling[i], PNGImageReader.adam7YSubsampling[i]); if (abortRequested()) { break; } } } else { encodePass(ios, image, 0, 0, 1, 1); } } finally { ios.finish(); } } private void writeIEND() throws IOException { ChunkStreamBackport cs = new ChunkStreamBackport(PNGImageReader.IEND_TYPE, stream); cs.finish(); } // Check two int arrays for value equality, always returns false // if either array is null private boolean equals(int[] s0, int[] s1) { if (s0 == null || s1 == null) { return false; } if (s0.length != s1.length) { return false; } for (int i = 0; i < s0.length; i++) { if (s0[i] != s1[i]) { return false; } } return true; } // Initialize the scale/scale0 or scaleh/scalel arrays to // hold the results of scaling an input value to the desired // output bit depth private void initializeScaleTables(int[] sampleSize) { int bitDepth = metadata.IHDR_bitDepth; // If the existing tables are still valid, just return if (bitDepth == scalingBitDepth && equals(sampleSize, this.sampleSize)) { return; } // Compute new tables this.sampleSize = sampleSize; this.scalingBitDepth = bitDepth; int maxOutSample = (1 << bitDepth) - 1; if (bitDepth <= 8) { scale = new byte[numBands][]; for (int b = 0; b < numBands; b++) { int maxInSample = (1 << sampleSize[b]) - 1; int halfMaxInSample = maxInSample/2; scale[b] = new byte[maxInSample + 1]; for (int s = 0; s <= maxInSample; s++) { scale[b][s] = (byte)((s*maxOutSample + halfMaxInSample)/maxInSample); } } scale0 = scale[0]; scaleh = scalel = null; } else { // bitDepth == 16 // Divide scaling table into high and low bytes scaleh = new byte[numBands][]; scalel = new byte[numBands][]; for (int b = 0; b < numBands; b++) { int maxInSample = (1 << sampleSize[b]) - 1; int halfMaxInSample = maxInSample/2; scaleh[b] = new byte[maxInSample + 1]; scalel[b] = new byte[maxInSample + 1]; for (int s = 0; s <= maxInSample; s++) { int val = (s*maxOutSample + halfMaxInSample)/maxInSample; scaleh[b][s] = (byte)(val >> 8); scalel[b][s] = (byte)(val & 0xff); } } scale = null; scale0 = null; } } @Override public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IIOException { if (stream == null) { throw new IllegalStateException("output == null!"); } if (image == null) { throw new IllegalArgumentException("image == null!"); } if (image.hasRaster()) { throw new UnsupportedOperationException("image has a Raster!"); } RenderedImage im = image.getRenderedImage(); SampleModel sampleModel = im.getSampleModel(); this.numBands = sampleModel.getNumBands(); // Set source region and subsampling to default values this.sourceXOffset = im.getMinX(); this.sourceYOffset = im.getMinY(); this.sourceWidth = im.getWidth(); this.sourceHeight = im.getHeight(); this.sourceBands = null; this.periodX = 1; this.periodY = 1; if (param != null) { // Get source region and subsampling factors Rectangle sourceRegion = param.getSourceRegion(); if (sourceRegion != null) { Rectangle imageBounds = new Rectangle(im.getMinX(), im.getMinY(), im.getWidth(), im.getHeight()); // Clip to actual image bounds sourceRegion = sourceRegion.intersection(imageBounds); sourceXOffset = sourceRegion.x; sourceYOffset = sourceRegion.y; sourceWidth = sourceRegion.width; sourceHeight = sourceRegion.height; } // Adjust for subsampling offsets int gridX = param.getSubsamplingXOffset(); int gridY = param.getSubsamplingYOffset(); sourceXOffset += gridX; sourceYOffset += gridY; sourceWidth -= gridX; sourceHeight -= gridY; // Get subsampling factors periodX = param.getSourceXSubsampling(); periodY = param.getSourceYSubsampling(); int[] sBands = param.getSourceBands(); if (sBands != null) { sourceBands = sBands; numBands = sourceBands.length; } } // Compute output dimensions int destWidth = (sourceWidth + periodX - 1)/periodX; int destHeight = (sourceHeight + periodY - 1)/periodY; if (destWidth <= 0 || destHeight <= 0) { throw new IllegalArgumentException("Empty source region!"); } // Compute total number of pixels for progress notification this.totalPixels = destWidth*destHeight; this.pixelsDone = 0; // Create metadata IIOMetadata imd = image.getMetadata(); if (imd != null) { metadata = (PNGMetadata)convertImageMetadata(imd, ImageTypeSpecifier.createFromRenderedImage(im), null); } else { metadata = new PNGMetadata(); } // reset compression level to default: int deflaterLevel = DEFAULT_COMPRESSION_LEVEL; if (param != null) { switch(param.getCompressionMode()) { case ImageWriteParam.MODE_DISABLED: deflaterLevel = Deflater.NO_COMPRESSION; break; case ImageWriteParam.MODE_EXPLICIT: float quality = param.getCompressionQuality(); if (quality >= 0f && quality <= 1f) { deflaterLevel = 9 - Math.round(9f * quality); } break; default: } // Use Adam7 interlacing if set in write param switch (param.getProgressiveMode()) { case ImageWriteParam.MODE_DEFAULT: metadata.IHDR_interlaceMethod = 1; break; case ImageWriteParam.MODE_DISABLED: metadata.IHDR_interlaceMethod = 0; break; // MODE_COPY_FROM_METADATA should already be taken care of // MODE_EXPLICIT is not allowed default: } } // Initialize bitDepth and colorType metadata.initialize(new ImageTypeSpecifier(im), numBands); // Overwrite IHDR width and height values with values from image metadata.IHDR_width = destWidth; metadata.IHDR_height = destHeight; this.bpp = numBands*((metadata.IHDR_bitDepth == 16) ? 2 : 1); // Initialize scaling tables for this image initializeScaleTables(sampleModel.getSampleSize()); clearAbortRequest(); processImageStarted(0); try { write_magic(); write_IHDR(); write_cHRM(); write_gAMA(); write_iCCP(); write_sBIT(); write_sRGB(); write_PLTE(); write_hIST(); write_tRNS(); write_bKGD(); write_pHYs(); write_sPLT(); write_tIME(); write_tEXt(); write_iTXt(); write_zTXt(); writeUnknownChunks(); write_IDAT(im, deflaterLevel); if (abortRequested()) { processWriteAborted(); } else { // Finish up and inform the listeners we are done writeIEND(); processImageComplete(); } } catch (IOException e) { throw new IIOException("I/O error writing PNG file!", e); } } }
43,903
Java
.java
gredler/jdk9-png-writer-backport
13
2
0
2016-05-19T04:15:31Z
2016-05-19T06:25:34Z
PNGImageWriterSpiBackport.java
/FileExtraction/Java_unseen/gredler_jdk9-png-writer-backport/src/main/java/com/sun/imageio/plugins/png/PNGImageWriterSpiBackport.java
/* * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.imageio.plugins.png; import java.awt.image.ColorModel; import java.awt.image.IndexColorModel; import java.awt.image.SampleModel; import java.util.Iterator; import java.util.Locale; import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriter; import javax.imageio.spi.ImageWriterSpi; import javax.imageio.spi.ServiceRegistry; import javax.imageio.stream.ImageOutputStream; import com.sun.imageio.plugins.png.PNGMetadata; public class PNGImageWriterSpiBackport extends ImageWriterSpi { private static final String vendorName = "The Interwebs"; private static final String version = "1.0"; private static final String[] names = { "png", "PNG" }; private static final String[] suffixes = { "png" }; private static final String[] MIMETypes = { "image/png", "image/x-png" }; private static final String writerClassName = "com.sun.imageio.plugins.png.PNGImageWriterBackport"; private static final String[] readerSpiNames = { "com.sun.imageio.plugins.png.PNGImageReaderSpi" }; public PNGImageWriterSpiBackport() { super(vendorName, version, names, suffixes, MIMETypes, writerClassName, new Class<?>[] { ImageOutputStream.class }, readerSpiNames, false, null, null, null, null, true, PNGMetadata.nativeMetadataFormatName, "com.sun.imageio.plugins.png.PNGMetadataFormat", null, null ); } @Override public boolean canEncodeImage(ImageTypeSpecifier type) { SampleModel sampleModel = type.getSampleModel(); ColorModel colorModel = type.getColorModel(); // Find the maximum bit depth across all channels int[] sampleSize = sampleModel.getSampleSize(); int bitDepth = sampleSize[0]; for (int i = 1; i < sampleSize.length; i++) { if (sampleSize[i] > bitDepth) { bitDepth = sampleSize[i]; } } // Ensure bitDepth is between 1 and 16 if (bitDepth < 1 || bitDepth > 16) { return false; } // Check number of bands, alpha int numBands = sampleModel.getNumBands(); if (numBands < 1 || numBands > 4) { return false; } boolean hasAlpha = colorModel.hasAlpha(); // Fix 4464413: PNGTransparency reg-test was failing // because for IndexColorModels that have alpha, // numBands == 1 && hasAlpha == true, thus causing // the check below to fail and return false. if (colorModel instanceof IndexColorModel) { return true; } if ((numBands == 1 || numBands == 3) && hasAlpha) { return false; } if ((numBands == 2 || numBands == 4) && !hasAlpha) { return false; } return true; } @Override public String getDescription(Locale locale) { return "JDK9 Backport PNG image writer"; } @Override public ImageWriter createWriterInstance(Object extension) { return new PNGImageWriterBackport(this); } @Override public void onRegistration(ServiceRegistry registry, Class< ? > category) { Iterator< ImageWriterSpi > others = registry.getServiceProviders(ImageWriterSpi.class, false); while (others.hasNext()) { ImageWriterSpi other = others.next(); if (other != this) { for (String formatName : other.getFormatNames()) { if ("png".equals(formatName)) { registry.setOrdering(ImageWriterSpi.class, this, other); break; } } } } } }
5,107
Java
.java
gredler/jdk9-png-writer-backport
13
2
0
2016-05-19T04:15:31Z
2016-05-19T06:25:34Z
Database.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/code/husky/Database.java
package code.husky; import java.sql.Connection; import org.bukkit.plugin.Plugin; /** * Abstract Database class, serves as a base for any connection method (MySQL, SQLite, etc.) * * @author -_Husky_- * @author tips48 */ public abstract class Database { /** * Plugin instance, use for plugin.getDataFolder() and plugin.getLogger() */ protected Plugin plugin; /** * Creates a new Database * * @param plugin * Plugin instance */ protected Database(Plugin plugin) { this.plugin = plugin; } /** * Opens a connection with the database * * @return Connection opened */ public abstract Connection openConnection(); /** * Checks if a connection is open with the database * * @return true if a connection is open */ public abstract boolean checkConnection(); /** * Gets the connection with the database * * @return Connection with the database, null if none */ public abstract Connection getConnection(); /** * Closes the connection with the database */ public abstract void closeConnection(); }
1,179
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
MySQL.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/code/husky/mysql/MySQL.java
package code.husky.mysql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import org.bukkit.plugin.Plugin; import code.husky.Database; /** * Connects to and uses a MySQL database * * @author -_Husky_- * @author tips48 */ public class MySQL extends Database { private final String user; private final String database; private final String password; private final String port; private final String hostname; private Connection connection; /** * Creates a new MySQL instance * * @param plugin * Plugin instance * @param hostname * Name of the host * @param port * Port number * @param database * Database name * @param username * Username * @param password * Password */ public MySQL(Plugin plugin, String hostname, String port, String database, String username, String password) { super(plugin); this.hostname = hostname; this.port = port; this.database = database; this.user = username; this.password = password; this.connection = null; } @Override public Connection openConnection() { try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password); } catch (SQLException e) { plugin.getLogger().log(Level.SEVERE, "Could not connect to MySQL server! because: " + e.getMessage()); } catch (ClassNotFoundException e) { plugin.getLogger().log(Level.SEVERE, "JDBC Driver not found!"); } return connection; } @Override public boolean checkConnection() { return connection != null; } @Override public Connection getConnection() { return connection; } @Override public void closeConnection() { if (connection != null) { try { connection.close(); } catch (SQLException e) { plugin.getLogger().log(Level.SEVERE, "Error closing the MySQL Connection!"); e.printStackTrace(); } } } public ResultSet querySQL(String query) { Connection c = null; if (checkConnection()) { c = getConnection(); } else { c = openConnection(); } Statement s = null; try { s = c.createStatement(); } catch (SQLException e1) { e1.printStackTrace(); } ResultSet ret = null; try { ret = s.executeQuery(query); } catch (SQLException e) { e.printStackTrace(); } closeConnection(); return ret; } public void updateSQL(String update) { Connection c = null; if (checkConnection()) { c = getConnection(); } else { c = openConnection(); } Statement s = null; try { s = c.createStatement(); s.executeUpdate(update); } catch (SQLException e1) { e1.printStackTrace(); } closeConnection(); } }
3,444
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
SQLite.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/code/husky/sqlite/SQLite.java
package code.husky.sqlite; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import org.bukkit.plugin.Plugin; import code.husky.Database; /** * Connects to and uses a SQLite database * * @author tips48 */ public class SQLite extends Database { private final String dbLocation; private Connection connection; /** * Creates a new SQLite instance * * @param plugin * Plugin instance * @param dbLocation * Location of the Database (Must end in .db) */ public SQLite(Plugin plugin, String dbLocation) { super(plugin); this.dbLocation = dbLocation; this.connection = null; } @Override public Connection openConnection() { File file = new File(dbLocation); if (!(file.exists())) { try { file.createNewFile(); } catch (IOException e) { plugin.getLogger().log(Level.SEVERE, "Unable to create database!"); } } try { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("jdbc:sqlite:" + plugin.getDataFolder().toPath().toString() + "/" + dbLocation); } catch (SQLException e) { plugin.getLogger().log(Level.SEVERE, "Could not connect to SQLite server! because: " + e.getMessage()); } catch (ClassNotFoundException e) { plugin.getLogger().log(Level.SEVERE, "JDBC Driver not found!"); } return connection; } @Override public boolean checkConnection() { try { return !(connection.isClosed()); } catch (SQLException e) { e.printStackTrace(); return false; } } @Override public Connection getConnection() { return connection; } @Override public void closeConnection() { if (connection != null) { try { connection.close(); } catch (SQLException e) { plugin.getLogger().log(Level.SEVERE, "Error closing the SQLite Connection!"); e.printStackTrace(); } } } }
2,296
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
package-info.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/package-info.java
/** * Main package */ /** * This package provides classes to load the plugin in Bukkit */ package com.github.catageek.ByteCart;
131
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
ModifiableRunnable.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/ModifiableRunnable.java
package com.github.catageek.ByteCart; import org.bukkit.inventory.Inventory; /** * Represents a runnable that can updates its inventory variable * * @param <T> */ public interface ModifiableRunnable<T> extends Runnable { /** * Updates the inventory variable * * @param inventory */ void SetParam(Inventory inventory); }
339
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
ByteCart.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/ByteCart.java
package com.github.catageek.ByteCart; import java.util.MissingResourceException; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; import com.github.catageek.ByteCart.CollisionManagement.CollisionAvoiderManager; import com.github.catageek.ByteCart.EventManagement.ByteCartListener; import com.github.catageek.ByteCart.EventManagement.ConstantSpeedListener; import com.github.catageek.ByteCart.EventManagement.PreloadChunkListener; import com.github.catageek.ByteCart.Storage.IsTrainManager; import com.github.catageek.ByteCart.Wanderer.BCWandererManager; import com.github.catageek.ByteCart.plugins.BCDynmapPlugin; import com.github.catageek.ByteCart.plugins.BCHostnameResolutionPlugin; import com.github.catageek.ByteCart.plugins.BCWandererTracker; import com.github.catageek.ByteCartAPI.ByteCartAPI; import com.github.catageek.ByteCartAPI.ByteCartPlugin; import com.github.catageek.ByteCartAPI.AddressLayer.Resolver; import com.github.catageek.ByteCart.Commands.CommandBCBack; import com.github.catageek.ByteCart.Commands.CommandBCDMapSync; import com.github.catageek.ByteCart.Commands.CommandBCReload; import com.github.catageek.ByteCart.Commands.CommandBCTicket; import com.github.catageek.ByteCart.Commands.CommandBCUpdater; import com.github.catageek.ByteCart.Commands.CommandMeGo; import com.github.catageek.ByteCart.Commands.CommandSendTo; /** * Main class */ public final class ByteCart extends JavaPlugin implements ByteCartPlugin { public static Logger log = Logger.getLogger("Minecraft"); public static ByteCart myPlugin; public static boolean debug; private BCHostnameResolutionPlugin hostnamePlugin; private PreloadChunkListener preloadchunklistener; private ConstantSpeedListener constantspeedlistener; private CollisionAvoiderManager cam; private BCWandererManager wf; private IsTrainManager it; public int Lockduration; private boolean keepitems; private Resolver resolver; /* (non-Javadoc) * @see org.bukkit.plugin.java.JavaPlugin#onEnable() */ @Override public void onEnable(){ myPlugin = this; ByteCartAPI.setPlugin(this); this.saveDefaultConfig(); this.loadConfig(); this.setCam(new CollisionAvoiderManager()); this.setWf(new BCWandererManager()); this.setIt(new IsTrainManager()); getServer().getPluginManager().registerEvents(new ByteCartListener(), this); getCommand("mego").setExecutor(new CommandMeGo(this)); getCommand("sendto").setExecutor(new CommandSendTo(this)); getCommand("bcreload").setExecutor(new CommandBCReload()); getCommand("bcupdater").setExecutor(new CommandBCUpdater()); getCommand("bcticket").setExecutor(new CommandBCTicket(this)); getCommand("bcback").setExecutor(new CommandBCBack()); getCommand("bcdmapsync").setExecutor(new CommandBCDMapSync()); if (Bukkit.getPluginManager().isPluginEnabled("dynmap") && this.getConfig().getBoolean("dynmap", true)) { log.info("[ByteCart] loading dynmap plugin."); try { getServer().getPluginManager().registerEvents(new BCDynmapPlugin(), this); } catch (MissingResourceException e) { log.info("[ByteCart] Failed to load dynmap plugin."); } } if (this.getConfig().getBoolean("hostname_resolution", true)) { log.info("[ByteCart] loading BCHostname plugin."); hostnamePlugin = new BCHostnameResolutionPlugin(); try { hostnamePlugin.onLoad(); ByteCartAPI.setResolver(hostnamePlugin); getServer().getPluginManager().registerEvents(hostnamePlugin, this); getCommand("host").setExecutor(hostnamePlugin); } catch (MissingResourceException e) { log.info("[ByteCart] Failed to load BCHostname plugin."); } } BCWandererTracker updatertrackerplugin = new BCWandererTracker(); getServer().getPluginManager().registerEvents(updatertrackerplugin, this); getCommand("bctracker").setExecutor(updatertrackerplugin); /* Uncomment to launch storage test Block block = this.getServer().getWorld("plat").getBlockAt(0, 61, 0); Inventory inventory = ((Chest)block.getState()).getInventory(); (new FileStorageTest(inventory)).runTest(); */ log.info("[ByteCart] plugin has been enabled."); } /* (non-Javadoc) * @see org.bukkit.plugin.java.JavaPlugin#onDisable() */ @Override public void onDisable(){ log.info("Your plugin has been disabled."); myPlugin = null; ByteCartAPI.setPlugin(null); log = null; } /** * Load the configuration file * */ public final void loadConfig() { debug = this.getConfig().getBoolean("debug", false); keepitems = this.getConfig().getBoolean("keepitems", true); Lockduration = this.getConfig().getInt("Lockduration", 44); if(debug){ log.info("ByteCart : debug mode is on."); } if(this.getConfig().getBoolean("loadchunks")) { if (preloadchunklistener == null) { preloadchunklistener = new PreloadChunkListener(); getServer().getPluginManager().registerEvents(preloadchunklistener, this); } } else if (preloadchunklistener != null) { HandlerList.unregisterAll(preloadchunklistener); preloadchunklistener = null; } if(this.getConfig().getBoolean("constantspeed", false)) { if (constantspeedlistener == null) { constantspeedlistener = new ConstantSpeedListener(); getServer().getPluginManager().registerEvents(constantspeedlistener, this); } } else if (constantspeedlistener != null) { HandlerList.unregisterAll(constantspeedlistener); constantspeedlistener = null; } } /** * @return the cam */ public CollisionAvoiderManager getCollisionAvoiderManager() { return cam; } /** * @param cam the cam to set */ private void setCam(CollisionAvoiderManager cam) { this.cam = cam; } /** * @return the it */ public IsTrainManager getIsTrainManager() { return it; } /** * @param it the it to set */ private void setIt(IsTrainManager it) { this.it = it; } /** * @return true if we must keep items while removing carts */ public boolean keepItems() { return keepitems; } /** * @return the resolver registered */ @Override public Resolver getResolver() { return resolver; } /** * Set the resolver that will be used * * @param resolver the resolver provided */ @Override public void setResolver(Resolver resolver) { this.resolver = resolver; } @Override public final Logger getLog() { return log; } /** * @return the wf */ @Override public BCWandererManager getWandererManager() { return wf; } /** * @param wf the wf to set */ private void setWf(BCWandererManager wf) { this.wf = wf; } }
6,622
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
package-info.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/package-info.java
/** * */ /** * Implementation of the configuration updaters */ package com.github.catageek.ByteCart.Updaters;
114
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
UpdaterResetRegion.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/UpdaterResetRegion.java
package com.github.catageek.ByteCart.Updaters; import org.bukkit.Bukkit; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.Event.UpdaterClearRingEvent; import com.github.catageek.ByteCartAPI.Signs.BCSign; import com.github.catageek.ByteCartAPI.Wanderer.AbstractWanderer; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; final class UpdaterResetRegion extends UpdaterRegion implements Wanderer { UpdaterResetRegion(BCSign bc, UpdaterContent rte) { super(bc, rte); } @Override public void doAction(BlockFace to) { if (! this.isAtBorder()) reset(); } @Override protected BlockFace selectDirection() { BlockFace face; if ((face = manageBorder()) != null) return face; return AbstractWanderer.getRandomBlockFace(getRoutingTable(), getFrom().getBlockFace()); } @Override protected final void reset() { // case of reset // erase address on sign if ring 0 Address address = this.getSignAddress(); boolean isValid = address.isValid(); int track = this.getTrackNumber(); if (!isValid || track == -1) { address.remove(); if (isValid) { UpdaterClearRingEvent event = new UpdaterClearRingEvent(this, 0); Bukkit.getServer().getPluginManager().callEvent(event); } } // clear routes except route to ring 0 super.reset(); } }
1,374
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
UpdaterResetLocal.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/UpdaterResetLocal.java
package com.github.catageek.ByteCart.Updaters; import java.util.Stack; import org.bukkit.Bukkit; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.Signs.BC9001; import com.github.catageek.ByteCartAPI.ByteCartAPI; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.CollisionManagement.IntersectionSide; import com.github.catageek.ByteCartAPI.CollisionManagement.IntersectionSide.Side; import com.github.catageek.ByteCartAPI.Event.UpdaterClearStationEvent; import com.github.catageek.ByteCartAPI.Event.UpdaterClearSubnetEvent; import com.github.catageek.ByteCartAPI.Event.UpdaterSignInvalidateEvent; import com.github.catageek.ByteCartAPI.Signs.BCSign; import com.github.catageek.ByteCartAPI.Wanderer.AbstractWanderer; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; final class UpdaterResetLocal extends UpdaterLocal implements Wanderer { UpdaterResetLocal(BCSign bc, UpdaterContent rte) { super(bc, rte, Level.RESET_LOCAL); } @Override public void doAction(BlockFace to) { int ring; if ((ring = this.getTrackNumber()) != -1) { incrementRingCounter(ring); } this.getEnd().clear(); // save the region number this.getContent().setCurrent(this.getSignAddress().getRegion().getAmount()); save(); } @Override public void doAction(Side to) { Address address = this.getSignAddress(); // Keep track on the subring level we are in int mask = this.getNetmask(); if (mask < 8) { Stack<Integer> end = this.getEnd(); if (to.equals(Side.LEVER_ON) && (end.isEmpty() || mask > end.peek())) { end.push(mask); if(ByteCart.debug) ByteCart.log.info("ByteCart : pushing mask " + mask + " on stack"); } else if (to.equals(Side.LEVER_OFF) && ! end.isEmpty()) { if(ByteCart.debug) ByteCart.log.info("ByteCart : popping mask " + end.peek() + " from stack"); end.pop(); } } save(); // if we are not in the good region, skip update if (getContent().getCurrent() != getContent().getRegion()) return; if (address.isValid()) { if (this.getContent().isFullreset()) { if (this.getNetmask() == 8) { UpdaterClearStationEvent event = new UpdaterClearStationEvent(this, address, ((BC9001)this.getBcSign()).getStationName()); Bukkit.getServer().getPluginManager().callEvent(event); } else { UpdaterClearSubnetEvent event = new UpdaterClearSubnetEvent(this, address, ByteCartAPI.MAXSTATION >> this.getNetmask()); Bukkit.getServer().getPluginManager().callEvent(event); } address.remove(); if (ByteCart.debug) ByteCart.log.info("ByteCart: removing address"); } } else { UpdaterSignInvalidateEvent event = new UpdaterSignInvalidateEvent(this); Bukkit.getServer().getPluginManager().callEvent(event); address.remove(); if (ByteCart.debug) ByteCart.log.info("ByteCart: removing invalid address"); } } @Override public IntersectionSide.Side giveSimpleDirection() { int mask = this.getNetmask(); Stack<Integer> end = this.getEnd(); if ( mask < 8 && (end.isEmpty() || mask > end.peek())) return IntersectionSide.Side.LEVER_ON; return IntersectionSide.Side.LEVER_OFF; } @Override public BlockFace giveRouterDirection() { // check if we are in the good region if (this.getSignAddress().isValid() && this.getSignAddress().getRegion().getAmount() != getWandererRegion()) { // case this is not the right region BlockFace dir = RoutingTable.getDirection(getWandererRegion()); if (dir != null) return dir; return this.getFrom().getBlockFace(); } // the route where we went the lesser int preferredroute = this.getContent().getMinDistanceRing(RoutingTable, getFrom()); BlockFace dir; if ((dir = RoutingTable.getDirection(preferredroute)) != null) return dir; return AbstractWanderer.getRandomBlockFace(RoutingTable, getFrom().getBlockFace()); } }
3,962
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
UpdaterBackBone.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/UpdaterBackBone.java
package com.github.catageek.ByteCart.Updaters; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.Signs.BCSign; import com.github.catageek.ByteCartAPI.Wanderer.AbstractWanderer; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; class UpdaterBackBone extends AbstractRegionUpdater implements Wanderer { UpdaterBackBone(BCSign bc, UpdaterContent rte) { super(bc, rte); } @Override protected BlockFace selectDirection() { BlockFace face; if ((face = manageBorder()) != null) return face; return AbstractWanderer.getRandomBlockFace(this.getRoutingTable(), this.getFrom().getBlockFace()); } @Override public void Update(BlockFace To) { // current: track number we are on int current = getCurrent(); if (getRoutes() != null) { if (getSignAddress().isValid()) { // there is an address on the sign if(ByteCart.debug) ByteCart.log.info("ByteCart : track number is " + getTrackNumber()); setCurrent(getTrackNumber()); if(ByteCart.debug) ByteCart.log.info("ByteCart : current is " + current); } else // no address on sign, and is not provider // assumes it's 0 if first sign met if (current == -2) setCurrent(0); routeUpdates(To); } } @Override public final int getTrackNumber() { Address address; if ((address = getSignAddress()).isValid()) return address.getRegion().getAmount(); return -1; } }
1,534
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
UpdaterFactory.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/UpdaterFactory.java
package com.github.catageek.ByteCart.Updaters; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Calendar; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.entity.Vehicle; import org.bukkit.inventory.Inventory; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.FileStorage.InventoryFile; import com.github.catageek.ByteCart.Util.LogUtil; import com.github.catageek.ByteCart.Wanderer.BCWandererManager; import com.github.catageek.ByteCartAPI.Event.UpdaterRemoveEvent; import com.github.catageek.ByteCartAPI.Signs.BCSign; import com.github.catageek.ByteCartAPI.Wanderer.InventoryContent; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer.Level; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer.Scope; import com.github.catageek.ByteCartAPI.Wanderer.WandererFactory; public final class UpdaterFactory implements WandererFactory { // A map with ephemeral elements and timers private UpdaterSet updaterset = new UpdaterSet(); @Override public Wanderer getWanderer(BCSign bc, Inventory inv) { UpdaterContent rte; final BCWandererManager wm = ByteCart.myPlugin.getWandererManager(); if (wm.isWanderer(inv, "Updater")) updaterset.addUpdater(bc.getVehicle().getEntityId()); if (wm.isWanderer(inv, Level.REGION, "Updater") && (rte = getUpdaterContent(inv)) != null) return new UpdaterRegion(bc, rte); if (wm.isWanderer(inv, Level.RESET_REGION, "Updater") && (rte = getUpdaterContent(inv)) != null) return new UpdaterResetRegion(bc, rte); if (wm.isWanderer(inv, Level.BACKBONE, "Updater") && (rte = getUpdaterContent(inv)) != null) return new UpdaterBackBone(bc, rte); if (wm.isWanderer(inv, Level.RESET_BACKBONE, "Updater") && (rte = getUpdaterContent(inv)) != null) return new UpdaterResetBackbone(bc, rte); if (wm.isWanderer(inv, Level.RESET_LOCAL, "Updater") && (rte = getUpdaterContent(inv)) != null) return new UpdaterResetLocal(bc, rte); if (wm.isWanderer(inv, Level.LOCAL, "Updater") && (rte = getUpdaterContent(inv)) != null) return new UpdaterLocal(bc, rte); return null; } @Override public final void removeAllWanderers() { updaterset.clear(); } @Override public boolean areAllRemoved() { return updaterset.getMap().isEmpty(); } private UpdaterContent getUpdaterContent(Inventory inv) { UpdaterContent rte = null; InventoryFile file = null; if (InventoryFile.isInventoryFile(inv, "Updater")) { file = new InventoryFile(inv, true, "Updater"); } if (file == null) { return null; } if (! file.isEmpty()) { ObjectInputStream ois; try { ois = new ObjectInputStream(file.getInputStream()); rte = (UpdaterContent) ois.readObject(); } catch (IOException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } rte.setInventory(inv); return rte; } @Override public void updateTimestamp(InventoryContent rte) { // Update the expiration time to have twice the spent time left long initial; long expiration; if ((initial = rte.getCreationtime()) == (expiration = rte.getExpirationTime())) return; long last = Calendar.getInstance().getTimeInMillis(); long update = last + ((last - initial) << 1); if (update > expiration) { rte.setExpirationTime(update); updaterset.getMap().reset(update - last / 50, ((Vehicle) rte.getInventory().getHolder()).getEntityId()); } } @Override public void createWanderer(int id, Inventory inv, int region, Level level, Player player , boolean isfullreset, boolean isnew) { UpdaterContent rte; if (level.scope.equals(Scope.LOCAL)) rte = new UpdaterContent(inv, level, region, player, isfullreset); else rte = new UpdaterContent(inv, level, region, player, isfullreset, isnew); try { ByteCart.myPlugin.getWandererManager().saveContent(rte, "Updater", level); } catch (ClassNotFoundException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } updaterset.getMap().add(id); LogUtil.sendError(player, ByteCart.myPlugin.getConfig().getString("Info.SetUpdater") ); } @Override public void destroyWanderer(Inventory inv) { int id = ((Vehicle) inv.getHolder()).getEntityId(); Bukkit.getServer().getPluginManager().callEvent(new UpdaterRemoveEvent(id)); updaterset.getMap().remove(id); inv.clear(); } }
4,467
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
UpdaterResetBackbone.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/UpdaterResetBackbone.java
package com.github.catageek.ByteCart.Updaters; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCartAPI.Signs.BCSign; import com.github.catageek.ByteCartAPI.Wanderer.AbstractWanderer; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; class UpdaterResetBackbone extends UpdaterBackBone implements Wanderer { UpdaterResetBackbone(BCSign bc, UpdaterContent rte) { super(bc, rte); } @Override public void doAction(BlockFace to) { if (! this.isAtBorder()) reset(); } @Override protected BlockFace selectDirection() { BlockFace face; if ((face = manageBorder()) != null) return face; return AbstractWanderer.getRandomBlockFace(getRoutingTable(), getFrom().getBlockFace()); } }
730
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
UpdaterRegion.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/UpdaterRegion.java
package com.github.catageek.ByteCart.Updaters; import java.util.Random; import org.bukkit.Bukkit; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.Util.LogUtil; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.Event.UpdaterSetRingEvent; import com.github.catageek.ByteCartAPI.Signs.BCSign; import com.github.catageek.ByteCartAPI.Wanderer.AbstractWanderer; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; class UpdaterRegion extends AbstractRegionUpdater implements Wanderer { UpdaterRegion(BCSign bc, UpdaterContent rte) { super(bc, rte); } private final String getAddress(int ring) { return "" + getWandererRegion() + "." + ring + ".0"; } private int setSign(int current) { current = findFreeTrackNumber(current); // update sign with new number we found or current this.getSignAddress().setAddress(this.getAddress(current)); this.getSignAddress().finalizeAddress(); if(ByteCart.debug) ByteCart.log.info("ByteCart : change address on sign to " + this.getAddress(current)); return current; } private int findFreeTrackNumber(int current) { if (current == -2) return 0; while(current < 0) { // find a free number for the track if needed current = this.getCounter().firstEmpty(); // if there is already a route, find another number // except if the route connects to here if(ByteCart.debug) ByteCart.log.info("ByteCart : trying ring " + current); if (! this.getRoutingTable().isEmpty(current) && ! this.getRoutingTable().isDirectlyConnected(current, getFrom().getBlockFace())) { this.getCounter().incrementCount(current); current = -1; } } return current; } private int getOrSetCurrent(int current) { // check if the sign has not priority if (current > 0 && current < getTrackNumber()) { // current < sign => reset counter, clear route and write sign this.getCounter().reset(getTrackNumber()); this.getRoutingTable().removeEntry(getTrackNumber(), getFrom().getBlockFace()); this.getSignAddress().setAddress(this.getAddress(current)); this.getSignAddress().finalizeAddress(); if(ByteCart.debug) ByteCart.log.info("ByteCart : change address on sign to " + this.getAddress(current)); return current; } else { // sign seems to have priority // if the router knows that it is directly connected // we keep it, otherwise we find a new number (if possible) // if (! this.getRoutingTable().isDirectlyConnected(getTrackNumber(), getFrom()) && this.isTrackNumberProvider()) // return setSign(current); if(ByteCart.debug) ByteCart.log.info("ByteCart : getOrSetCurrent() : current as track on sign " + this.getTrackNumber()); return getTrackNumber(); } } private boolean isSignNeedUpdate(int current) { int track = getTrackNumber(); if (! this.getRoutes().isNew() && track == -1 && current == -2) { String error = "First BC8010 sign met has no address. If it is an initial configuration" + ", add option 'new' at the end of bcupdater command to confirm." + " If this is not a new network (i.e. you have already used bcupdater)" + ", you should start from anywhere but here"; LogUtil.sendError(this.getRoutes().getPlayer(), error); ByteCart.myPlugin.getWandererManager().getFactory("Updater").destroyWanderer(this.getRoutes().getInventory()); return true; } return (track == -1 && current != -2) || (track > 0 && current != -2 && getCounter().getCount(track) == 0) || (current >= 0 && current != track) || (track > 0 && ! this.getRoutingTable().isDirectlyConnected(track, getFrom().getBlockFace())); } @Override protected BlockFace selectDirection() { BlockFace face; if ((face = manageBorder()) != null) return face; if (this.getRoutes() != null) { // current: track number we are on int current = this.getRoutes().getCurrent(); if (this.isSignNeedUpdate(current)) { if (ByteCart.debug) ByteCart.log.info("ByteCart : selectDirection() : sign need update as current = " + current); return this.getFrom().getBlockFace(); } // if there is a side we don't have visited yet, let go there if (isTrackNumberProvider()) { try { if ((face = this.getRoutingTable().getFirstUnknown()) != null && ! this.isSameTrack(face)) { if (ByteCart.debug) ByteCart.log.info("ByteCart : selectDirection() : first unknown " + face.toString()); return face; } } catch (NullPointerException e) { LogUtil.sendError(this.getRoutes().getPlayer(), "ByteCart : Chest expected at position " + this.getCenter().getRelative(BlockFace.UP, 5).getLocation()); LogUtil.sendError(this.getRoutes().getPlayer(), "ByteCart : or at position " + this.getCenter().getRelative(BlockFace.DOWN, 2).getLocation()); throw e; } int min; if((min = this.getCounter().getMinimum(this.getRoutingTable(), this.getFrom())) != -1) { if (ByteCart.debug) ByteCart.log.info("ByteCart : selectDirection() : minimum counter " + min); return this.getRoutingTable().getDirection(min); } } } if (ByteCart.debug) ByteCart.log.info("ByteCart : selectDirection() : default "); return AbstractWanderer.getRandomBlockFace(this.getRoutingTable(), this.getFrom().getBlockFace()); } @Override public void Update(BlockFace To) { // current: track number we are on int current = getCurrent(); boolean isNew = (current < 0); UpdaterSetRingEvent event = null; if (isTrackNumberProvider()) { if (! getSignAddress().isValid()) { // if there is no address on the sign // we provide one current = setSign(current); event = new UpdaterSetRingEvent(this, -1, current); Bukkit.getServer().getPluginManager().callEvent(event); } if (getSignAddress().isValid()) { // there is an address on the sign int old = getTrackNumber(); current = getOrSetCurrent(current); event = new UpdaterSetRingEvent(this, old, current); if (old != current) Bukkit.getServer().getPluginManager().callEvent(event); } } else { current = 0; } setCurrent(current); if(ByteCart.debug) ByteCart.log.info("ByteCart : Update() : current is " + current); // update track counter if we have entered a new one if (current > 0 && isNew) { this.getCounter().incrementCount(current, new Random().nextInt(this.getRoutingTable().size() + 1) + 1 ); } routeUpdates(To); } @Override public final int getTrackNumber() { Address address; if ((address = getSignAddress()).isValid()) return address.getTrack().getAmount(); return -1; } }
6,686
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
UpdaterSet.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/UpdaterSet.java
package com.github.catageek.ByteCart.Updaters; import java.util.Iterator; import org.bukkit.Bukkit; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.Storage.ExpirableSet; import com.github.catageek.ByteCartAPI.Event.UpdaterRemoveEvent; /** * A set for integers with a timeout of 1h */ final class UpdaterSet { // entries stay for 1h UpdaterSet() { long duration = ByteCart.myPlugin.getConfig().getInt("updater.timeout", 60)*1200; updateSet = new ExpirableSet<Integer>(duration, false, "UpdaterRoutes"); } private final ExpirableSet<Integer> updateSet; ExpirableSet<Integer> getMap() { return updateSet; } boolean isUpdater(Integer id) { return updateSet.contains(id); } void addUpdater(int id) { this.updateSet.add(id); } void clear() { Iterator<Integer> it = updateSet.getIterator(); while (it.hasNext()) { Bukkit.getServer().getPluginManager().callEvent(new UpdaterRemoveEvent(it.next())); } updateSet.clear(); } }
998
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
UpdaterLocal.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/UpdaterLocal.java
package com.github.catageek.ByteCart.Updaters; import java.util.Stack; import org.bukkit.Bukkit; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCart.IO.ComponentSign; import com.github.catageek.ByteCart.Signs.BC9001; import com.github.catageek.ByteCart.Util.LogUtil; import com.github.catageek.ByteCartAPI.ByteCartAPI; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.CollisionManagement.IntersectionSide.Side; import com.github.catageek.ByteCartAPI.Event.UpdaterEnterSubnetEvent; import com.github.catageek.ByteCartAPI.Event.UpdaterLeaveSubnetEvent; import com.github.catageek.ByteCartAPI.Event.UpdaterPassStationEvent; import com.github.catageek.ByteCartAPI.Event.UpdaterSetStationEvent; import com.github.catageek.ByteCartAPI.Event.UpdaterSetSubnetEvent; import com.github.catageek.ByteCartAPI.Signs.BCSign; import com.github.catageek.ByteCartAPI.Wanderer.DefaultLocalWanderer; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; public class UpdaterLocal extends DefaultLocalWanderer<UpdaterContent> implements Wanderer { protected UpdaterLocal(BCSign bc, UpdaterContent rte) { super(bc, rte, "Updater", Level.LOCAL); } protected UpdaterLocal(BCSign bc, UpdaterContent rte, Level level) { super(bc, rte, "Updater", level); } @Override public void doAction(Side to) { if (this.getNetmask() == ByteCartAPI.MAXSTATIONLOG) { // Erase default name "Station" // TODO : added 04/2015, to be removed if (((BC9001)this.getBcSign()).getStationName().equals("Station")) { (new ComponentSign(this.getCenter())).setLine(2, ""); } //it's a station, launch event UpdaterPassStationEvent event = new UpdaterPassStationEvent(this, this.getSignAddress(), ((BC9001)this.getBcSign()).getStationName()); Bukkit.getServer().getPluginManager().callEvent(event); } // cookie still there if (this.getStart().empty() ^ this.getEnd().empty()) return; // we did not enter the subnet int start; if(to.Value() != Side.LEVER_ON.Value() && this.getNetmask() < ByteCartAPI.MAXSTATIONLOG) { // if we have the same sign as when entering the subnet, close the subnet if (this.isExactSubnet((start = this.getFirstStationNumber()), this.getNetmask())) { this.getSignAddress().setAddress(buildAddress(start)); this.getSignAddress().finalizeAddress(); ByteCart.myPlugin.getWandererManager().getFactory("Updater").updateTimestamp(this.getContent()); this.leaveSubnet(); this.save(); } return; } int length = (ByteCartAPI.MAXSTATION >> this.getNetmask()); // if sign is not consistent, rewrite it if (! getSignAddress().isValid() || this.needUpdate()) { Address old = this.getSignAddress(); if ((start = this.getFreeSubnet(getNetmask())) != -1) { String address = buildAddress(start); this.getSignAddress().setAddress(address); this.getSignAddress().finalizeAddress(); // reload sign Address reloadAddress = AddressFactory.getAddress(address); this.setSignAddress(reloadAddress); ByteCart.myPlugin.getWandererManager().getFactory("Updater").updateTimestamp(this.getContent()); // launch event if (length > 1) { UpdaterSetSubnetEvent event = new UpdaterSetSubnetEvent(this, old, reloadAddress, length); Bukkit.getServer().getPluginManager().callEvent(event); } else { UpdaterSetStationEvent event = new UpdaterSetStationEvent(this, old, reloadAddress, ((BC9001)this.getBcSign()).getStationName()); Bukkit.getServer().getPluginManager().callEvent(event); } if(ByteCart.debug) ByteCart.log.info("ByteCart : UpdaterLocal : Update() : rewrite sign to " + address + "(" + this.getSignAddress().toString() + ")"); } } int stationfield = -1; if (getSignAddress().isValid()) stationfield = this.getSignAddress().getStation().getAmount(); if (length != 1) { // general case // if we go out from the current subnet and possibly entering a new one if (! this.isInSubnet(stationfield, this.getNetmask())) leaveSubnet(); if (stationfield != -1) { // register new subnet start and mask Stack<Integer> startstack = this.getStart(); Stack<Integer> endstack = this.getEnd(); int oldstart = getFirstStationNumber(); int oldend = getLastStationNumber(); startstack.push(stationfield); endstack.push(stationfield + length); // launch event UpdaterEnterSubnetEvent event = new UpdaterEnterSubnetEvent(this, getSignAddress(), length, AddressFactory.getAddress(buildAddress(oldstart)), oldend - oldstart); Bukkit.getServer().getPluginManager().callEvent(event); } } else // case of stations if (stationfield != -1) this.getCounter().incrementCount(stationfield, 64); save(); } @Override public final void leaveSubnet() { super.leaveSubnet(); if(!this.getStart().empty() && ! this.getEnd().empty()) { Stack<Integer> startstack = this.getStart(); Stack<Integer> endstack = this.getEnd(); int start = startstack.pop(); int end = endstack.pop(); int newstart = getFirstStationNumber(); int newend = getLastStationNumber(); // launch event UpdaterLeaveSubnetEvent event = new UpdaterLeaveSubnetEvent(this, AddressFactory.getAddress(buildAddress(start)), end - start , AddressFactory.getAddress(buildAddress(newstart)), newend - newstart); Bukkit.getServer().getPluginManager().callEvent(event); } } private final int getFreeSubnet(int netmask) { boolean free; int start = getFirstStationNumber(); int end = getLastStationNumber(); int step = ByteCartAPI.MAXSTATION >> netmask; if(ByteCart.debug) ByteCart.log.info("ByteCart : getFreeSubnet() : start = " + start + " end " + end + " step = " + step + "\n" + this.getCounter().toString()); for (int i = start; i < end; i += step) { free = true; for (int j = i; j < i + step; j++) { free &= (this.getCounter().getCount(j) == 0); } if (free) { if(ByteCart.debug) ByteCart.log.info("ByteCart : getFreeSubnet() : testing : " + i + " : " + free); return i; } if(ByteCart.debug) ByteCart.log.info("ByteCart : getFreeSubnet() : testing : " + i + " : " + free); } LogUtil.sendError(this.getContent().getPlayer(), "Sign at " + this.getCenter().getLocation().toString() + "could not get an address because address pool is empty." + " Maximum station numbers is reached on the " + step + "-station subnet " + this.buildAddress(start)); return -1; } private String buildAddress(int start) { String address = "" + this.getCounter().getCount(counterSlot.REGION.slot) + "." + getCurrent() + "." + start; return address; } private final boolean isInSubnet(int address, int netmask) { return (address >= this.getFirstStationNumber() && (address | ((ByteCartAPI.MAXSTATION - 1) >> netmask)) < this.getLastStationNumber()); } private final boolean needUpdate() { return getSignAddress().getRegion().getAmount() != this.getCounter().getCount(counterSlot.REGION.slot) || getSignAddress().getTrack().getAmount() != this.getCounter().getCount(counterSlot.RING.slot) || ! isInSubnet(getSignAddress().getStation().getAmount(), this.getNetmask()); } private int getCurrent() { return this.getCounter().getCount(counterSlot.RING.slot); } @Override public final Level getLevel() { return Level.LOCAL; } @Override public int getTrackNumber() { Address address; if ((address = this.getSignAddress()).isValid()) return address.getTrack().getAmount(); return -1; } }
7,638
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
UpdaterContent.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/UpdaterContent.java
package com.github.catageek.ByteCart.Updaters; import java.io.Serializable; import java.util.Calendar; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.Routing.Metric; import com.github.catageek.ByteCart.Routing.RoutingTableWritable; import com.github.catageek.ByteCart.Wanderer.WandererContent; import com.github.catageek.ByteCartAPI.Util.DirectionRegistry; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; /** * A class to store data in books used by updater */ public class UpdaterContent extends WandererContent implements Serializable { /** * */ private static final long serialVersionUID = 848098890652934583L; private boolean fullreset = false; private boolean isnew = false; private long lastrouterseen; UpdaterContent(Inventory inv, Wanderer.Level level, int region, Player player , boolean isfullreset) { this(inv, level, region, player, isfullreset, false); } UpdaterContent(Inventory inv, Wanderer.Level level, int region, Player player , boolean isfullreset, boolean isnew) { super(inv, level, region, player); this.fullreset = isfullreset; this.isnew = isnew; this.setExpirationTime(ByteCart.myPlugin.getConfig().getInt("updater.timeout", 60) * 60000 + getCreationtime()); } /** * Get a set of the entries of the IGP packet * * @return the set */ public Set<Entry<Integer,Metric>> getEntrySet() { return tablemap.entrySet(); } /** * Build the IGP exchange packet * * @param table the routing table * @param direction the direction to exclude */ void putRoutes(RoutingTableWritable table, DirectionRegistry direction) { tablemap.clear(); Iterator<Integer> it = table.getOrderedRouteNumbers(); while (it.hasNext()) { int i = it.next(); if( table.getDirection(i) != null && table.getDirection(i) != direction.getBlockFace()) { tablemap.put(i, new Metric(table.getMinMetric(i))); if(ByteCart.debug) ByteCart.log.info("ByteCart : Route exchange : give ring " + i + " with metric " + table.getMinMetric(i) + " to " + table.getDirection(i)); } } } /** * Set the timestamp field to now */ void seenTimestamp() { this.lastrouterseen = Calendar.getInstance().getTimeInMillis(); } /** * Get the time difference between now and the last time we called seenTimestamp() * * @return the time difference, or -1 if seenTimestamp() was never called */ public int getInterfaceDelay() { if (lastrouterseen != 0) return (int) ((Calendar.getInstance().getTimeInMillis() - lastrouterseen) / 1000); return -1; } /** * @return the fullreset */ boolean isFullreset() { return fullreset; } /** * @return the isnew */ boolean isNew() { return isnew; } }
2,883
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
AbstractRegionUpdater.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/AbstractRegionUpdater.java
package com.github.catageek.ByteCart.Updaters; import java.io.IOException; import java.util.Iterator; import java.util.Set; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.Routing.BCCounter; import com.github.catageek.ByteCart.Signs.BC8010; import com.github.catageek.ByteCartAPI.Signs.BCSign; import com.github.catageek.ByteCartAPI.Util.DirectionRegistry; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer.Level; abstract class AbstractRegionUpdater extends DefaultRouterWanderer { AbstractRegionUpdater(BCSign bc, UpdaterContent rte) { super(bc, rte.getRegion()); Routes = rte; counter = rte.getCounter(); if (bc instanceof BC8010) { BC8010 ic = (BC8010) bc; IsTrackNumberProvider = ic.isTrackNumberProvider(); } else IsTrackNumberProvider = false; } abstract protected void Update(BlockFace to); abstract protected int getTrackNumber(); private UpdaterContent Routes; private final boolean IsTrackNumberProvider; private BCCounter counter; abstract protected BlockFace selectDirection(); /** * Perform the IGP routing protocol update * * @param To the direction where we are going to */ protected final void routeUpdates(BlockFace To) { if(isRouteConsumer()) { Set<Integer> connected = getRoutingTable().getDirectlyConnectedList(getFrom().getBlockFace()); int current = getCurrent(); current = (current == -2 ? 0 : current); // if the track we come from is not recorded // or others track are wrongly recorded, we correct this if (current >=0 && ( ! connected.contains(current) || connected.size() != 1)) { Iterator<Integer> it = connected.iterator(); while (it.hasNext()) { getRoutingTable().removeEntry(it.next(), getFrom().getBlockFace()); } // Storing the route from where we arrive if(ByteCart.debug) ByteCart.log.info("ByteCart : Wanderer : storing ring " + current + " direction " + getFrom().ToString()); getRoutingTable().setEntry(current, getFrom().getBlockFace(), 0); ByteCart.myPlugin.getWandererManager().getFactory("Updater").updateTimestamp(Routes); } // loading received routes in router if coming from another router if (this.getRoutes().getLastrouterid() != this.getCenter().hashCode()) getRoutingTable().Update(getRoutes(), getFrom().getBlockFace()); // preparing the routes to send Routes.putRoutes(getRoutingTable(), new DirectionRegistry(To)); // storing the route in the map // ByteCart.myPlugin.getUm().getMapRoutes().put(getVehicle().getEntityId(), getRoutes(), false); setCurrent(current); this.getRoutes().setLastrouterid(this.getCenter().hashCode()); try { getRoutingTable().serialize(true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Routing.DefaultRouterWanderer#doAction(org.bukkit.block.BlockFace) */ @Override public void doAction(BlockFace To) { this.Update(To); int current = getCurrent(); current = (current == -2 ? 0 : current); if(ByteCart.debug) ByteCart.log.info("ByteCart : doAction() : current is " + current); // If we are turning back, keep current track otherwise discard if (!isSameTrack(To)) getRoutes().setCurrent(-1); this.getRoutes().seenTimestamp(); try { ByteCart.myPlugin.getWandererManager().saveContent(Routes, "Updater", this.getLevel()); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Routing.DefaultRouterWanderer#giveRouterDirection() */ @Override public final BlockFace giveRouterDirection() { return this.selectDirection(); } /** * Get the type of updater * * @return the type */ public final Level getLevel() { return getRoutes().getLevel(); } protected final UpdaterContent getRoutes() { return Routes; } protected final BCCounter getCounter() { return counter; } protected final int getCurrent() { if (getRoutes() != null) // current: track number we are on return getRoutes().getCurrent(); return -1; } protected final void setCurrent(int current) { if (getRoutes() != null) getRoutes().setCurrent(current); } /** * @return true if the IC can receive routes */ private boolean isRouteConsumer() { return getRoutes().getLevel().equals(this.getSignLevel()); } /** * Clear the routing table, keeping ring 0 */ protected void reset() { boolean fullreset = this.getRoutes().isFullreset(); if (fullreset) this.getSignAddress().remove(); // clear routes except route to ring 0 getRoutingTable().clear(fullreset); try { getRoutingTable().serialize(true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Tells if this updater must provide track numbers for this IC * * @return true if this updater must provide track numbers */ protected final boolean isTrackNumberProvider() { return IsTrackNumberProvider; } }
5,231
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
AbstractUpdater.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/AbstractUpdater.java
package com.github.catageek.ByteCart.Updaters; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCart.Routing.RoutingTableWritable; import com.github.catageek.ByteCart.Signs.BC8010; import com.github.catageek.ByteCartAPI.Signs.BCSign; import com.github.catageek.ByteCartAPI.Wanderer.AbstractWanderer; abstract class AbstractUpdater extends AbstractWanderer { private final RoutingTableWritable RoutingTable; protected AbstractUpdater(BCSign bc, int region) { super(bc, region); if (bc instanceof BC8010) { BC8010 ic = (BC8010) bc; RoutingTable = ic.getRoutingTable(); } else { RoutingTable = null; } } /** * Get the direction where to go if we are at the border of a region or the backbone * * @return the direction where we must go */ public final BlockFace manageBorder() { if ((isAtBorder())) { BlockFace dir; if ((dir = this.getRoutingTable().getDirection(this.getWandererRegion())) != null) return dir; return getFrom().getBlockFace(); } return null; } /** * @return the routing table */ protected final RoutingTableWritable getRoutingTable() { return RoutingTable; } }
1,165
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
DefaultRouterWanderer.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Updaters/DefaultRouterWanderer.java
package com.github.catageek.ByteCart.Updaters; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCartAPI.CollisionManagement.IntersectionSide.Side; import com.github.catageek.ByteCartAPI.Signs.BCSign; /** * * This class implements a wanderer that will run through all routers * randomly, without going to branches. * * Wanderers implementors may extends this class and overrides its methods * */ class DefaultRouterWanderer extends AbstractUpdater { DefaultRouterWanderer(BCSign bc, int region) { super(bc, region); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Routing.AbstractWanderer#doAction(com.github.catageek.ByteCart.CollisionManagement.SimpleCollisionAvoider.Side) */ @Override public void doAction(Side To) { return; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Routing.AbstractWanderer#doAction(org.bukkit.block.BlockFace) */ @Override public void doAction(BlockFace To) { } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Routing.AbstractWanderer#giveSimpleDirection() */ @Override public Side giveSimpleDirection() { return Side.LEVER_OFF; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Routing.AbstractWanderer#giveRouterDirection() */ @Override public BlockFace giveRouterDirection() { return getRandomBlockFace(this.getRoutingTable(), this.getFrom().getBlockFace()); } }
1,398
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7009.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7009.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCart.HAL.PinRegistry; import com.github.catageek.ByteCart.IO.ComponentSign; import com.github.catageek.ByteCart.IO.OutputPin; import com.github.catageek.ByteCart.IO.OutputPinFactory; import com.github.catageek.ByteCartAPI.HAL.RegistryOutput; import com.github.catageek.ByteCartAPI.Util.DirectionRegistry; import com.github.catageek.ByteCartAPI.Util.MathUtil; final class BC7009 extends AbstractTriggeredSign implements Triggable { private final BlockFace From; BC7009(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); From = getCardinal().getOppositeFace(); } @Override public void trigger() { this.addIO(); RoundRobin(); } private void RoundRobin() { final ComponentSign sign = new ComponentSign(this.getBlock()); final String line = sign.getLine(3); DirectionRegistry dir; try { int current = Integer.parseInt(line); dir = new DirectionRegistry(current); } catch (NumberFormatException e) { dir = new DirectionRegistry(From); } BlockFace newdir = MathUtil.clockwise(dir.getBlockFace()); if (newdir.equals(From)) newdir = MathUtil.clockwise(newdir); final int amount = new DirectionRegistry(newdir).getAmount(); this.getOutput(0).setAmount(amount); sign.setLine(3, "" + amount); } @Override public String getName() { return "BC7009"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Load Balancer"; } /** * Registers levers as output * * @param from the origin axis * @param center the center of the router */ private final void addIO() { // Center of the device, at sign level org.bukkit.block.Block center = this.getBlock().getRelative(this.getCardinal(), 2).getRelative(MathUtil.clockwise(this.getCardinal())); // Main output OutputPin[] sortie = new OutputPin[4]; // East sortie[0] = OutputPinFactory.getOutput(center.getRelative(BlockFace.WEST,3).getRelative(BlockFace.SOUTH)); // North sortie[1] = OutputPinFactory.getOutput(center.getRelative(BlockFace.EAST,3).getRelative(BlockFace.NORTH)); // South sortie[3] = OutputPinFactory.getOutput(center.getRelative(BlockFace.SOUTH,3).getRelative(BlockFace.EAST)); // West sortie[2] = OutputPinFactory.getOutput(center.getRelative(BlockFace.NORTH,3).getRelative(BlockFace.WEST)); RegistryOutput main = new PinRegistry<OutputPin>(sortie); // output[0] is main levers this.addOutputRegistry(main); } }
2,620
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7003.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7003.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.HAL.AbstractIC; import com.github.catageek.ByteCart.HAL.PinRegistry; import com.github.catageek.ByteCart.IO.InputFactory; import com.github.catageek.ByteCart.IO.InputPin; import com.github.catageek.ByteCart.IO.OutputPin; import com.github.catageek.ByteCart.IO.OutputPinFactory; import com.github.catageek.ByteCart.Storage.ExpirableMap; import com.github.catageek.ByteCart.ThreadManagement.Expirable; import com.github.catageek.ByteCartAPI.HAL.RegistryOutput; import com.github.catageek.ByteCartAPI.Util.MathUtil; /** * A cart counter */ final class BC7003 extends AbstractIC implements Triggable, Powerable { final static private ExpirableMap<org.bukkit.Location, Integer> wavecount = new ExpirableMap<org.bukkit.Location, Integer>(400, false, "BC7003"); BC7003(org.bukkit.block.Block block) { super(block); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { // adding lever as output 0 (if not forced in constructor) this.AddOutputIO(); // We treat the counter try { if (!this.decrementWaveCount()) { (new RemoveCount(ByteCart.myPlugin.Lockduration + 6, true, "Removecount")).reset(getLocation(), this.getOutput(0)); } } catch (Exception e) { if(ByteCart.debug) ByteCart.log.info("ByteCart : "+ e.toString()); e.printStackTrace(); } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Powerable#power() */ @Override public void power() { // check if we are really powered if (! this.getBlock().getRelative(MathUtil.clockwise(getCardinal())).isBlockPowered() && ! this.getBlock().getRelative(MathUtil.anticlockwise(getCardinal())).isBlockPowered()) { return; } // add input command = redstone InputPin[] wire = new InputPin[2]; // Right wire[0] = InputFactory.getInput(this.getBlock().getRelative(BlockFace.UP).getRelative(MathUtil.clockwise(getCardinal()))); // left wire[1] = InputFactory.getInput(this.getBlock().getRelative(BlockFace.UP).getRelative(MathUtil.anticlockwise(getCardinal()))); // InputRegistry[0] = detector this.addInputRegistry(new PinRegistry<InputPin>(wire)); // Adding lever as output 0 this.AddOutputIO(); // if detector is on, the signal is red (= on) if (this.getInput(0).getAmount() != 0) { // setting red signal this.getOutput(0).setAmount(1); this.incrementWaveCount(); (new RemoveCount(400, true, "Removecount")).reset(getLocation(), this.getOutput(0)); wavecount.reset(getLocation(), this.getOutput(0)); } } /** * increment the counter * */ final private void incrementWaveCount() { synchronized(wavecount) { if (!wavecount.contains(this.getLocation())) { wavecount.put(getLocation(), 1); // if(ByteCart.debug) // ByteCart.log.info("ByteCart." + getName() + ": count = " + wavecount.getValue(getBlock()) + " init"); } else { // if(ByteCart.debug) // ByteCart.log.info("ByteCart." + getName() + ": ++count = " + wavecount.getValue(getBlock()) + " before"); wavecount.put(getLocation(), wavecount.get(getLocation()) + 1); // if(ByteCart.debug) // ByteCart.log.info("ByteCart." + getName() + ": ++count = " + wavecount.getValue(getBlock()) + " after"); } } } /** * decrement the counter * * @return true if the counter is strictly positive */ final private boolean decrementWaveCount() { synchronized(wavecount) { if (wavecount.contains(getLocation()) && wavecount.get(getLocation()) > 1) wavecount.put(getLocation(), wavecount.get(getLocation()) - 1); else { wavecount.remove(getLocation()); // if(ByteCart.debug) // ByteCart.log.info("ByteCart." + getName() + ": --count = 0"); return false; } // if(ByteCart.debug) // ByteCart.log.info("ByteCart." + getName() + ": --count = " + wavecount.getValue(getBlock())); return true; } } /** * Add the lever behind the sign to give the red light signal * */ private final void AddOutputIO() { // Declare red light signal = lever OutputPin[] lever = new OutputPin[1]; // Right lever[0] = OutputPinFactory.getOutput(this.getBlock().getRelative(getCardinal(), 2)); // OutputRegistry = red light signal this.addOutputRegistry(new PinRegistry<OutputPin>(lever)); } /** * Runnable to remove the counter after a timeout */ final private class RemoveCount extends Expirable<org.bukkit.Location> { public RemoveCount(long duration, boolean isSync, String name) { super(duration, isSync, name); } @Override public void expire(Object... objects) { ((RegistryOutput) objects[0]).setAmount(0); } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public final String getName() { return "BC7003"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "Cart counter"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#isTrain() */ @Override public boolean isTrain() { return false; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#wasTrain(org.bukkit.Location) */ @Override public boolean wasTrain(org.bukkit.Location loc) { return false; } @Override public boolean isLeverReversed() { return false; } }
5,522
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7004.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7004.java
/** * */ package com.github.catageek.ByteCart.Signs; import org.bukkit.block.BlockFace; import org.bukkit.block.data.Rail; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCart.AddressLayer.AddressString; import com.github.catageek.ByteCart.AddressLayer.TicketFactory; import com.github.catageek.ByteCart.HAL.AbstractIC; import com.github.catageek.ByteCart.HAL.PinRegistry; import com.github.catageek.ByteCart.IO.InputFactory; import com.github.catageek.ByteCart.IO.InputPin; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.Util.MathUtil; /** * A cart spawner */ final class BC7004 extends AbstractIC implements Powerable { private final String type; private final String address; public BC7004(org.bukkit.block.Block block, String type, String address) { super(block); this.type = type; this.address = address; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Powerable#power() */ @Override public void power() { org.bukkit.block.Block block = this.getBlock(); // check if we are really powered if (! block.getRelative(MathUtil.clockwise(getCardinal())).isBlockPowered() && ! block.getRelative(MathUtil.anticlockwise(getCardinal())).isBlockPowered()) { return; } // add input command = redstone InputPin[] wire = new InputPin[2]; // Right wire[0] = InputFactory.getInput(block.getRelative(BlockFace.UP).getRelative(MathUtil.clockwise(getCardinal()))); // left wire[1] = InputFactory.getInput(block.getRelative(BlockFace.UP).getRelative(MathUtil.anticlockwise(getCardinal()))); // InputRegistry[0] = wire this.addInputRegistry(new PinRegistry<InputPin>(wire)); // if wire is on, we spawn a cart if (this.getInput(0).getAmount() != 0) { org.bukkit.block.Block rail = block.getRelative(BlockFace.UP, 2); org.bukkit.Location loc = rail.getLocation(); // check that it is a track, and no cart is there if ((rail.getBlockData() instanceof Rail) && MathUtil.getVehicleByLocation(loc) == null) { Entity entity = block.getWorld().spawnEntity(loc, getType()); // put a ticket in the inventory if necessary if (entity instanceof InventoryHolder && AddressString.isResolvableAddressOrName(address)) { Inventory inv = ((InventoryHolder) entity).getInventory(); TicketFactory.getOrCreateTicket(inv); Address dst = AddressFactory.getAddress(inv); dst.setAddress(address); dst.finalizeAddress(); } } } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC7004"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Cart spawner"; } /** * Get the type of cart to spawn * * @return the type */ private EntityType getType() { if(type.equalsIgnoreCase("storage")) { return EntityType.MINECART_CHEST; } if(type.equalsIgnoreCase("furnace")) { return EntityType.MINECART_FURNACE; } if(type.equalsIgnoreCase("hopper")) { return EntityType.MINECART_HOPPER; } return EntityType.MINECART; } }
3,382
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC9128.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC9128.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCartAPI.Signs.HasNetmask; import com.github.catageek.ByteCartAPI.Signs.Subnet; /** * A 128-station subnet bound */ final class BC9128 extends AbstractBC9000 implements Subnet,HasNetmask, Triggable { BC9128(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.netmask = 1; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#getName() */ @Override public final String getName() { return "BC9128"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "128-station subnet"; } }
753
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
AbstractSimpleCrossroad.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/AbstractSimpleCrossroad.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCart.AddressLayer.AddressRouted; import com.github.catageek.ByteCart.CollisionManagement.CollisionAvoiderBuilder; import com.github.catageek.ByteCart.CollisionManagement.SimpleCollisionAvoider; import com.github.catageek.ByteCart.CollisionManagement.SimpleCollisionAvoiderBuilder; import com.github.catageek.ByteCart.HAL.PinRegistry; import com.github.catageek.ByteCart.IO.OutputPin; import com.github.catageek.ByteCart.IO.OutputPinFactory; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.CollisionManagement.IntersectionSide.Side; import com.github.catageek.ByteCartAPI.HAL.RegistryBoth; import com.github.catageek.ByteCartAPI.HAL.RegistryInput; import com.github.catageek.ByteCartAPI.Signs.BCSign; import com.github.catageek.ByteCartAPI.Util.MathUtil; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; /** * An abstract class for T-intersection signs */ abstract class AbstractSimpleCrossroad extends AbstractTriggeredSign implements BCSign { protected CollisionAvoiderBuilder builder; private AddressRouted destination; AbstractSimpleCrossroad(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); builder = new SimpleCollisionAvoiderBuilder(this, block.getRelative(this.getCardinal(), 3).getLocation()); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override abstract public String getName(); /** * Register the inputs and outputs * */ protected void addIO() { // Output[0] = 2 bits registry representing levers on the left and on the right of the sign OutputPin[] lever2 = new OutputPin[3]; // Left lever2[0] = OutputPinFactory.getOutput(this.getBlock().getRelative(MathUtil.anticlockwise(this.getCardinal()))); // Right lever2[1] = OutputPinFactory.getOutput(this.getBlock().getRelative(MathUtil.clockwise(this.getCardinal()))); // Back lever2[2] = OutputPinFactory.getOutput(this.getBlock().getRelative(this.getCardinal())); PinRegistry<OutputPin> command1 = new PinRegistry<OutputPin>(lever2); this.addOutputRegistry(command1); } protected final void addIOInv() { // Input[0] = destination region taken from Inventory, slot #0 Address IPaddress = getDestinationAddress(); if (IPaddress == null) return; RegistryInput slot2 = IPaddress.getRegion(); this.addInputRegistry(slot2); // Input[1] = destination track taken from cart, slot #1 RegistryInput slot1 = IPaddress.getTrack(); this.addInputRegistry(slot1); // Input[2] = destination station taken from cart, slot #2 RegistryBoth slot0 = IPaddress.getStation(); this.addInputRegistry(slot0); } protected void manageWanderer(SimpleCollisionAvoider intersection) { // routing intersection.WishToGo(route(), false); } protected Side route() { return Side.LEVER_OFF; } @Override public void trigger() { try { this.addIO(); SimpleCollisionAvoider intersection = ByteCart.myPlugin.getCollisionAvoiderManager().<SimpleCollisionAvoider>getCollisionAvoider(builder); if (! ByteCart.myPlugin.getWandererManager().isWanderer(getInventory())) { boolean isTrain = AbstractTriggeredSign.isTrain(getDestinationAddress()); // if this is a cart in a train if (this.wasTrain(this.getLocation())) { ByteCart.myPlugin.getIsTrainManager().getMap().reset(getBlock().getLocation()); intersection.Book(isTrain); return; } // if this is the first car of a train // we keep it during 2 s if (isTrain) { this.setWasTrain(this.getLocation(), true); } intersection.WishToGo(this.route(), isTrain); return; } manageWanderer(intersection); } catch (ClassCastException e) { if(ByteCart.debug) ByteCart.log.info("ByteCart : " + e.toString()); // Not the good blocks to build the signs return; } catch (NullPointerException e) { if(ByteCart.debug) ByteCart.log.info("ByteCart : "+ e.toString()); e.printStackTrace(); // there was no inventory in the cart return; } } protected final AddressRouted getDestinationAddress() { if (destination != null) return destination; return destination = AddressFactory.getAddress(this.getInventory()); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BCSign#getLevel() */ @Override public Wanderer.Level getLevel() { return Wanderer.Level.LOCAL; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BCSign#getSignAddress() */ @Override public final Address getSignAddress() { return AddressFactory.getAddress(getBlock(), 3); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BCSign#getCenter() */ @Override public final org.bukkit.block.Block getCenter() { return this.getBlock(); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BCSign#getDestinationIP() */ @Override public final String getDestinationIP() { Address ip; if ((ip = getDestinationAddress()) != null) return ip.toString(); return ""; } }
5,235
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
package-info.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/package-info.java
/** * */ /** * All ICs are in this package */ package com.github.catageek.ByteCart.Signs;
94
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC8020.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC8020.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressRouted; import com.github.catageek.ByteCart.Routing.RoutingTableWritable; import com.github.catageek.ByteCart.Wanderer.BCWandererManager; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.Signs.BCRouter; import com.github.catageek.ByteCartAPI.Wanderer.AbstractWanderer; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer.Scope; /** * An IC at the entry of a L2 router */ class BC8020 extends BC8010 implements BCRouter, Triggable, HasRoutingTable { BC8020(Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.IsTrackNumberProvider = false; } BC8020(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle, boolean isOldVersion) { super(block, vehicle, isOldVersion); this.IsTrackNumberProvider = false; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC8010#selectUpdater() */ @Override protected boolean selectWanderer() { final BCWandererManager wm = ByteCart.myPlugin.getWandererManager(); return (! wm.isWanderer(this.getInventory())) || wm.isWanderer(this.getInventory(), Scope.LOCAL); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC8010#SelectRoute(com.github.catageek.ByteCart.AddressLayer.AddressRouted, com.github.catageek.ByteCart.AddressLayer.Address, com.github.catageek.ByteCart.Routing.RoutingTableWritable) */ @Override protected BlockFace SelectRoute(AddressRouted IPaddress, Address sign, RoutingTableWritable RoutingTable) { try { if (IPaddress.getTTL() != 0) { // lookup destination region return RoutingTable.getDirection(IPaddress.getRegion().getAmount()); } } catch (NullPointerException e) { } // if TTL reached end of life and is not returnable, then we lookup region 0 try { return RoutingTable.getDirection(0); } catch (NullPointerException e) { } // If everything has failed, then we randomize output direction return AbstractWanderer.getRandomBlockFace(RoutingTable, getCardinal().getOppositeFace()); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC8010#getLevel() */ @Override public Wanderer.Level getLevel() { return Wanderer.Level.BACKBONE; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC8010#getName() */ @Override public String getName() { return "BC8020"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC8010#getFriendlyName() */ @Override public String getFriendlyName() { return "L2 Router"; } }
2,787
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7008.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7008.java
/** * */ package com.github.catageek.ByteCart.Signs; import java.util.ListIterator; import org.bukkit.World; import org.bukkit.block.BlockFace; import org.bukkit.entity.Vehicle; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import com.github.catageek.ByteCart.ByteCart; /** * A cart remover */ final class BC7008 extends AbstractTriggeredSign implements Triggable { /** * @param block */ public BC7008(org.bukkit.block.Block block, Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC7008"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Cart remover"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { org.bukkit.entity.Vehicle vehicle = this.getVehicle(); // we eject the passenger vehicle.eject(); // we drop items if (ByteCart.myPlugin.keepItems()) { org.bukkit.inventory.Inventory inventory; if (vehicle instanceof InventoryHolder) { inventory = ((InventoryHolder) vehicle).getInventory(); World world = this.getBlock().getWorld(); org.bukkit.Location loc = this.getBlock().getRelative(BlockFace.UP, 2).getLocation(); ListIterator<ItemStack> it = inventory.iterator(); while (it.hasNext()) { ItemStack stack = it.next(); if (stack != null) world.dropItem(loc, stack); } } } vehicle.remove(); } }
1,638
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
Powerable.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/Powerable.java
package com.github.catageek.ByteCart.Signs; import java.io.IOException; import com.github.catageek.ByteCartAPI.HAL.IC; /** * An IC that can be powered should implement this */ public interface Powerable extends IC { /** * Method called when the IC is powered * * @throws ClassNotFoundException * @throws IOException */ public void power(); }
360
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
AbstractBC9000.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/AbstractBC9000.java
package com.github.catageek.ByteCart.Signs; import java.io.IOException; import org.bukkit.Bukkit; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressRouted; import com.github.catageek.ByteCart.CollisionManagement.SimpleCollisionAvoider; import com.github.catageek.ByteCart.HAL.SubRegistry; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.CollisionManagement.IntersectionSide.Side; import com.github.catageek.ByteCartAPI.Event.SignPostSubnetEvent; import com.github.catageek.ByteCartAPI.Event.SignPreSubnetEvent; import com.github.catageek.ByteCartAPI.HAL.RegistryBoth; import com.github.catageek.ByteCartAPI.HAL.RegistryInput; import com.github.catageek.ByteCartAPI.Signs.HasNetmask; import com.github.catageek.ByteCartAPI.Signs.Subnet; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; /** * An abstract class for all subnet class */ abstract class AbstractBC9000 extends AbstractSimpleCrossroad implements Subnet,HasNetmask { protected int netmask; AbstractBC9000(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#trigger() */ @Override public void trigger() { try { this.addIO(); SimpleCollisionAvoider intersection = ByteCart.myPlugin.getCollisionAvoiderManager().<SimpleCollisionAvoider>getCollisionAvoider(builder); if (! ByteCart.myPlugin.getWandererManager().isWanderer(getInventory())) { boolean isTrain = AbstractTriggeredSign.isTrain(getDestinationAddress()); // if this is a cart in a train if (this.wasTrain(this.getLocation())) { ByteCart.myPlugin.getIsTrainManager().getMap().reset(getBlock().getLocation()); intersection.Book(isTrain); return; } // if this is the first car of a train // we keep it during 2 s if (isTrain) { this.setWasTrain(this.getLocation(), true); } Side result = intersection.WishToGo(this.route(), isTrain); SignPostSubnetEvent event = new SignPostSubnetEvent(this, result); Bukkit.getServer().getPluginManager().callEvent(event); return; } manageWanderer(intersection); } catch (ClassCastException e) { if(ByteCart.debug) ByteCart.log.info("ByteCart : " + e.toString()); // Not the good blocks to build the signs return; } catch (NullPointerException e) { if(ByteCart.debug) ByteCart.log.info("ByteCart : "+ e.toString()); e.printStackTrace(); // there was no inventory in the cart return; } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#manageUpdater(com.github.catageek.ByteCart.CollisionManagement.SimpleCollisionAvoider) */ @Override protected void manageWanderer(SimpleCollisionAvoider intersection) { // it's an updater, so let it choosing direction Wanderer wanderer; try { wanderer = ByteCart.myPlugin.getWandererManager().getFactory(this.getInventory()).getWanderer(this, this.getInventory()); // routing Side to = intersection.WishToGo(wanderer.giveSimpleDirection(), false); // here we perform routes update wanderer.doAction(to); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#route() */ @Override protected Side route() { SignPreSubnetEvent event; AddressRouted dst = this.getDestinationAddress(); int ttl; if (this.isAddressMatching() && (ttl = dst.getTTL()) != 0) { dst.updateTTL(ttl -1); dst.finalizeAddress(); event = new SignPreSubnetEvent(this, Side.LEVER_ON); } else event = new SignPreSubnetEvent(this, Side.LEVER_OFF); Bukkit.getServer().getPluginManager().callEvent(event); return event.getSide(); } /** * Get the first station of the subnet * * @param station a station number in the subnet * @return the first station number */ private RegistryBoth applyNetmask(RegistryBoth station) { if (this.netmask < station.length()) return new SubRegistry<RegistryBoth>(station, this.netmask, 0); return station; } /** * Tell if the address stored in the ticket is matching the subnet address stored in the IC * * @return true if the address is in the subnet */ protected boolean isAddressMatching() { try { return this.getInput(2).getAmount() == this.getInput(5).getAmount() && this.getInput(1).getAmount() == this.getInput(4).getAmount() && this.getInput(0).getAmount() == this.getInput(3).getAmount(); } catch (NullPointerException e) { // there is no address on sign } return false; } /* * Configures all IO ports of this sign. * * The following input pins are configured: * 0: vehicle region * 1: vehicle track * 2: vehicle station (w/ applied net mask) * 3: sign region * 4: sign track * 5: sign station (w/ applied net mask) * * The following output pins are configured: * 0: left lever * 1: right lever */ /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#addIO() */ @Override protected void addIO() { Address sign = this.getSignAddress(); super.addIO(); // Input[0] = destination region taken from Inventory, slot #0 Address IPaddress = getDestinationAddress(); if (IPaddress == null) return; RegistryInput slot2 = IPaddress.getRegion(); this.addInputRegistry(slot2); // Input[1] = destination track taken from cart, slot #1 RegistryInput slot1 = IPaddress.getTrack(); this.addInputRegistry(slot1); // Input[2] = destination station taken from cart, slot #2, 6 bits RegistryBoth slot0 = IPaddress.getStation(); // We keep only the X most significant bits (netmask) slot0 = applyNetmask(slot0); this.addInputRegistry(slot0); // Address is on a sign, line #3 // Input[3] = region from sign, line #3, 6 bits registry // Input[4] = track from sign, line #3, 6 bits registry // Input[5] = station number from sign, line #0, 6 bits registry this.addAddressAsInputs(sign); } /** * Register the given address as an input of the IC * * This method will register 3 inputs. * * @param addr the address to register */ private void addAddressAsInputs(Address addr) { if(addr.isValid()) { RegistryInput region = addr.getRegion(); this.addInputRegistry(region); RegistryInput track = addr.getTrack(); this.addInputRegistry(track); RegistryBoth station = addr.getStation(); station = applyNetmask(station); this.addInputRegistry(station); } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.HasNetmask#getNetmask() */ @Override public final int getNetmask() { return netmask; } }
6,932
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7020.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7020.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.HAL.PinRegistry; import com.github.catageek.ByteCart.IO.OutputPin; import com.github.catageek.ByteCart.IO.OutputPinFactory; import com.github.catageek.ByteCartAPI.Util.MathUtil; /** * Power the lever on the train including wagons */ class BC7020 extends AbstractTriggeredSign implements Triggable { BC7020(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { addIO(); // if this is a cart in a train if (this.wasTrain(this.getLocation())) { ByteCart.myPlugin.getIsTrainManager().getMap().reset(getLocation()); actionWagon(); return; } if (this.isTrain()) { this.setWasTrain(this.getLocation(), true); this.getOutput(0).setAmount(3); // activate levers } else this.getOutput(0).setAmount(0); // deactivate levers } /** * A method called on each wagon of the train * */ protected void actionWagon() { } /** * Register the output levers * */ private void addIO() { // Output[0] = 2 bits registry representing levers on the left and on the right of the sign OutputPin[] lever2 = new OutputPin[2]; // Left lever2[0] = OutputPinFactory.getOutput(this.getBlock().getRelative(MathUtil.anticlockwise(this.getCardinal()))); // Right lever2[1] = OutputPinFactory.getOutput(this.getBlock().getRelative(MathUtil.clockwise(this.getCardinal()))); PinRegistry<OutputPin> command1 = new PinRegistry<OutputPin>(lever2); this.addOutputRegistry(command1); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC7020"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Is a Train ?"; } }
2,037
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
AbstractTriggeredSign.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/AbstractTriggeredSign.java
package com.github.catageek.ByteCart.Signs; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Minecart; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCart.AddressLayer.AddressRouted; import com.github.catageek.ByteCart.AddressLayer.TicketFactory; import com.github.catageek.ByteCart.HAL.AbstractIC; import com.github.catageek.ByteCartAPI.AddressLayer.Address; /** * Base class for all signs that are triggered by vehicles that pass over it. * * Reads the address configuration of the vehicle from its inventory and caches it. */ abstract class AbstractTriggeredSign extends AbstractIC implements Triggable { private final org.bukkit.entity.Vehicle Vehicle; private org.bukkit.inventory.Inventory Inventory; AbstractTriggeredSign(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block); this.Vehicle = vehicle; this.Inventory = this.extractInventory(); } /** * @return The vehicle which triggered the sign. */ final public org.bukkit.entity.Vehicle getVehicle() { return Vehicle; } /** * Extract the address configuration of the current vehicle. If the vehicle has * no address configuration, the default address (if configured) is applied. * * @return Inventory with address configuration from the current vehicle. */ final private org.bukkit.inventory.Inventory extractInventory() { org.bukkit.inventory.Inventory newInv = Bukkit.createInventory(null, 27); // we load inventory of cart or player if (this.Vehicle != null) { if (this.getVehicle() instanceof InventoryHolder) return ((InventoryHolder) this.getVehicle()).getInventory(); else if (this.getVehicle() instanceof Minecart) { final List<Entity> passengers = this.getVehicle().getPassengers(); for (Entity passenger : passengers) { if (passenger instanceof InventoryHolder) { if (passenger instanceof Player) { if(ByteCart.debug) ByteCart.log.info("ByteCart: loading player inventory :" + ((Player) passenger).getDisplayName()); } return ((InventoryHolder) passenger).getInventory(); } } } /* There is no inventory, so we create one */ // we have a default route ? so we write it in inventory if (ByteCart.myPlugin.getConfig().contains("EmptyCartsDefaultRoute")) { String DefaultRoute = ByteCart.myPlugin.getConfig().getString("EmptyCartsDefaultRoute"); TicketFactory.getOrCreateTicket(newInv); //construct address object AddressRouted myAddress = AddressFactory.getAddress(newInv); //write address myAddress.setAddress(DefaultRoute); myAddress.initializeTTL(); myAddress.finalizeAddress(); } } return newInv; } /** * @return The inventory of the vehicle which triggered this sign. */ public org.bukkit.inventory.Inventory getInventory() { return Inventory; } /** * Set the inventory variable * * @param inv */ protected void setInventory(org.bukkit.inventory.Inventory inv) { this.Inventory = inv; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#isTrain() */ @Override public final boolean isTrain() { return AbstractTriggeredSign.isTrain(AddressFactory.getAddress(this.getInventory())); } public static final boolean isTrain(Address address) { if (address != null) return address.isTrain(); return false; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#wasTrain(org.bukkit.Location) */ @Override public final boolean wasTrain(Location loc) { boolean ret; if (ByteCart.myPlugin.getIsTrainManager().getMap().contains(loc)) { ret = ByteCart.myPlugin.getIsTrainManager().getMap().get(loc); /* if(ByteCart.debug && ret) ByteCart.log.info("ByteCart: "+ this.getName() + " at " + this.getLocation() + " : " + this.getVehicle() + " is wagon !"); */ return ret; } /* if(ByteCart.debug) ByteCart.log.info("ByteCart: "+ this.getName() + " at " + this.getLocation() + " : " + this.getVehicle() + " is not wagon !"); */ return false; } /** * Remember the train bit * * @param loc the location where to store the bit * @param b the bit */ protected final void setWasTrain(Location loc, boolean b) { if (b) ByteCart.myPlugin.getIsTrainManager().getMap().put(loc, true); } /** * Default is lever not reversed * @return false */ @Override public boolean isLeverReversed() { return false; } }
4,668
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7017.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7017.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCart.AddressLayer.AddressRouted; import com.github.catageek.ByteCart.AddressLayer.ReturnAddressFactory; import com.github.catageek.ByteCartAPI.AddressLayer.Address; /** * A block that makes the cart return to its origin using return address */ public final class BC7017 extends AbstractTriggeredSign implements Triggable { BC7017(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } public BC7017(org.bukkit.block.Block block, Player player) { super(block, null); this.setInventory(player.getInventory()); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC7017"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Return back"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { Address returnAddress = ReturnAddressFactory.getAddress(this.getInventory()); if (returnAddress == null || ! returnAddress.isReturnable()) return; String returnAddressString = returnAddress.toString(); AddressRouted targetAddress = AddressFactory.getAddress(getInventory()); if(ByteCart.debug) ByteCart.log.info("ByteCart: 7017 : Writing address " + returnAddressString); returnAddress.remove(); returnAddress.finalizeAddress(); boolean isTrain = targetAddress.isTrain(); targetAddress.setAddress(returnAddressString); targetAddress.setTrain(isTrain); if (this.getInventory().getHolder() instanceof Player) ((Player) this.getInventory().getHolder()).sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + ByteCart.myPlugin.getConfig().getString("Info.SetAddress") + " (" + ChatColor.RED + returnAddressString + ")"); targetAddress.initializeTTL(); targetAddress.finalizeAddress(); } }
2,191
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC9064.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC9064.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCartAPI.Signs.HasNetmask; import com.github.catageek.ByteCartAPI.Signs.Subnet; /** * A 64-station subnet bound */ final class BC9064 extends AbstractBC9000 implements Subnet,HasNetmask, Triggable { BC9064(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.netmask = 2; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#getName() */ @Override public final String getName() { return "BC9064"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "64-station subnet"; } }
751
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7014.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7014.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCart.AddressLayer.AddressRouted; import com.github.catageek.ByteCart.IO.InputFactory; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.HAL.RegistryInput; import com.github.catageek.ByteCartAPI.Util.MathUtil; /** * A station field setter using a redstone signal strength */ class BC7014 extends BC7010 implements Triggable { BC7014(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.StorageCartAllowed = true; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#getAddressToWrite() */ @Override protected Address getAddressToWrite() { addIO(); AddressRouted InvAddress = AddressFactory.getAddress(this.getInventory()); if (InvAddress == null) return null; RegistryInput wire = this.getInput(0); if (wire == null || wire.getAmount() == 0) return null; if(ByteCart.debug) ByteCart.log.info("ByteCart: "+ this.getName() + " wire : " + wire.getAmount()); return AddressFactory.getAddress(format(wire, InvAddress)); } /** * Build the address string * * @param wire the wire to take as input * @param InvAddress the address to modify * @return a string containing the address */ protected String format(RegistryInput wire, AddressRouted InvAddress) { return ""+InvAddress.getRegion().getAmount()+"." +InvAddress.getTrack().getAmount()+"." +wire.getAmount(); } /** * Register the input wire on the left of the sign * */ protected void addIO() { // Input[0] : wire on left org.bukkit.block.Block block = this.getBlock().getRelative(BlockFace.UP).getRelative(MathUtil.anticlockwise(getCardinal())); RegistryInput wire = InputFactory.getInput(block); this.addInputRegistry(wire); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#getIsTrain() */ @Override protected final boolean getIsTrain() { boolean signtrain = super.getIsTrain(); Address address; if((address = AddressFactory.getAddress(this.getInventory())) != null) return address.isTrain() || signtrain; return signtrain; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#getName() */ @Override public String getName() { return "BC7014"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#getFriendlyName() */ @Override public String getFriendlyName() { return "setStation"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#forceTicketReuse() */ @Override protected boolean forceTicketReuse() { return true; } }
2,819
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7021.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7021.java
package com.github.catageek.ByteCart.Signs; /** * Power the lever on the train head but not on wagons */ final class BC7021 extends BC7020 implements Triggable { BC7021(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7020#actionWagon() */ @Override protected void actionWagon() { this.getOutput(0).setAmount(0); // deactivate levers } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7020#getName() */ @Override public final String getName() { return "BC7021"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7020#getFriendlyName() */ @Override public final String getFriendlyName() { return "Train head"; } }
788
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7013.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7013.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.block.BlockFace; import com.github.catageek.ByteCart.AddressLayer.AddressRouted; import com.github.catageek.ByteCart.HAL.PinRegistry; import com.github.catageek.ByteCart.HAL.SuperRegistry; import com.github.catageek.ByteCart.IO.InputFactory; import com.github.catageek.ByteCart.IO.InputPin; import com.github.catageek.ByteCartAPI.HAL.RegistryInput; import com.github.catageek.ByteCartAPI.Util.MathUtil; /** * A ring field setter using redstone */ class BC7013 extends BC7014 implements Triggable { BC7013(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7014#format(com.github.catageek.ByteCart.HAL.RegistryInput, com.github.catageek.ByteCart.AddressLayer.AddressRouted) */ @Override protected String format(RegistryInput wire, AddressRouted InvAddress) { return ""+InvAddress.getRegion().getAmount()+"." +wire.getAmount()+"." +InvAddress.getStation().getAmount(); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7014#addIO() */ @Override protected void addIO() { // Input[0] : wire on left org.bukkit.block.Block block = this.getBlock().getRelative(BlockFace.UP).getRelative(MathUtil.anticlockwise(getCardinal())); RegistryInput wire = InputFactory.getInput(block); InputPin[] levers = new InputPin[2]; block = this.getBlock().getRelative(BlockFace.UP).getRelative(MathUtil.clockwise(getCardinal())); levers[0] = InputFactory.getInput(block); block = this.getBlock().getRelative(getCardinal().getOppositeFace()); levers[1] = InputFactory.getInput(block); RegistryInput ret = new SuperRegistry<RegistryInput>(new PinRegistry<InputPin>(levers), wire); this.addInputRegistry(ret); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7014#getName() */ @Override public String getName() { return "BC7013"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7014#getFriendlyName() */ @Override public String getFriendlyName() { return "setTrack"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7014#forceTicketReuse() */ @Override protected boolean forceTicketReuse() { return true; } }
2,308
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
HasRoutingTable.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/HasRoutingTable.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCart.Routing.RoutingTableWritable; /** * An IC that have a routing table should implement this */ interface HasRoutingTable { /** * Get the routing table * * @return the routing table */ public RoutingTableWritable getRoutingTable(); }
325
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC8021.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC8021.java
package com.github.catageek.ByteCart.Signs; import java.io.IOException; import org.bukkit.block.BlockState; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.Routing.RoutingTableFactory; import com.github.catageek.ByteCart.Routing.RoutingTableWritable; import com.github.catageek.ByteCartAPI.Signs.BCRouter; import com.google.gson.JsonSyntaxException; class BC8021 extends BC8020 implements BCRouter, Triggable, HasRoutingTable { BC8021(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle, false); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC8010#loadChest() */ protected RoutingTableWritable loadChest() { BlockState blockstate; if ((blockstate = getCenter().getState()) instanceof InventoryHolder) { // Loading inventory of chest at same level of the sign Inventory ChestInventory = ((InventoryHolder) blockstate).getInventory(); // Converting inventory in routing table try { return RoutingTableFactory.getRoutingTable(ChestInventory, 0); } catch (JsonSyntaxException | ClassNotFoundException | IOException e) { ByteCart.log.info("ByteCart: Error while loading chest at position " + this.getCenter().getLocation() + ". Please clean its content and run bcupdater region command."); return null; } } else { return null; } } @Override public String getName() { return "BC8021"; } }
1,521
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7010.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7010.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.ChatColor; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCart.AddressLayer.AddressRouted; import com.github.catageek.ByteCart.AddressLayer.TicketFactory; import com.github.catageek.ByteCart.IO.ComponentSign; import com.github.catageek.ByteCartAPI.AddressLayer.Address; /** * A ticket spawner for players */ public class BC7010 extends AbstractTriggeredSign implements Triggable, Clickable { private boolean PlayerAllowed = true; protected boolean StorageCartAllowed = false; /** * Constructor : !! vehicle can be null !! */ BC7010(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } public BC7010(Block block, Player player) { super(block, null); this.setInventory(player.getInventory()); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public final void trigger() { if (! this.isHolderAllowed() || ByteCart.myPlugin.getWandererManager().isWanderer(getInventory())) return; // if this is a cart in a train if (this.wasTrain(this.getLocation())) { ByteCart.myPlugin.getIsTrainManager().getMap().reset(getLocation()); return; } Address address = getAddressToWrite(); if (address == null) return; boolean isTrain = getIsTrain(); this.setAddress(address.toString(), this.getNameToWrite(), isTrain); // if this is the first car of a train // we save the state during 2 s if (isTrain) { this.setWasTrain(this.getLocation(), true); } } /** * Provide the train bit value to set * * @return the train bit value */ protected boolean getIsTrain() { return (new ComponentSign(this.getBlock())).getLine(0).equalsIgnoreCase("train"); } /** * Provide the address to set in ticket * * @return the address to write */ protected Address getAddressToWrite() { Address Address = AddressFactory.getAddress(this.getBlock(), 3); return Address; } /** * Provide the name to display for the destination * * @return the name */ private String getNameToWrite() { return (new ComponentSign(this.getBlock())).getLine(2); } /** * Get the destination address of an existing ticket * * @return the destination address */ protected AddressRouted getTargetAddress() { return AddressFactory.getAddress(this.getInventory()); } /** * Spawn a ticket in inventory and set the destination address * The train bit is not set. * * @param SignAddress the destination address * @param name the destination name * @return true if success, false otherwise */ public final boolean setAddress(String SignAddress, String name){ return setAddress(SignAddress, name, false); } /** * Spawn a ticket in inventory and set the destination address * * @param SignAddress the destination address * @param name the destination name * @param train true if it is a train head * @return true if success, false otherwise */ public final boolean setAddress(String SignAddress, String name, boolean train){ Player player = null; if (this.getInventory().getHolder() instanceof Player) player = (Player) this.getInventory().getHolder(); if (player == null) TicketFactory.getOrCreateTicket(this.getInventory()); else TicketFactory.getOrCreateTicket(player, forceTicketReuse()); AddressRouted IPaddress = getTargetAddress(); if (IPaddress == null || !IPaddress.setAddress(SignAddress)) { if (this.getInventory().getHolder() instanceof Player) { ((Player) this.getInventory().getHolder()).sendMessage(ChatColor.GREEN+"[Bytecart] " + ChatColor.RED + ByteCart.myPlugin.getConfig().getString("Error.SetAddress") ); } return false; } if (this.getInventory().getHolder() instanceof Player) { this.infoPlayer(SignAddress); } IPaddress.initializeTTL(); IPaddress.setTrain(train); IPaddress.finalizeAddress(); return true; } /** * Checks that the requestor is allowed to use this IC * * @return true if the requestor is allowed */ private final boolean isHolderAllowed() { InventoryHolder holder = this.getInventory().getHolder(); if (holder instanceof Player) return PlayerAllowed; return StorageCartAllowed; } /** * Send message to player in the chat window * * @param signAddress the address got by the player */ protected void infoPlayer(String signAddress) { ((Player) this.getInventory().getHolder()).sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + ByteCart.myPlugin.getConfig().getString("Info.SetAddress") + " " + ChatColor.RED + signAddress); if (this.getVehicle() == null && ! ByteCart.myPlugin.getConfig().getBoolean("usebooks")) ((Player) this.getInventory().getHolder()).sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + ByteCart.myPlugin.getConfig().getString("Info.SetAddress2") ); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Clickable#click() */ @Override public final void click() { this.trigger(); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC7010"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Goto"; } /** * Tells if we must modify an existing ticket or create a new one * * @return true if modifying, false to create */ protected boolean forceTicketReuse() { return false; } }
5,738
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7019.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7019.java
/** * */ package com.github.catageek.ByteCart.Signs; import java.util.Random; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCart.AddressLayer.AddressString; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.HAL.RegistryBoth; import com.github.catageek.ByteCartAPI.HAL.RegistryInput; /** * Gives random address to a cart */ final class BC7019 extends BC7010 implements Triggable { BC7019(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.StorageCartAllowed = true; this.addIO(); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC7019"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Random address"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#getAddressToWrite() */ @Override protected Address getAddressToWrite() { int startRegion = getInput(3).getAmount(); int endRegion = getInput(0).getAmount(); int newRegion = startRegion + (new Random()).nextInt(endRegion - startRegion +1); int startTrack = getInput(4).getAmount(); int endTrack = getInput(1).getAmount(); int newTrack = startTrack + (new Random()).nextInt(endTrack - startTrack +1); int startStation = getInput(5).getAmount(); int endStation = getInput(2).getAmount(); int newStation = startStation + (new Random()).nextInt(endStation - startStation +1); StringBuilder sb = new StringBuilder(); String dot = "."; sb.append(newRegion).append(dot).append(newTrack).append(dot).append(newStation); return new AddressString(sb.toString(), false); } private void addIO() { // add input [0], [1] and [2] from 4th line this.addAddressAsInputs(AddressFactory.getAddress(getBlock(), 3)); // add input [3], [4] and [5] from 3th line this.addAddressAsInputs(AddressFactory.getAddress(getBlock(), 2)); } private void addAddressAsInputs(Address addr) { if(addr.isValid()) { RegistryInput region = addr.getRegion(); this.addInputRegistry(region); RegistryInput track = addr.getTrack(); this.addInputRegistry(track); RegistryBoth station = addr.getStation(); this.addInputRegistry(station); } } }
2,413
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC9000.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC9000.java
package com.github.catageek.ByteCart.Signs; import java.io.IOException; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.CollisionManagement.SimpleCollisionAvoider; import com.github.catageek.ByteCart.Updaters.UpdaterLocal; import com.github.catageek.ByteCartAPI.Signs.Subnet; /** * A simple intersection block with anticollision */ final class BC9000 extends AbstractSimpleCrossroad implements Subnet, Triggable { private final int netmask; BC9000(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.netmask = 0; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#manageUpdater(com.github.catageek.ByteCart.CollisionManagement.SimpleCollisionAvoider) */ @Override protected void manageWanderer(SimpleCollisionAvoider intersection) { // it's an updater, so let it choosing direction super.manageWanderer(intersection); if (ByteCart.myPlugin.getConfig().getBoolean("oldBC9000behaviour", true)) { UpdaterLocal updater; try { updater = (UpdaterLocal) ByteCart.myPlugin.getWandererManager().getFactory(this.getInventory()).getWanderer(this, this.getInventory()); // here we perform routes update updater.leaveSubnet(); updater.save(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#getName() */ @Override public String getName() { return "BC9000"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Collision avoider"; } /** * @return the netmask */ @Override public final int getNetmask() { return netmask; } }
1,945
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC8011.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC8011.java
package com.github.catageek.ByteCart.Signs; import java.io.IOException; import org.bukkit.block.BlockState; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.Routing.RoutingTableFactory; import com.github.catageek.ByteCart.Routing.RoutingTableWritable; import com.github.catageek.ByteCartAPI.Signs.BCRouter; import com.google.gson.JsonSyntaxException; final class BC8011 extends BC8010 implements BCRouter, Triggable, HasRoutingTable { BC8011(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle, false); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC8010#loadChest() */ protected RoutingTableWritable loadChest() { BlockState blockstate; if ((blockstate = getCenter().getState()) instanceof InventoryHolder) { // Loading inventory of chest at same level of the sign Inventory ChestInventory = ((InventoryHolder) blockstate).getInventory(); // Converting inventory in routing table try { return RoutingTableFactory.getRoutingTable(ChestInventory, 0); } catch (JsonSyntaxException | ClassNotFoundException | IOException e) { ByteCart.log.info("ByteCart: Error while loading chest at position " + this.getCenter().getLocation() + ". Please clean its content and run bcupdater region command."); return null; } } else { return null; } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC8010#getName() */ @Override public String getName() { return "BC8011"; } }
1,611
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7016.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7016.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCart.AddressLayer.ReturnAddressFactory; import com.github.catageek.ByteCart.HAL.PinRegistry; import com.github.catageek.ByteCart.IO.OutputPin; import com.github.catageek.ByteCart.IO.OutputPinFactory; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.Util.MathUtil; /** * A return address checker */ final class BC7016 extends AbstractTriggeredSign implements Triggable { BC7016(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC7016"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Is returnable ?"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { addIO(); Address returnAddress = ReturnAddressFactory.getAddress(this.getInventory()); if (returnAddress != null && returnAddress.isReturnable()) this.getOutput(0).setAmount(3); else this.getOutput(0).setAmount(0); } /** * Register the levers output * */ private void addIO() { // Output[0] = 2 bits registry representing levers on the left and on the right of the sign OutputPin[] lever2 = new OutputPin[2]; // Left lever2[0] = OutputPinFactory.getOutput(this.getBlock().getRelative(MathUtil.anticlockwise(this.getCardinal()))); // Right lever2[1] = OutputPinFactory.getOutput(this.getBlock().getRelative(MathUtil.clockwise(this.getCardinal()))); PinRegistry<OutputPin> command1 = new PinRegistry<OutputPin>(lever2); this.addOutputRegistry(command1); } }
1,854
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7002.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7002.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.scheduler.BukkitRunnable; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.HAL.AbstractIC; import com.github.catageek.ByteCart.HAL.PinRegistry; import com.github.catageek.ByteCart.IO.OutputPin; import com.github.catageek.ByteCart.IO.OutputPinFactory; /** * A cart detector */ final class BC7002 extends AbstractTriggeredSign implements Triggable { BC7002(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { OutputPin[] lever = new OutputPin[1]; // Right lever[0] = OutputPinFactory.getOutput(this.getBlock().getRelative(getCardinal())); // OutputRegistry[1] = red light signal this.addOutputRegistry(new PinRegistry<OutputPin>(lever)); this.getOutput(0).setAmount(1); // if(ByteCart.debug) // ByteCart.log.info("ByteCart : BC7002 count 1"); // ByteCart.myPlugin.getDelayedThreadManager().renew(getLocation(), 4, new Release(this)); (new Release(this)).runTaskLater(ByteCart.myPlugin, 4); } private final class Release extends BukkitRunnable { private final AbstractIC bc; public Release(AbstractIC bc) { this.bc = bc; } @Override public void run() { this.bc.getOutput(0).setAmount(0); } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public final String getName() { return "BC7002"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "Cart detector"; } }
1,745
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC9137.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC9137.java
package com.github.catageek.ByteCart.Signs; /** * Match IP ranges and negate the result. * * 1. Empty * 2. [BC9137] * 3. AA.BB.CC * 4. XX.YY.ZZ * * onState <=> !(AA.BB.CC <= IP <= XX.YY.ZZ) */ final class BC9137 extends AbstractBC9037 { BC9137(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractBC9037#negated() */ @Override protected boolean negated() { return true; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#getName() */ @Override public final String getName() { return "BC9137"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "Negated range matcher"; } @Override public boolean isLeverReversed() { return true; } }
924
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7018.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7018.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.entity.Player; import com.github.catageek.ByteCart.AddressLayer.TicketFactory; /** * A ticket remover */ class BC7018 extends AbstractTriggeredSign implements Triggable,Clickable { BC7018(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); // TODO Auto-generated constructor stub } BC7018(org.bukkit.block.Block block, Player player) { super(block, null); this.setInventory(player.getInventory()); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Clickable#click() */ @Override public void click() { this.trigger(); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { TicketFactory.removeTickets(this.getInventory()); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC7018"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Remove Ticket"; } }
1,159
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7012.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7012.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCart.AddressLayer.AddressRouted; import com.github.catageek.ByteCartAPI.HAL.RegistryInput; /** * A region field setter using redstone */ final class BC7012 extends BC7013 implements Triggable { BC7012(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7013#format(com.github.catageek.ByteCart.HAL.RegistryInput, com.github.catageek.ByteCart.AddressLayer.AddressRouted) */ @Override protected String format(RegistryInput wire, AddressRouted InvAddress) { return ""+wire.getAmount()+"." +InvAddress.getTrack().getAmount()+"." +InvAddress.getStation().getAmount(); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7013#getName() */ @Override public final String getName() { return "BC7012"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7013#getFriendlyName() */ @Override public final String getFriendlyName() { return "setRegion"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7013#forceTicketReuse() */ @Override protected boolean forceTicketReuse() { return true; } }
1,260
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
ClickedSignFactory.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/ClickedSignFactory.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.block.data.BlockData; import org.bukkit.block.data.Directional; import org.bukkit.block.data.Rotatable; import org.bukkit.entity.Player; import com.github.catageek.ByteCart.HAL.AbstractIC; import com.github.catageek.ByteCartAPI.Util.MathUtil; /** * This class contains the method to instantiate any IC */ final public class ClickedSignFactory { /** * Get an IC at the clicked sign * * @param block the sign clicked * @param player the player who clicked the sign * @return a Clickable IC, or null */ static final public Clickable getClickedIC(Block block, Player player) { if(AbstractIC.checkEligibility(block)) { // if there is really a BC sign post // we extract its # return ClickedSignFactory.getClickedIC(block, ((Sign) block.getState()).getLine(1), player); } // no BC sign post return null; } /** * Get an IC with a code declared 2 blocks behind the clicked sign * * @param block the sign clicked * @param player the player who clicked the sign * @return a Clickable IC, or null */ static final public Clickable getBackwardClickedIC(Block block, Player player) { final BlockData type = block.getState().getBlockData(); BlockFace f = null; if (type instanceof Directional) { f = ((Directional) type).getFacing().getOppositeFace(); } else if(type instanceof Rotatable) { f = ((Rotatable) type).getRotation().getOppositeFace(); f = MathUtil.straightUp(f); } else { return null; } final Block relative = block.getRelative(f, 2); if (AbstractIC.checkEligibility(relative)) { return ClickedSignFactory.getClickedIC(relative, ((Sign) relative.getState()).getLine(1), player); } return null; } /** * Get an IC with the specific code * * @param block the block where to reference the IC * @param signString the name of the sign as "BCXXXX" * @param player the player who clicked the sign * @return a Clickable IC, or null */ static final public Clickable getClickedIC(Block block, String signString, Player player) { if (signString.length() < 7) return null; int ICnumber = Integer.parseInt(signString.substring(3, 7)); // then we instantiate accordingly switch (ICnumber) { case 7010: return new BC7010(block, player); case 7018: return new BC7018(block, player); } return null; } }
2,494
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7007.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7007.java
/** * */ package com.github.catageek.ByteCart.Signs; import org.bukkit.entity.Minecart; import com.github.catageek.ByteCartAPI.Util.MathUtil; /** * An unbooster */ final class BC7007 extends AbstractTriggeredSign implements Triggable { /** * @param block * @param vehicle */ public BC7007(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { org.bukkit.entity.Vehicle vehicle = this.getVehicle(); Minecart cart = (Minecart) vehicle; if (cart.getMaxSpeed() > 0.4D) cart.setMaxSpeed(0.4D); MathUtil.setSpeed(cart, 0.4D); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC7007"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Unbooster"; } }
1,038
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7015.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7015.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCart.AddressLayer.AddressRouted; import com.github.catageek.ByteCart.AddressLayer.ReturnAddressFactory; import com.github.catageek.ByteCartAPI.AddressLayer.Address; /** * A return address setter */ final class BC7015 extends BC7011 implements Triggable { BC7015(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#getTargetAddress() */ @Override protected AddressRouted getTargetAddress() { return ReturnAddressFactory.getAddress(this.getInventory()); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#getIsTrain() */ @Override protected final boolean getIsTrain() { Address address; if((address = AddressFactory.getAddress(this.getInventory())) != null) return address.isTrain(); return false; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7011#getName() */ @Override public String getName() { return "BC7015"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7011#getFriendlyName() */ @Override public String getFriendlyName() { return "Set Return"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#forceTicketReuse() */ @Override protected boolean forceTicketReuse() { return true; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#infoPlayer(com.github.catageek.ByteCart.AddressLayer.Address) */ @Override protected void infoPlayer(String address) { ((Player) this.getInventory().getHolder()).sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + ByteCart.myPlugin.getConfig().getString("Info.SetReturnAddress") + " " + ChatColor.RED + address); } }
1,996
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC9004.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC9004.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCartAPI.Signs.HasNetmask; import com.github.catageek.ByteCartAPI.Signs.Subnet; /** * A 4-station subnet bound */ final class BC9004 extends AbstractBC9000 implements Subnet,HasNetmask, Triggable { BC9004(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.netmask = 6; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#getName() */ @Override public final String getName() { return "BC9004"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "4-station subnet"; } }
753
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
Clickable.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/Clickable.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCartAPI.HAL.IC; /** * An IC that a player can right-click should implement this */ public interface Clickable extends IC { /** * Method called when a player right-clicks the IC * */ public void click(); }
292
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7011.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7011.java
package com.github.catageek.ByteCart.Signs; /** * A universal ticket spawner */ public class BC7011 extends BC7010 implements Triggable { public BC7011(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.StorageCartAllowed = true; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#getName() */ @Override public String getName() { return "BC7011"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BC7010#getFriendlyName() */ @Override public String getFriendlyName() { return "Storage Goto"; } }
606
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
TriggeredSignFactory.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/TriggeredSignFactory.java
package com.github.catageek.ByteCart.Signs; import java.io.IOException; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.block.data.BlockData; import org.bukkit.block.data.Rail; import org.bukkit.entity.Vehicle; import com.github.catageek.ByteCart.HAL.AbstractIC; import com.github.catageek.ByteCartAPI.Util.MathUtil; /** * This class contains the method to instantiate any IC */ final public class TriggeredSignFactory { /** * Check the sign and instantiate the IC object, or null * * @param block the sign block * @param vehicle the vehicle that triggered the sign * @return a Triggable representing the IC * @throws ClassNotFoundException * @throws IndexOutOfBoundsException * @throws IOException */ static final public Triggable getTriggeredIC(Block block, Vehicle vehicle) { if(AbstractIC.checkEligibility(block)) { // if there is really a BC sign post // we extract its # return TriggeredSignFactory.getTriggeredIC(block, ((Sign) block.getState()).getLine(1), vehicle); } // Maybe the rail is in slope Block block2 = block.getRelative(BlockFace.DOWN); if (AbstractIC.checkEligibility(block2)) { BlockData rail = block.getRelative(BlockFace.UP).getState().getBlockData(); if (rail instanceof Rail && MathUtil.isOnSlope((Rail) rail)) return TriggeredSignFactory.getTriggeredIC(block2, ((Sign) block2.getState()).getLine(1), vehicle); } // no BC sign post return null; } /** * Read the string and instantiate the IC object, or null * * The string must be checked before calling this method * * @param block the sign block * @param signString the string containing the IC number * @param vehicle the vehicle triggering the sign * @return a Triggable representing the IC * @throws ClassNotFoundException * @throws IOException */ static final public Triggable getTriggeredIC(Block block, String signString, Vehicle vehicle) { if (signString.length() < 7) return null; int ICnumber; try { ICnumber = Integer.parseInt(signString.substring(3, 7)); // then we instantiate accordingly switch (ICnumber) { case 7000: case 7001: return (new BC7001(block, vehicle)); case 7002: return (new BC7002(block, vehicle)); case 7003: return (new BC7003(block)); case 7005: return (new BC7005(block, vehicle)); case 7006: return (new BC7006(block, vehicle)); case 7007: return (new BC7007(block, vehicle)); case 7008: return (new BC7008(block, vehicle)); case 7009: return (new BC7009(block, vehicle)); case 7010: return (new BC7010(block, vehicle)); case 7011: return (new BC7011(block, vehicle)); case 7012: return (new BC7012(block, vehicle)); case 7013: return (new BC7013(block, vehicle)); case 7014: return (new BC7014(block, vehicle)); case 7015: return (new BC7015(block, vehicle)); case 7016: return (new BC7016(block, vehicle)); case 7017: return (new BC7017(block, vehicle)); case 7018: return (new BC7018(block, vehicle)); case 7019: return (new BC7019(block, vehicle)); case 7020: return (new BC7020(block, vehicle)); case 7021: return (new BC7021(block, vehicle)); case 8010: return (new BC8010(block, vehicle)); case 8011: return (new BC8011(block, vehicle)); case 8020: return (new BC8020(block, vehicle)); case 8021: return (new BC8021(block, vehicle)); case 9000: return (new BC9000(block, vehicle)); case 9001: return (new BC9001(block, vehicle)); case 9002: return (new BC9002(block, vehicle)); case 9004: return (new BC9004(block, vehicle)); case 9008: return (new BC9008(block, vehicle)); case 9016: return (new BC9016(block, vehicle)); case 9032: return (new BC9032(block, vehicle)); case 9064: return (new BC9064(block, vehicle)); case 9128: return (new BC9128(block, vehicle)); case 9037: return (new BC9037(block, vehicle)); case 9137: return (new BC9137(block, vehicle)); } } catch (NumberFormatException e) { e.printStackTrace(); } return null; } }
4,206
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC9001.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC9001.java
package com.github.catageek.ByteCart.Signs; import java.io.IOException; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCart.HAL.PinRegistry; import com.github.catageek.ByteCart.IO.InputFactory; import com.github.catageek.ByteCart.IO.InputPin; import com.github.catageek.ByteCartAPI.ByteCartAPI; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.CollisionManagement.IntersectionSide; import com.github.catageek.ByteCartAPI.CollisionManagement.IntersectionSide.Side; import com.github.catageek.ByteCartAPI.Event.SignPostStationEvent; import com.github.catageek.ByteCartAPI.Event.SignPreStationEvent; import com.github.catageek.ByteCartAPI.Signs.Station; import com.github.catageek.ByteCartAPI.Util.MathUtil; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; /** * A station sign */ public final class BC9001 extends AbstractBC9000 implements Station, Powerable, Triggable { BC9001(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.netmask = ByteCartAPI.MAXSTATIONLOG; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractBC9000#trigger() */ @Override public void trigger() { try { Address sign = AddressFactory.getAddress(this.getBlock(),3); this.addIO(); // input[6] = redstone for "full station" signal InputPin[] wire = new InputPin[2]; // Right wire[0] = InputFactory.getInput(this.getBlock().getRelative(BlockFace.UP).getRelative(getCardinal(), 2).getRelative(MathUtil.clockwise(getCardinal()))); // left wire[1] = InputFactory.getInput(this.getBlock().getRelative(BlockFace.UP).getRelative(getCardinal(), 2).getRelative(MathUtil.anticlockwise(getCardinal()))); // InputRegistry[0] = start/stop command this.addInputRegistry(new PinRegistry<InputPin>(wire)); triggerBC7003(); if (! ByteCart.myPlugin.getWandererManager().isWanderer(getInventory())) { // if this is a cart in a train if (this.wasTrain(this.getLocation())) { ByteCart.myPlugin.getIsTrainManager().getMap().reset(getLocation()); // this.getOutput(0).setAmount(3); // push buttons return; } // if this is the first car of a train // we keep the state during 2 s if (AbstractTriggeredSign.isTrain(getDestinationAddress())) { this.setWasTrain(this.getLocation(), true); } this.route(); if(this.isAddressMatching() && this.getName().equals("BC9001") && this.getInventory().getHolder() instanceof Player) { ((Player) this.getInventory().getHolder()).sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.GREEN + ByteCart.myPlugin.getConfig().getString("Info.Destination") + " " + this.getFriendlyName() + " (" + sign + ")"); } return; } // it's an wanderer Wanderer wanderer; try { wanderer = ByteCart.myPlugin.getWandererManager().getFactory(this.getInventory()).getWanderer(this, this.getInventory()); // here we perform wanderer action wanderer.doAction(IntersectionSide.Side.LEVER_OFF); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // routing this.getOutput(0).setAmount(0); // unpower levers } catch (ClassCastException e) { if(ByteCart.debug) ByteCart.log.info("ByteCart : " + e.toString()); // Not the good blocks to build the signs return; } catch (NullPointerException e) { if(ByteCart.debug) ByteCart.log.info("ByteCart : "+ e.toString()); e.printStackTrace(); // there was no inventory in the cart return; } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Powerable#power() */ @Override public void power() { this.powerBC7003(); } /** * Manage the red light signal when triggered * */ private void triggerBC7003() { (new BC7003(this.getBlock())).trigger(); } /** * Manage the red light signal when powered * */ private void powerBC7003() { (new BC7003(this.getBlock())).power(); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractBC9000#route() */ @Override protected Side route() { SignPreStationEvent event; SignPostStationEvent event1; // test if every destination field matches sign field if (this.isAddressMatching() && this.getInput(6).getAmount() == 0) event = new SignPreStationEvent(this, Side.LEVER_ON); // power levers if matching else event = new SignPreStationEvent(this, Side.LEVER_OFF); // unpower levers if not matching Bukkit.getServer().getPluginManager().callEvent(event); if (event.getSide().equals(Side.LEVER_ON) && this.getInput(6).getAmount() == 0) { this.getOutput(0).setAmount(Side.LEVER_ON.Value()); // power levers if matching event1 = new SignPostStationEvent(this, Side.LEVER_ON); } else { this.getOutput(0).setAmount(0); // unpower levers if not matching event1 = new SignPostStationEvent(this, Side.LEVER_ON); } Bukkit.getServer().getPluginManager().callEvent(event1); return null; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#getName() */ @Override public final String getName() { return "BC9001"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Station"; } @Override public final String getStationName() { return ((Sign)this.getBlock().getState()).getLine(2); } }
5,817
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC9032.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC9032.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCartAPI.Signs.HasNetmask; import com.github.catageek.ByteCartAPI.Signs.Subnet; /** * A 32-station subnet bound */ final class BC9032 extends AbstractBC9000 implements Subnet,HasNetmask, Triggable { BC9032(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.netmask = 3; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#getName() */ @Override public final String getName() { return "BC9032"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "32-station subnet"; } }
752
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
PoweredSignFactory.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/PoweredSignFactory.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.Sign; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.HAL.AbstractIC; import com.github.catageek.ByteCart.Storage.ExpirableSet; /** * This class contains the method to instantiate any IC */ public class PoweredSignFactory { // Singleton set, keeps records 40 ticks to prevent duplicate private final ExpirableSet<Location> poweredsignsset = new ExpirableSet<Location>(2, false, "PoweredSign"); private Location loc = null; /** * Get an IC at the powered sign * * @param block the sign clicked * @return a Powerable IC, or null */ public Powerable getIC(Block block) { if(AbstractIC.checkEligibility(block) && ! this.poweredsignsset.contains(block.getLocation(loc))) { // if there is really a BC sign post // we extract its # final Powerable ps = PoweredSignFactory.getPoweredIC(block, ((Sign) block.getState()).getLine(1)); // register it as singleton for this location if (ps != null) { this.poweredsignsset.add(block.getLocation(loc)); } return ps; } // no BC sign post return null; } /** * Get an IC with the specific code * * @param block the block where to reference the IC * @param signString the name of the sign as "BCXXXX" * @return a Powerable IC, or null */ static final public Powerable getPoweredIC(Block block, String signString) { if (signString.length() < 7) return null; int ICnumber = Integer.parseInt(signString.substring(3, 7)); try { // then we instantiate accordingly switch (ICnumber) { case 7000: case 7001: return (new BC7001(block, null)); case 7003: return (new BC7003(block)); case 7004: return (new BC7004(block, ((Sign) block.getState()).getLine(3), ((Sign) block.getState()).getLine(2))); case 9001: return (new BC9001(block, null)); } } catch (Exception e) { if(ByteCart.debug) ByteCart.log.info("ByteCart : "+ e.toString()); // there was no inventory in the cart return null; } /* if(ByteCart.debug) ByteCart.log.info("ByteCart: #IC " + ICnumber + " not activated"); */ return null; } }
2,294
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC9016.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC9016.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCartAPI.Signs.HasNetmask; import com.github.catageek.ByteCartAPI.Signs.Subnet; /** * A 16-station subnet bound */ final class BC9016 extends AbstractBC9000 implements Subnet,HasNetmask, Triggable { BC9016(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.netmask = 4; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#getName() */ @Override public final String getName() { return "BC9016"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "16-station subnet"; } }
754
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7001.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7001.java
package com.github.catageek.ByteCart.Signs; import org.bukkit.Location; import org.bukkit.block.BlockFace; import org.bukkit.block.data.BlockData; import org.bukkit.block.data.Rail; import org.bukkit.entity.Minecart; import org.bukkit.entity.Vehicle; import org.bukkit.util.Vector; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.HAL.PinRegistry; import com.github.catageek.ByteCart.IO.InputFactory; import com.github.catageek.ByteCart.IO.InputPin; import com.github.catageek.ByteCart.IO.OutputPin; import com.github.catageek.ByteCart.IO.OutputPinFactory; import com.github.catageek.ByteCartAPI.Util.MathUtil; /** * this IC represents a stop/start block * it is commanded by a wire (like FalseBook 'station' block) * wire on => start or no velocity change * wire off => stop * it provides a busy bit with a lever on the block above the sign * lever off = block occupied and not powered * lever on = block free OR powered */ final class BC7001 extends AbstractTriggeredSign implements Triggable, Powerable { /** * Constructor : !! vehicle can be null !! */ BC7001(org.bukkit.block.Block block, Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { // add output occupied line = lever OutputPin[] lever = new OutputPin[1]; // Right lever[0] = OutputPinFactory.getOutput(this.getBlock().getRelative(getCardinal().getOppositeFace())); // OutputRegistry[0] = occupied signal this.addOutputRegistry(new PinRegistry<OutputPin>(lever)); // here starts the action // is there a minecart above ? if (this.getVehicle() != null) { // add input command = redstone InputPin[] wire = new InputPin[2]; // Right wire[0] = InputFactory.getInput(this.getBlock().getRelative(BlockFace.UP).getRelative(MathUtil.clockwise(getCardinal()))); // left wire[1] = InputFactory.getInput(this.getBlock().getRelative(BlockFace.UP).getRelative(MathUtil.anticlockwise(getCardinal()))); // InputRegistry[0] = start/stop command this.addInputRegistry(new PinRegistry<InputPin>(wire)); // if the wire is on if(this.getInput(0).getAmount() > 0) { if (this.wasTrain(this.getLocation())) ByteCart.myPlugin.getIsTrainManager().getMap().reset(this.getLocation()); if (this.isTrain()) { this.setWasTrain(this.getLocation(), true); } // the lever is on too //this.getOutput(0).setAmount(1); final BC7001 myBC7001 = this; ByteCart.myPlugin.getServer().getScheduler().scheduleSyncDelayedTask(ByteCart.myPlugin, new Runnable() { @Override public void run() { // we set busy myBC7001.getOutput(0).setAmount(1); } } , 5); // if the cart is stopped, start it if (this.getVehicle().getVelocity().equals(new Vector(0,0,0))) { if (((Minecart) this.getVehicle()).getMaxSpeed() == 0) ((Minecart) this.getVehicle()).setMaxSpeed(0.4d); this.getVehicle().setVelocity((new Vector(this.getCardinal().getModX(), this.getCardinal().getModY(), this.getCardinal().getModZ())).multiply(ByteCart.myPlugin.getConfig().getDouble("BC7001.startvelocity"))); } } // if the wire is off else { // stop the cart if this is not a train and tells to the previous block that we are stopped if(!this.wasTrain(getLocation())) { // the lever is off this.getOutput(0).setAmount(0); this.getVehicle().setVelocity(new Vector(0,0,0)); ((Minecart) this.getVehicle()).setMaxSpeed(0d); ByteCart.myPlugin.getIsTrainManager().getMap().remove(getBlock().getRelative(getCardinal().getOppositeFace(), 2).getLocation()); } else ByteCart.myPlugin.getIsTrainManager().getMap().reset(this.getLocation()); /* if(ByteCart.debug) ByteCart.log.info("ByteCart: BC7001 : cart on stop at " + this.Vehicle.getLocation().toString()); */ } // if this is the first car of a train // we keep it during 2 s } // there is no minecart above else { // the lever is on this.getOutput(0).setAmount(1); } } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Powerable#power() */ @Override public void power() { // power update // We need to find if a cart is stopped and set the member variable Vehicle org.bukkit.block.Block block = this.getBlock().getRelative(BlockFace.UP, 2); Location loc = block.getLocation(); BlockData rail; // if the rail is in slope, the cart is 1 block up if ((rail = block.getState().getBlockData()) instanceof Rail && MathUtil.isOnSlope((Rail) rail)) { loc.add(0, 1, 0); } final Triggable bc = TriggeredSignFactory.getTriggeredIC(this.getBlock(),MathUtil.getVehicleByLocation(loc)); if (bc != null) { ByteCart.myPlugin.getServer().getScheduler().scheduleSyncDelayedTask(ByteCart.myPlugin, new Runnable() { @Override public void run() { bc.trigger(); } } , 1); } else this.trigger(); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public final String getName() { return "BC7001"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "Stop/Start"; } }
5,349
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC9037.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC9037.java
package com.github.catageek.ByteCart.Signs; /** * Match IP ranges. * * 1. Empty * 2. [BC9037] * 3. AA.BB.CC * 4. XX.YY.ZZ * * onState <=> AA.BB.CC <= IP <= XX.YY.ZZ */ final class BC9037 extends AbstractBC9037 { BC9037(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractBC9037#negated() */ @Override protected boolean negated() { return false; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#getName() */ @Override public final String getName() { return "BC9037"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "Range matcher"; } }
827
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
Triggable.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/Triggable.java
package com.github.catageek.ByteCart.Signs; import java.io.IOException; import org.bukkit.Location; import com.github.catageek.ByteCartAPI.HAL.IC; /** * An IC that can be triggered by a cart should implement this */ public interface Triggable extends IC { /** * Method called when a cart is passing on the IC * * @throws ClassNotFoundException * @throws IOException */ public void trigger(); /** * Tell if the cart that triggers this IC has the train bit set, i.e is the head of a train * * @return true if the train bit is set */ public boolean isTrain(); /** * Tell if the IC was previously triggered by a cart with the train bit set * * This method retrieves the persistent value stored in a map. * * The value retrieved has a timeout, i.e the method will return false after a while. * * @param loc the location of the IC * @return true if a train is currently using the IC */ public boolean wasTrain(Location loc); /** * Tell if the lever is negated * @return true if it is negated */ public boolean isLeverReversed(); }
1,091
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
AbstractBC9037.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/AbstractBC9037.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.CollisionManagement.IntersectionSide; import com.github.catageek.ByteCartAPI.HAL.RegistryBoth; import com.github.catageek.ByteCartAPI.HAL.RegistryInput; /** * Match IP ranges. * * Example sign content: * 1. Empty * 2. [BCxxxx] * 3. AA.BB.CC * 4. XX.YY.ZZ * * Line 3 and 4 name the start and end of the range respectively. * There are two possible implementations: normal and negated. * * - Example on-state with normal implementation and configuration from above: * onState <=> AA.BB.CC <= IP <= XX.YY.ZZ * * - Example on-state with negated implementation and configuration from above: * onState <=> !(AA.BB.CC <= IP <= XX.YY.ZZ) */ abstract class AbstractBC9037 extends AbstractSimpleCrossroad implements Triggable { AbstractBC9037(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /** * * @return True if the sign uses the negated result of @{@link #isAddressMatching()}. */ protected abstract boolean negated(); @Override protected void addIO() { super.addIO(); // add input [0] to [2] from vehicle addIOInv(); // add input [3], [4] and [5] from 4th line this.addAddressAsInputs(AddressFactory.getAddress(getBlock(), 3)); // add input [6], [7] and [8] from 3th line this.addAddressAsInputs(AddressFactory.getAddress(getBlock(), 2)); } /** * Utility method to check whether a integer is between lower bound l and upper bound u. */ private boolean in(int l, int v, int u) { return l <= v && v <= u; } /** * Check if the vehicle IP is in the configured range. * * The return value depends on the return value of @{@link #negated()}. * The result is negated if said method returns true. * */ private boolean isAddressMatching() { try { int startRegion = getInput(6).getAmount(); int region = getInput(0).getAmount(); int endRegion = getInput(3).getAmount(); int startTrack = getInput(7).getAmount(); int track = getInput(1).getAmount(); int endTrack = getInput(4).getAmount(); int startStation = getInput(8).getAmount(); int station = getInput(2).getAmount(); int endStation = getInput(5).getAmount(); boolean value = in(startRegion, region, endRegion) && in(startTrack, track, endTrack) && in(startStation, station, endStation); if(negated()) return !value; return value; } catch (NullPointerException e) { // There is no address on sign } return false; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#route() */ @Override protected IntersectionSide.Side route() { if (! ByteCart.myPlugin.getWandererManager().isWanderer(getInventory()) && this.isAddressMatching()) return IntersectionSide.Side.LEVER_ON; return IntersectionSide.Side.LEVER_OFF; } private void addAddressAsInputs(Address addr) { if(addr.isValid()) { RegistryInput region = addr.getRegion(); this.addInputRegistry(region); RegistryInput track = addr.getTrack(); this.addInputRegistry(track); RegistryBoth station = addr.getStation(); this.addInputRegistry(station); } } }
3,363
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC8010.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC8010.java
package com.github.catageek.ByteCart.Signs; import java.io.IOException; import org.bukkit.Bukkit; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCart.AddressLayer.AddressFactory; import com.github.catageek.ByteCart.AddressLayer.AddressRouted; import com.github.catageek.ByteCart.AddressLayer.ReturnAddressFactory; import com.github.catageek.ByteCart.CollisionManagement.CollisionAvoiderBuilder; import com.github.catageek.ByteCart.CollisionManagement.Router; import com.github.catageek.ByteCart.CollisionManagement.RouterCollisionAvoiderBuilder; import com.github.catageek.ByteCart.Routing.RoutingTableFactory; import com.github.catageek.ByteCart.Routing.RoutingTableWritable; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.Event.SignPostRouteEvent; import com.github.catageek.ByteCartAPI.Event.SignPreRouteEvent; import com.github.catageek.ByteCartAPI.Event.UpdaterPassRouterEvent; import com.github.catageek.ByteCartAPI.Signs.BCRouter; import com.github.catageek.ByteCartAPI.Util.MathUtil; import com.github.catageek.ByteCartAPI.Wanderer.AbstractWanderer; import com.github.catageek.ByteCartAPI.Wanderer.Wanderer; import com.google.gson.JsonSyntaxException; /** * An IC at the entry of a L1 router */ public class BC8010 extends AbstractTriggeredSign implements BCRouter, Triggable, HasRoutingTable { private final BlockFace From; private final Address Sign; private final RoutingTableWritable RoutingTable; private AddressRouted destination; private final Block center; protected boolean IsTrackNumberProvider; private boolean IsOldVersion = true; BC8010(Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.IsTrackNumberProvider = true; From = this.getCardinal().getOppositeFace(); // reading destination address of the cart if (selectWanderer()) { destination = AddressFactory.getAddress(this.getInventory()); if (destination == null) { destination = AddressFactory.getDefaultTicket(this.getInventory()); } } // reading address written on BC8010 sign Sign = AddressFactory.getAddress(this.getBlock(),3); // Center of the router, at sign level center = this.getBlock().getRelative(this.getCardinal(), 6).getRelative(MathUtil.clockwise(this.getCardinal())); this.RoutingTable = loadChest(); } protected RoutingTableWritable loadChest() { BlockState blockstate; if ((blockstate = center.getRelative(BlockFace.UP, 5).getState()) instanceof InventoryHolder) { // Loading inventory of chest above router Inventory ChestInventory = ((InventoryHolder) blockstate).getInventory(); // Converting inventory in routing table try { return RoutingTableFactory.getRoutingTable(ChestInventory, 0); } catch (JsonSyntaxException | ClassNotFoundException | IOException e) { ByteCart.log.info("ByteCart: Error while loading chest at position " + this.center.getLocation() + ". Please clean its content and run bcupdater region command."); return null; } } else if ((blockstate = center.getRelative(BlockFace.DOWN, 2).getState()) instanceof InventoryHolder) { // Loading inventory of chest above router Inventory ChestInventory = ((InventoryHolder) blockstate).getInventory(); // Converting inventory in routing table try { return RoutingTableFactory.getRoutingTable(ChestInventory, 0); } catch (JsonSyntaxException | ClassNotFoundException | IOException e) { ByteCart.log.info("ByteCart: Error while loading chest at position " + this.center.getLocation() + ". Please clean its content and run bcupdater region command."); return null; } } else { return null; } } BC8010(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle, boolean isOldVersion) { this(block, vehicle); this.IsOldVersion = isOldVersion; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { CollisionAvoiderBuilder builder = new RouterCollisionAvoiderBuilder(this, center.getLocation(), this.IsOldVersion); try { BlockFace direction, to; Router router = ByteCart.myPlugin.getCollisionAvoiderManager().<Router>getCollisionAvoider(builder); boolean isTrain = AbstractTriggeredSign.isTrain(destination); // Here begins the triggered action if(ByteCart.debug) { ByteCart.log.info("Router world: " + center.getWorld().getName()); ByteCart.log.info("Router location: X: " + center.getX() + " Y: " + center.getY() + " Z: " + center.getZ()); } // is this an wanderer who needs special routing ? no then routing normally if(selectWanderer()) { // if this is a cart in a train if (this.wasTrain(this.getLocation())) { // leave a message to next cart that it is a train ByteCart.myPlugin.getIsTrainManager().getMap().reset(getLocation()); // tell to router not to change position ByteCart.myPlugin.getCollisionAvoiderManager().<Router>getCollisionAvoider(builder).Book(isTrain); return; } if (destination != null) { // Time-to-live management //loading TTl of cart int ttl = destination.getTTL(); // if ttl did not reach end of life ( = 0) if (ttl != 0) { destination.updateTTL(ttl-1); } // if ttl was 1 (now 0), we try to return the cart to source station if (ttl == 1 && tryReturnCart()) destination = AddressFactory.getAddress(this.getInventory()); if(ByteCart.debug) { ByteCart.log.info("ByteCart : TTL is " + destination.getTTL()); } // if this is the first car of a train // we keep it during 2 s if (isTrain) { this.setWasTrain(this.getLocation(), true); } destination.finalizeAddress(); } direction = this.SelectRoute(destination, Sign, RoutingTable); // trigger event BlockFace bdest = router.WishToGo(From, direction, isTrain); int ring = this.getRoutingTable().getDirectlyConnected(bdest); SignPostRouteEvent event = new SignPostRouteEvent(this, ring); Bukkit.getServer().getPluginManager().callEvent(event); return; } // it's a wanderer, so let it choosing direction Wanderer wanderer = null; try { wanderer = getWanderer(); } catch (ClassNotFoundException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // routing normally to = router.WishToGo(From, wanderer.giveRouterDirection(), isTrain); if (ByteCart.myPlugin.getWandererManager().isWanderer(getInventory(), "Updater")) { int nextring = this.getRoutingTable().getDirectlyConnected(to); UpdaterPassRouterEvent event = new UpdaterPassRouterEvent(wanderer, to, nextring); Bukkit.getServer().getPluginManager().callEvent(event); } // here we perform routes update wanderer.doAction(to); } catch (ClassCastException e) { if(ByteCart.debug) ByteCart.log.info("ByteCart : " + e.toString()); e.printStackTrace(); // Not the good blocks to build the signs return; } catch (NullPointerException e) { if(ByteCart.debug) ByteCart.log.info("ByteCart : "+ e.toString()); e.printStackTrace(); // there was no inventory in the cart return; } } /** * Tells if this cart needs normal routing * @return true if the cart needs normal routing */ protected boolean selectWanderer() { // everything that is not an wanderer must be routed return ! ByteCart.myPlugin.getWandererManager().isWanderer(getInventory()); } /** * Compute the direction to take * * @param IPaddress the destination address * @param sign the BC sign * @param RoutingTableWritable the routing table contained in the chest * @return the direction to destination, or to ring 0. If ring 0 does not exist, random direction */ protected BlockFace SelectRoute(AddressRouted IPaddress, Address sign, RoutingTableWritable RoutingTable) { BlockFace face; // same region : lookup destination track if (IPaddress != null && IPaddress.getRegion().getAmount() == sign.getRegion().getAmount() && IPaddress.getTTL() != 0) { int destination = this.destination.getTrack().getAmount(); BlockFace out = RoutingTable.getAllowedDirection(destination); if (out != null) { // trigger event SignPreRouteEvent event = new SignPreRouteEvent(this, this.getRoutingTable().getDirectlyConnected(out)); Bukkit.getServer().getPluginManager().callEvent(event); return RoutingTable.getDirection(event.getTargetTrack()); } } // If not in same region, or if TTL is 0, or the ring does not exist then we lookup track 0 if ((face = RoutingTable.getAllowedDirection(0)) != null) return face; // If everything has failed, then we randomize output direction return AbstractWanderer.getRandomBlockFace(RoutingTable, getCardinal().getOppositeFace()); } /** * Try to send the cart to its return address * * @return true if success */ private boolean tryReturnCart() { Address returnAddress = ReturnAddressFactory.getAddress(this.getInventory()); if (returnAddress != null && returnAddress.isReturnable()) { (new BC7017(this.getBlock(), this.getVehicle())).trigger(); return true; } return false; } /** * Get the wanderer object * * @return the wanderer * @throws ClassNotFoundException * @throws IOException */ private final Wanderer getWanderer() throws ClassNotFoundException, IOException { return ByteCart.myPlugin.getWandererManager().getFactory(this.getInventory()).getWanderer(this, this.getInventory()); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BCSign#getLevel() */ @Override public Wanderer.Level getLevel() { return Wanderer.Level.REGION; } /** * Return the direction from where the cart is coming * * @return the direction */ @Override public final BlockFace getFrom() { return From; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BCSign#getSignAddress() */ @Override public final Address getSignAddress() { return Sign; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.HasRoutingTable#getRoutingTable() */ @Override public final RoutingTableWritable getRoutingTable() { return RoutingTable; } /** * Tell if this IC will provide track numbers during configuration * * @return true if the IC provides track number */ public final boolean isTrackNumberProvider() { return IsTrackNumberProvider; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BCSign#getDestinationIP() */ @Override public final String getDestinationIP() { return destination.toString(); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BCRouter#getOriginTrack() */ @Override public final int getOriginTrack() { return Sign.getTrack().getAmount(); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.BCSign#getCenter() */ @Override public final Block getCenter() { return center; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC8010"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "L1 Router"; } }
11,482
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC9008.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC9008.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCartAPI.Signs.HasNetmask; import com.github.catageek.ByteCartAPI.Signs.Subnet; /** * A 8-station subnet bound */ final class BC9008 extends AbstractBC9000 implements Subnet,HasNetmask, Triggable { BC9008(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.netmask = 5; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#getName() */ @Override public final String getName() { return "BC9008"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "8-station subnet"; } }
750
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7006.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7006.java
/** * */ package com.github.catageek.ByteCart.Signs; import org.bukkit.entity.Minecart; import com.github.catageek.ByteCartAPI.Util.MathUtil; /** * A booster */ final class BC7006 extends AbstractTriggeredSign implements Triggable { /** * @param block * @param vehicle */ public BC7006(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { org.bukkit.entity.Vehicle vehicle = this.getVehicle(); Minecart cart = (Minecart) vehicle; if (cart.getMaxSpeed() <= 0.4D) cart.setMaxSpeed(0.68D); MathUtil.setSpeed(cart, 0.68D); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC7006"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Booster"; } }
1,036
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC9002.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC9002.java
package com.github.catageek.ByteCart.Signs; import com.github.catageek.ByteCartAPI.Signs.HasNetmask; import com.github.catageek.ByteCartAPI.Signs.Subnet; /** * A 2-station subnet bound */ final class BC9002 extends AbstractBC9000 implements Subnet,HasNetmask, Triggable { BC9002(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); this.netmask = 7; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.AbstractSimpleCrossroad#getName() */ @Override public final String getName() { return "BC9002"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public final String getFriendlyName() { return "2-station subnet"; } }
754
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
BC7005.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/Signs/BC7005.java
/** * */ package com.github.catageek.ByteCart.Signs; /** * An eject sign */ final class BC7005 extends AbstractTriggeredSign implements Triggable { /** * @param block * @param vehicle */ public BC7005(org.bukkit.block.Block block, org.bukkit.entity.Vehicle vehicle) { super(block, vehicle); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.Signs.Triggable#trigger() */ @Override public void trigger() { if (this.getVehicle() != null) this.getVehicle().eject(); } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getName() */ @Override public String getName() { return "BC7005"; } /* (non-Javadoc) * @see com.github.catageek.ByteCart.HAL.AbstractIC#getFriendlyName() */ @Override public String getFriendlyName() { return "Eject"; } }
817
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
ByteCartUpdaterMoveListener.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/EventManagement/ByteCartUpdaterMoveListener.java
package com.github.catageek.ByteCart.EventManagement; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Vehicle; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.vehicle.VehicleMoveEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCartAPI.Event.UpdaterMoveEvent; import com.github.catageek.ByteCartAPI.Event.UpdaterRemoveEvent; /** * Launch an event when an updater moves * This listener unregisters itself automatically if there is no updater */ public class ByteCartUpdaterMoveListener implements Listener { // flag for singleton private static boolean exist = false; @EventHandler(ignoreCancelled = true) public void onVehicleMoveEvent(VehicleMoveEvent event) { Location loc = event.getFrom(); Integer from_x = loc.getBlockX(); Integer from_z = loc.getBlockZ(); loc = event.getTo(); int to_x = loc.getBlockX(); int to_z = loc.getBlockZ(); // Check if the vehicle crosses a cube boundary if(from_x == to_x && from_z == to_z) return; // no boundary crossed, resumed Vehicle v = event.getVehicle(); // reset the timer if (v instanceof InventoryHolder) { Inventory inv = ((InventoryHolder) v).getInventory(); if (ByteCart.myPlugin.getWandererManager().isWanderer(inv, "Updater")) { Bukkit.getServer().getPluginManager().callEvent(new UpdaterMoveEvent(event)); return; } } if (ByteCart.myPlugin.getWandererManager().getFactory("Updater").areAllRemoved()) { removeListener(); } } /** * Detect a destroyed updater * * @param event */ @EventHandler(ignoreCancelled = true) public void onVehicleDestroy(VehicleDestroyEvent event) { Vehicle v = event.getVehicle(); if (v instanceof InventoryHolder) { Inventory inv = ((InventoryHolder) v).getInventory(); if (ByteCart.myPlugin.getWandererManager().isWanderer(inv, "Updater")) { ByteCart.myPlugin.getWandererManager().getFactory("Updater").destroyWanderer(inv); Bukkit.getServer().getPluginManager().callEvent(new UpdaterRemoveEvent(v.getEntityId())); } } } private void removeListener() { HandlerList.unregisterAll(this); setExist(false); } /** * @return the exist */ public static boolean isExist() { return exist; } /** * @param exist the exist to set */ public static void setExist(boolean exist) { ByteCartUpdaterMoveListener.exist = exist; } }
2,608
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z